/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
6046.2.3 by Shannon Weyrick
Add get_user_option_as_int_from_SI, for retrieving an integer
1058
    def test_get_user_option_as_int_from_SI(self):
1059
        conf, parser = self.make_config_parser("""
1060
plain = 100
1061
si_k = 5k,
1062
si_kb = 5kb,
1063
si_m = 5M,
1064
si_mb = 5MB,
1065
si_g = 5g,
1066
si_gb = 5gB,
1067
""")
1068
        get_si = conf.get_user_option_as_int_from_SI
1069
        self.assertEqual(100, get_si('plain'))
1070
        self.assertEqual(5000, get_si('si_k'))
1071
        self.assertEqual(5000, get_si('si_kb'))
1072
        self.assertEqual(5000000, get_si('si_m'))
1073
        self.assertEqual(5000000, get_si('si_mb'))
1074
        self.assertEqual(5000000000, get_si('si_g'))
1075
        self.assertEqual(5000000000, get_si('si_gb'))
1076
        self.assertEqual(None, get_si('non-exist'))
1077
        self.assertEqual(42, get_si('non-exist-with-default',  42))
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
1078
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
1079
class TestSupressWarning(TestIniConfig):
1080
1081
    def make_warnings_config(self, s):
1082
        conf, parser = self.make_config_parser(s)
1083
        return conf.suppress_warning
1084
1085
    def test_suppress_warning_unknown(self):
1086
        suppress_warning = self.make_warnings_config('')
1087
        self.assertEqual(False, suppress_warning('unknown_warning'))
1088
1089
    def test_suppress_warning_known(self):
1090
        suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
1091
        self.assertEqual(False, suppress_warning('c'))
1092
        self.assertEqual(True, suppress_warning('a'))
1093
        self.assertEqual(True, suppress_warning('b'))
1094
1095
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1096
class TestGetConfig(tests.TestCase):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1097
1098
    def test_constructs(self):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1099
        my_config = config.GlobalConfig()
1100
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1101
    def test_calls_read_filenames(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1102
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
1103
        oldparserclass = config.ConfigObj
1104
        config.ConfigObj = InstrumentedConfigObj
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1105
        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.
1106
        try:
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1107
            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.
1108
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
1109
            config.ConfigObj = oldparserclass
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1110
        self.assertIsInstance(parser, InstrumentedConfigObj)
1551.2.20 by Aaron Bentley
Treated config files as utf-8
1111
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
1112
                                          '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.
1113
1114
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1115
class TestBranchConfig(tests.TestCaseWithTransport):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1116
1117
    def test_constructs(self):
1118
        branch = FakeBranch()
1119
        my_config = config.BranchConfig(branch)
1120
        self.assertRaises(TypeError, config.BranchConfig)
1121
1122
    def test_get_location_config(self):
1123
        branch = FakeBranch()
1124
        my_config = config.BranchConfig(branch)
1125
        location_config = my_config._get_location_config()
1126
        self.assertEqual(branch.base, location_config.location)
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1127
        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
1128
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
1129
    def test_get_config(self):
1130
        """The Branch.get_config method works properly"""
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1131
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
1132
        my_config = b.get_config()
1133
        self.assertIs(my_config.get_user_option('wacky'), None)
1134
        my_config.set_user_option('wacky', 'unlikely')
1135
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
1136
1137
        # Ensure we get the same thing if we start again
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1138
        b2 = branch.Branch.open('.')
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
1139
        my_config2 = b2.get_config()
1140
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
1141
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
1142
    def test_has_explicit_nickname(self):
1143
        b = self.make_branch('.')
1144
        self.assertFalse(b.get_config().has_explicit_nickname())
1145
        b.nick = 'foo'
1146
        self.assertTrue(b.get_config().has_explicit_nickname())
1147
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1148
    def test_config_url(self):
1149
        """The Branch.get_config will use section that uses a local url"""
1150
        branch = self.make_branch('branch')
1151
        self.assertEqual('branch', branch.nick)
1152
1153
        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
1154
        conf = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1155
            '[%s]\nnickname = foobar' % (local_url,),
1156
            local_url, save=True)
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1157
        self.assertEqual('foobar', branch.nick)
1158
1159
    def test_config_local_path(self):
1160
        """The Branch.get_config will use a local system path"""
1161
        branch = self.make_branch('branch')
1162
        self.assertEqual('branch', branch.nick)
1163
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1164
        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
1165
        conf = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1166
            '[%s/branch]\nnickname = barry' % (local_path,),
1167
            'branch',  save=True)
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1168
        self.assertEqual('barry', branch.nick)
1169
1878.1.2 by John Arbash Meinel
Add a test that new locations.conf entries are created with a local path, rather than a URL
1170
    def test_config_creates_local(self):
1171
        """Creating a new entry in config uses a local path."""
2230.3.6 by Aaron Bentley
work in progress bind stuff
1172
        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
1173
        branch.set_push_location('http://foobar')
1174
        local_path = osutils.getcwd().encode('utf8')
1175
        # Surprisingly ConfigObj doesn't create a trailing newline
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1176
        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.
1177
                                 '[%s/branch]\n'
1178
                                 'push_location = http://foobar\n'
3221.7.1 by Matt Nordhoff
Upgrade ConfigObj to version 4.5.1.
1179
                                 'push_location:policy = norecurse\n'
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1180
                                 % (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
1181
2120.5.4 by Alexander Belchenko
Whitebox test for Config.get_nickname (req. by Aaron Bentley)
1182
    def test_autonick_urlencoded(self):
1183
        b = self.make_branch('!repo')
1184
        self.assertEqual('!repo', b.get_config().get_nickname())
1185
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1186
    def test_warn_if_masked(self):
1187
        warnings = []
1188
        def warning(*args):
1189
            warnings.append(args[0] % args[1:])
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1190
        self.overrideAttr(trace, 'warning', warning)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1191
1192
        def set_option(store, warn_masked=True):
1193
            warnings[:] = []
1194
            conf.set_user_option('example_option', repr(store), store=store,
1195
                                 warn_masked=warn_masked)
1196
        def assertWarning(warning):
1197
            if warning is None:
1198
                self.assertEqual(0, len(warnings))
1199
            else:
1200
                self.assertEqual(1, len(warnings))
1201
                self.assertEqual(warning, warnings[0])
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1202
        branch = self.make_branch('.')
1203
        conf = branch.get_config()
1204
        set_option(config.STORE_GLOBAL)
1205
        assertWarning(None)
1206
        set_option(config.STORE_BRANCH)
1207
        assertWarning(None)
1208
        set_option(config.STORE_GLOBAL)
1209
        assertWarning('Value "4" is masked by "3" from branch.conf')
1210
        set_option(config.STORE_GLOBAL, warn_masked=False)
1211
        assertWarning(None)
1212
        set_option(config.STORE_LOCATION)
1213
        assertWarning(None)
1214
        set_option(config.STORE_BRANCH)
1215
        assertWarning('Value "3" is masked by "0" from locations.conf')
1216
        set_option(config.STORE_BRANCH, warn_masked=False)
1217
        assertWarning(None)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1218
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1219
5448.1.1 by Vincent Ladeuil
Use TestCaseInTempDir for tests requiring disk resources
1220
class TestGlobalConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1221
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1222
    def test_user_id(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1223
        my_config = config.GlobalConfig.from_string(sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1224
        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
1225
                         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.
1226
1227
    def test_absent_user_id(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1228
        my_config = config.GlobalConfig()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1229
        self.assertEqual(None, my_config._get_user_id())
1230
1231
    def test_configured_editor(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1232
        my_config = config.GlobalConfig.from_string(sample_config_text)
5743.13.1 by Vincent Ladeuil
Deprecate _get_editor to identify its usages.
1233
        editor = self.applyDeprecated(
1234
            deprecated_in((2, 4, 0)), my_config.get_editor)
1235
        self.assertEqual('vim', editor)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1236
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
1237
    def test_signatures_always(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1238
        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
1239
        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
1240
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1241
        self.assertEqual(config.SIGN_ALWAYS,
1242
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1243
        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
1244
1245
    def test_signatures_if_possible(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1246
        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
1247
        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
1248
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1249
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
1250
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1251
        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
1252
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1253
    def test_signatures_ignore(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1254
        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
1255
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1256
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1257
        self.assertEqual(config.SIGN_NEVER,
1258
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1259
        self.assertEqual(False, my_config.signature_needed())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1260
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1261
    def _get_sample_config(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1262
        my_config = config.GlobalConfig.from_string(sample_config_text)
1534.7.154 by Aaron Bentley
Removed changes from bzr.ab 1529..1536
1263
        return my_config
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1264
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1265
    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.
1266
        my_config = self._get_sample_config()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1267
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
1268
        self.assertEqual(False, my_config.signature_needed())
1269
6012.2.3 by Jonathan Riddell
add config option for signing key
1270
    def test_gpg_signing_key(self):
1271
        my_config = self._get_sample_config()
6012.2.11 by Jonathan Riddell
rename config option signing_key to gpg_signing_key
1272
        self.assertEqual("DD4D5088", my_config.gpg_signing_key())
6012.2.3 by Jonathan Riddell
add config option for signing key
1273
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1274
    def _get_empty_config(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1275
        my_config = config.GlobalConfig()
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1276
        return my_config
1277
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
1278
    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.
1279
        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.
1280
        self.assertEqual("gpg", my_config.gpg_signing_command())
1281
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1282
    def test_get_user_option_default(self):
1283
        my_config = self._get_empty_config()
1284
        self.assertEqual(None, my_config.get_user_option('no_option'))
1285
1286
    def test_get_user_option_global(self):
1287
        my_config = self._get_sample_config()
1288
        self.assertEqual("something",
1289
                         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.
1290
1472 by Robert Collins
post commit hook, first pass implementation
1291
    def test_post_commit_default(self):
1292
        my_config = self._get_sample_config()
1293
        self.assertEqual(None, my_config.post_commit())
1294
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
1295
    def test_configured_logformat(self):
1553.2.8 by Erik BÃ¥gfors
tests for config log_formatter
1296
        my_config = self._get_sample_config()
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
1297
        self.assertEqual("short", my_config.log_format())
1553.2.8 by Erik BÃ¥gfors
tests for config log_formatter
1298
5971.1.58 by Jonathan Riddell
more tests for new config options
1299
    def test_configured_acceptable_keys(self):
1300
        my_config = self._get_sample_config()
1301
        self.assertEqual("amy", my_config.acceptable_keys())
1302
1303
    def test_configured_validate_signatures_in_log(self):
1304
        my_config = self._get_sample_config()
1305
        self.assertEqual(True, my_config.validate_signatures_in_log())
1306
1553.6.12 by Erik BÃ¥gfors
remove AliasConfig, based on input from abentley
1307
    def test_get_alias(self):
1308
        my_config = self._get_sample_config()
1309
        self.assertEqual('help', my_config.get_alias('h'))
1310
2900.3.6 by Tim Penhey
Added tests.
1311
    def test_get_aliases(self):
1312
        my_config = self._get_sample_config()
1313
        aliases = my_config.get_aliases()
1314
        self.assertEqual(2, len(aliases))
1315
        sorted_keys = sorted(aliases)
1316
        self.assertEqual('help', aliases[sorted_keys[0]])
1317
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
1318
1553.6.12 by Erik BÃ¥gfors
remove AliasConfig, based on input from abentley
1319
    def test_get_no_alias(self):
1320
        my_config = self._get_sample_config()
1321
        self.assertEqual(None, my_config.get_alias('foo'))
1322
1323
    def test_get_long_alias(self):
1324
        my_config = self._get_sample_config()
1325
        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.
1326
4603.1.10 by Aaron Bentley
Provide change editor via config.
1327
    def test_get_change_editor(self):
1328
        my_config = self._get_sample_config()
1329
        change_editor = my_config.get_change_editor('old', 'new')
1330
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
1331
        self.assertEqual('vimdiff -of @new_path @old_path',
4603.1.10 by Aaron Bentley
Provide change editor via config.
1332
                         ' '.join(change_editor.command_template))
1333
1334
    def test_get_no_change_editor(self):
1335
        my_config = self._get_empty_config()
1336
        change_editor = my_config.get_change_editor('old', 'new')
1337
        self.assertIs(None, change_editor)
1338
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
1339
    def test_get_merge_tools(self):
1340
        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.
1341
        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.
1342
        self.log(repr(tools))
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1343
        self.assertEqual(
1344
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
1345
            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.
1346
            tools)
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
1347
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1348
    def test_get_merge_tools_empty(self):
5321.1.93 by Gordon Tyler
Added tests for get_default_merge_tool.
1349
        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.
1350
        tools = conf.get_merge_tools()
1351
        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.
1352
1353
    def test_find_merge_tool(self):
1354
        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.
1355
        cmdline = conf.find_merge_tool('sometool')
1356
        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.
1357
1358
    def test_find_merge_tool_not_found(self):
1359
        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.
1360
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
1361
        self.assertIs(cmdline, None)
5321.1.93 by Gordon Tyler
Added tests for get_default_merge_tool.
1362
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.
1363
    def test_find_merge_tool_known(self):
1364
        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.
1365
        cmdline = conf.find_merge_tool('kdiff3')
1366
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
1367
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.
1368
    def test_find_merge_tool_override_known(self):
1369
        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.
1370
        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.
1371
        cmdline = conf.find_merge_tool('kdiff3')
1372
        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.
1373
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1374
2900.3.6 by Tim Penhey
Added tests.
1375
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
1376
1377
    def test_empty(self):
1378
        my_config = config.GlobalConfig()
1379
        self.assertEqual(0, len(my_config.get_aliases()))
1380
1381
    def test_set_alias(self):
1382
        my_config = config.GlobalConfig()
1383
        alias_value = 'commit --strict'
1384
        my_config.set_alias('commit', alias_value)
1385
        new_config = config.GlobalConfig()
1386
        self.assertEqual(alias_value, new_config.get_alias('commit'))
1387
1388
    def test_remove_alias(self):
1389
        my_config = config.GlobalConfig()
1390
        my_config.set_alias('commit', 'commit --strict')
1391
        # Now remove the alias again.
1392
        my_config.unset_alias('commit')
1393
        new_config = config.GlobalConfig()
1394
        self.assertIs(None, new_config.get_alias('commit'))
1395
1396
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1397
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1398
1399
    def test_constructs(self):
1400
        my_config = config.LocationConfig('http://example.com')
1401
        self.assertRaises(TypeError, config.LocationConfig)
1402
1403
    def test_branch_calls_read_filenames(self):
1474 by Robert Collins
Merge from Aaron Bentley.
1404
        # This is testing the correct file names are provided.
1405
        # TODO: consolidate with the test for GlobalConfigs filename checks.
1406
        #
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1407
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
1408
        oldparserclass = config.ConfigObj
1409
        config.ConfigObj = InstrumentedConfigObj
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1410
        try:
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1411
            my_config = config.LocationConfig('http://www.example.com')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1412
            parser = my_config._get_parser()
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1413
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
1414
            config.ConfigObj = oldparserclass
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1415
        self.assertIsInstance(parser, InstrumentedConfigObj)
1474 by Robert Collins
Merge from Aaron Bentley.
1416
        self.assertEqual(parser._calls,
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1417
                         [('__init__', config.locations_config_filename(),
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1418
                           'utf-8')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1419
1420
    def test_get_global_config(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1421
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1422
        global_config = my_config._get_global_config()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1423
        self.assertIsInstance(global_config, config.GlobalConfig)
1424
        self.assertIs(global_config, my_config._get_global_config())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1425
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1426
    def assertLocationMatching(self, expected):
1427
        self.assertEqual(expected,
1428
                         list(self.my_location_config._get_matching_sections()))
1429
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1430
    def test__get_matching_sections_no_match(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1431
        self.get_branch_config('/')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1432
        self.assertLocationMatching([])
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1433
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1434
    def test__get_matching_sections_exact(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1435
        self.get_branch_config('http://www.example.com')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1436
        self.assertLocationMatching([('http://www.example.com', '')])
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1437
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1438
    def test__get_matching_sections_suffix_does_not(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1439
        self.get_branch_config('http://www.example.com-com')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1440
        self.assertLocationMatching([])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1441
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1442
    def test__get_matching_sections_subdir_recursive(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1443
        self.get_branch_config('http://www.example.com/com')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1444
        self.assertLocationMatching([('http://www.example.com', 'com')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1445
1993.3.5 by James Henstridge
add back recurse=False option to config file
1446
    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
1447
        self.get_branch_config('http://www.example.com/ignoreparent')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1448
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1449
                                      '')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1450
1993.3.5 by James Henstridge
add back recurse=False option to config file
1451
    def test__get_matching_sections_ignoreparent_subdir(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1452
        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
1453
            'http://www.example.com/ignoreparent/childbranch')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1454
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1455
                                      'childbranch')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1456
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1457
    def test__get_matching_sections_subdir_trailing_slash(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1458
        self.get_branch_config('/b')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1459
        self.assertLocationMatching([('/b/', '')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1460
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1461
    def test__get_matching_sections_subdir_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1462
        self.get_branch_config('/a/foo')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1463
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1464
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1465
    def test__get_matching_sections_subdir_child_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1466
        self.get_branch_config('/a/foo/bar')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1467
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1468
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1469
    def test__get_matching_sections_trailing_slash_with_children(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1470
        self.get_branch_config('/a/')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1471
        self.assertLocationMatching([('/a/', '')])
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1472
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1473
    def test__get_matching_sections_explicit_over_glob(self):
1474
        # XXX: 2006-09-08 jamesh
1475
        # This test only passes because ord('c') > ord('*').  If there
1476
        # was a config section for '/a/?', it would get precedence
1477
        # over '/a/c'.
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1478
        self.get_branch_config('/a/c')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1479
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1480
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
1481
    def test__get_option_policy_normal(self):
1482
        self.get_branch_config('http://www.example.com')
1483
        self.assertEqual(
1484
            self.my_location_config._get_config_policy(
1485
            'http://www.example.com', 'normal_option'),
1486
            config.POLICY_NONE)
1487
1488
    def test__get_option_policy_norecurse(self):
1489
        self.get_branch_config('http://www.example.com')
1490
        self.assertEqual(
1491
            self.my_location_config._get_option_policy(
1492
            'http://www.example.com', 'norecurse_option'),
1493
            config.POLICY_NORECURSE)
1494
        # Test old recurse=False setting:
1495
        self.assertEqual(
1496
            self.my_location_config._get_option_policy(
1497
            'http://www.example.com/norecurse', 'normal_option'),
1498
            config.POLICY_NORECURSE)
1499
1500
    def test__get_option_policy_normal(self):
1501
        self.get_branch_config('http://www.example.com')
1502
        self.assertEqual(
1503
            self.my_location_config._get_option_policy(
1504
            'http://www.example.com', 'appendpath_option'),
1505
            config.POLICY_APPENDPATH)
1506
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1507
    def test__get_options_with_policy(self):
1508
        self.get_branch_config('/dir/subdir',
1509
                               location_config="""\
1510
[/dir]
1511
other_url = /other-dir
1512
other_url:policy = appendpath
1513
[/dir/subdir]
1514
other_url = /other-subdir
1515
""")
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1516
        self.assertOptions(
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1517
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
1518
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
1519
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1520
            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.
1521
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1522
    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
1523
        self.get_branch_config('http://www.example.com/ignoreparent')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1524
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1525
                         self.my_config.username())
1526
1527
    def test_location_not_listed(self):
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1528
        """Test that the global username is used when no location matches"""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1529
        self.get_branch_config('/home/robertc/sources')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1530
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1531
                         self.my_config.username())
1532
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
1533
    def test_overriding_location(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1534
        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
1535
        self.assertEqual('Robert Collins <robertc@example.org>',
1536
                         self.my_config.username())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1537
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1538
    def test_signatures_not_set(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1539
        self.get_branch_config('http://www.example.com',
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1540
                                 global_config=sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1541
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1542
                         self.my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1543
        self.assertEqual(config.SIGN_NEVER,
1544
                         self.my_config.signing_policy())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1545
1546
    def test_signatures_never(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1547
        self.get_branch_config('/a/c')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1548
        self.assertEqual(config.CHECK_NEVER,
1549
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1550
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1551
    def test_signatures_when_available(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1552
        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
1553
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1554
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1555
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1556
    def test_signatures_always(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1557
        self.get_branch_config('/b')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1558
        self.assertEqual(config.CHECK_ALWAYS,
1559
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1560
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1561
    def test_gpg_signing_command(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1562
        self.get_branch_config('/b')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1563
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
1564
1565
    def test_gpg_signing_command_missing(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1566
        self.get_branch_config('/a')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1567
        self.assertEqual("false", self.my_config.gpg_signing_command())
1568
6012.2.3 by Jonathan Riddell
add config option for signing key
1569
    def test_gpg_signing_key(self):
1570
        self.get_branch_config('/b')
6012.2.11 by Jonathan Riddell
rename config option signing_key to gpg_signing_key
1571
        self.assertEqual("DD4D5088", self.my_config.gpg_signing_key())
6012.2.3 by Jonathan Riddell
add config option for signing key
1572
6012.2.9 by Jonathan Riddell
fixes 68501
1573
    def test_gpg_signing_key_default(self):
6012.2.3 by Jonathan Riddell
add config option for signing key
1574
        self.get_branch_config('/a')
6012.2.11 by Jonathan Riddell
rename config option signing_key to gpg_signing_key
1575
        self.assertEqual("erik@bagfors.nu", self.my_config.gpg_signing_key())
6012.2.3 by Jonathan Riddell
add config option for signing key
1576
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1577
    def test_get_user_option_global(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1578
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1579
        self.assertEqual('something',
1580
                         self.my_config.get_user_option('user_global_option'))
1581
1582
    def test_get_user_option_local(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1583
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1584
        self.assertEqual('local',
1585
                         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
1586
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
1587
    def test_get_user_option_appendpath(self):
1588
        # returned as is for the base path:
1589
        self.get_branch_config('http://www.example.com')
1590
        self.assertEqual('append',
1591
                         self.my_config.get_user_option('appendpath_option'))
1592
        # Extra path components get appended:
1593
        self.get_branch_config('http://www.example.com/a/b/c')
1594
        self.assertEqual('append/a/b/c',
1595
                         self.my_config.get_user_option('appendpath_option'))
1596
        # Overriden for http://www.example.com/dir, where it is a
1597
        # normal option:
1598
        self.get_branch_config('http://www.example.com/dir/a/b/c')
1599
        self.assertEqual('normal',
1600
                         self.my_config.get_user_option('appendpath_option'))
1601
1602
    def test_get_user_option_norecurse(self):
1603
        self.get_branch_config('http://www.example.com')
1604
        self.assertEqual('norecurse',
1605
                         self.my_config.get_user_option('norecurse_option'))
1606
        self.get_branch_config('http://www.example.com/dir')
1607
        self.assertEqual(None,
1608
                         self.my_config.get_user_option('norecurse_option'))
1609
        # http://www.example.com/norecurse is a recurse=False section
1610
        # that redefines normal_option.  Subdirectories do not pick up
1611
        # this redefinition.
1612
        self.get_branch_config('http://www.example.com/norecurse')
1613
        self.assertEqual('norecurse',
1614
                         self.my_config.get_user_option('normal_option'))
1615
        self.get_branch_config('http://www.example.com/norecurse/subdir')
1616
        self.assertEqual('normal',
1617
                         self.my_config.get_user_option('normal_option'))
1618
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1619
    def test_set_user_option_norecurse(self):
1620
        self.get_branch_config('http://www.example.com')
1621
        self.my_config.set_user_option('foo', 'bar',
1622
                                       store=config.STORE_LOCATION_NORECURSE)
1623
        self.assertEqual(
1624
            self.my_location_config._get_option_policy(
1625
            'http://www.example.com', 'foo'),
1626
            config.POLICY_NORECURSE)
1627
1628
    def test_set_user_option_appendpath(self):
1629
        self.get_branch_config('http://www.example.com')
1630
        self.my_config.set_user_option('foo', 'bar',
1631
                                       store=config.STORE_LOCATION_APPENDPATH)
1632
        self.assertEqual(
1633
            self.my_location_config._get_option_policy(
1634
            'http://www.example.com', 'foo'),
1635
            config.POLICY_APPENDPATH)
1636
1637
    def test_set_user_option_change_policy(self):
1638
        self.get_branch_config('http://www.example.com')
1639
        self.my_config.set_user_option('norecurse_option', 'normal',
1640
                                       store=config.STORE_LOCATION)
1641
        self.assertEqual(
1642
            self.my_location_config._get_option_policy(
1643
            'http://www.example.com', 'norecurse_option'),
1644
            config.POLICY_NONE)
1645
1646
    def test_set_user_option_recurse_false_section(self):
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1647
        # The following section has recurse=False set.  The test is to
1648
        # make sure that a normal option can be added to the section,
1649
        # converting recurse=False to the norecurse policy.
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1650
        self.get_branch_config('http://www.example.com/norecurse')
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
1651
        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
1652
                             'The section "http://www.example.com/norecurse" '
1653
                             'has been converted to use policies.'],
1654
                            self.my_config.set_user_option,
1655
                            'foo', 'bar', store=config.STORE_LOCATION)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1656
        self.assertEqual(
1657
            self.my_location_config._get_option_policy(
1658
            'http://www.example.com/norecurse', 'foo'),
1659
            config.POLICY_NONE)
1660
        # The previously existing option is still norecurse:
1661
        self.assertEqual(
1662
            self.my_location_config._get_option_policy(
1663
            'http://www.example.com/norecurse', 'normal_option'),
1664
            config.POLICY_NORECURSE)
1665
1472 by Robert Collins
post commit hook, first pass implementation
1666
    def test_post_commit_default(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1667
        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
1668
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1669
                         self.my_config.post_commit())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1670
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1671
    def get_branch_config(self, location, global_config=None,
1672
                          location_config=None):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1673
        my_branch = FakeBranch(location)
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
1674
        if global_config is None:
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1675
            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.
1676
        if location_config is None:
1677
            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.
1678
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1679
        my_global_config = config.GlobalConfig.from_string(global_config,
1680
                                                           save=True)
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1681
        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.
1682
            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.
1683
        my_config = config.BranchConfig(my_branch)
1684
        self.my_config = my_config
1685
        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.
1686
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1687
    def test_set_user_setting_sets_and_saves(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1688
        self.get_branch_config('/a/c')
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1689
        record = InstrumentedConfigObj("foo")
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1690
        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
1691
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1692
        self.callDeprecated(['The recurse option is deprecated as of '
1693
                             '0.14.  The section "/a/c" has been '
1694
                             'converted to use policies.'],
1695
                            self.my_config.set_user_option,
1696
                            'foo', 'bar', store=config.STORE_LOCATION)
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
1697
        self.assertEqual([('reload',),
1698
                          ('__contains__', '/a/c'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1699
                          ('__contains__', '/a/c/'),
1700
                          ('__setitem__', '/a/c', {}),
1701
                          ('__getitem__', '/a/c'),
1702
                          ('__setitem__', 'foo', 'bar'),
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1703
                          ('__getitem__', '/a/c'),
1704
                          ('as_bool', 'recurse'),
1705
                          ('__getitem__', '/a/c'),
1706
                          ('__delitem__', 'recurse'),
1707
                          ('__getitem__', '/a/c'),
1708
                          ('keys',),
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1709
                          ('__getitem__', '/a/c'),
1710
                          ('__contains__', 'foo:policy'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1711
                          ('write',)],
1712
                         record._calls[1:])
1713
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1714
    def test_set_user_setting_sets_and_saves2(self):
1715
        self.get_branch_config('/a/c')
1716
        self.assertIs(self.my_config.get_user_option('foo'), None)
1717
        self.my_config.set_user_option('foo', 'bar')
1718
        self.assertEqual(
3616.2.6 by Mark Hammond
Fix test_set_user_setting_sets_and_saves2 on windows by stripping EOL
1719
            self.my_config.branch.control_files.files['branch.conf'].strip(),
1720
            'foo = bar')
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1721
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1722
        self.my_config.set_user_option('foo', 'baz',
1723
                                       store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1724
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1725
        self.my_config.set_user_option('foo', 'qux')
1726
        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.
1727
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1728
    def test_get_bzr_remote_path(self):
1729
        my_config = config.LocationConfig('/a/c')
1730
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1731
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1732
        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.
1733
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1734
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1735
1185.62.7 by John Arbash Meinel
Whitespace cleanup.
1736
1770.2.8 by Aaron Bentley
Add precedence test
1737
precedence_global = 'option = global'
1738
precedence_branch = 'option = branch'
1739
precedence_location = """
1740
[http://]
1741
recurse = true
1742
option = recurse
1743
[http://example.com/specific]
1744
option = exact
1745
"""
1746
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1747
class TestBranchConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1748
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1749
    def get_branch_config(self, global_config=None, location=None,
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1750
                          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.
1751
        my_branch = FakeBranch(location)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1752
        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
1753
            my_global_config = config.GlobalConfig.from_string(global_config,
1754
                                                               save=True)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1755
        if location_config is not None:
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1756
            my_location_config = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1757
                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.
1758
        my_config = config.BranchConfig(my_branch)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1759
        if branch_data_config is not None:
1760
            my_config.branch.control_files.files['branch.conf'] = \
1761
                branch_data_config
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1762
        return my_config
1763
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1764
    def test_user_id(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1765
        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
1766
        my_config = config.BranchConfig(branch)
1767
        self.assertEqual("Robert Collins <robertc@example.net>",
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1768
                         my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1769
        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.
1770
        my_config.set_user_option('email',
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1771
                                  "Robert Collins <robertc@example.org>")
1772
        self.assertEqual("John", my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1773
        del my_config.branch.control_files.files['email']
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1774
        self.assertEqual("Robert Collins <robertc@example.org>",
1775
                         my_config.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1776
1777
    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.
1778
        my_config = self.get_branch_config(global_config=sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1779
        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
1780
                         my_config._get_user_id())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1781
        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
1782
        self.assertEqual("John", my_config._get_user_id())
1783
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
1784
    def test_BZR_EMAIL_OVERRIDES(self):
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
1785
        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
1786
        branch = FakeBranch()
1787
        my_config = config.BranchConfig(branch)
1788
        self.assertEqual("Robert Collins <robertc@example.org>",
1789
                         my_config.username())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1790
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1791
    def test_signatures_forced(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1792
        my_config = self.get_branch_config(
1793
            global_config=sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1794
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1795
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1796
        self.assertTrue(my_config.signature_needed())
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1797
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1798
    def test_signatures_forced_branch(self):
1799
        my_config = self.get_branch_config(
1800
            global_config=sample_ignore_signatures,
1801
            branch_data_config=sample_always_signatures)
1802
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1803
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1804
        self.assertTrue(my_config.signature_needed())
1805
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1806
    def test_gpg_signing_command(self):
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1807
        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.
1808
            global_config=sample_config_text,
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1809
            # branch data cannot set gpg_signing_command
1810
            branch_data_config="gpg_signing_command=pgp")
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1811
        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.
1812
1813
    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.
1814
        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.
1815
        self.assertEqual('something',
1816
                         my_config.get_user_option('user_global_option'))
1472 by Robert Collins
post commit hook, first pass implementation
1817
1818
    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.
1819
        my_config = self.get_branch_config(global_config=sample_config_text,
1820
                                      location='/a/c',
1821
                                      location_config=sample_branches_text)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1822
        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
1823
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1824
                         my_config.post_commit())
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1825
        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.
1826
        # post-commit is ignored when present in branch data
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1827
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1828
                         my_config.post_commit())
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1829
        my_config.set_user_option('post_commit', 'rmtree_root',
1830
                                  store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1831
        self.assertEqual('rmtree_root', my_config.post_commit())
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1832
1770.2.8 by Aaron Bentley
Add precedence test
1833
    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.
1834
        # FIXME: eager test, luckily no persitent config file makes it fail
1835
        # -- vila 20100716
1770.2.8 by Aaron Bentley
Add precedence test
1836
        my_config = self.get_branch_config(global_config=precedence_global)
1837
        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.
1838
        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.
1839
                                           branch_data_config=precedence_branch)
1770.2.8 by Aaron Bentley
Add precedence test
1840
        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.
1841
        my_config = self.get_branch_config(
1842
            global_config=precedence_global,
1843
            branch_data_config=precedence_branch,
1844
            location_config=precedence_location)
1770.2.8 by Aaron Bentley
Add precedence test
1845
        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.
1846
        my_config = self.get_branch_config(
1847
            global_config=precedence_global,
1848
            branch_data_config=precedence_branch,
1849
            location_config=precedence_location,
1850
            location='http://example.com/specific')
1770.2.8 by Aaron Bentley
Add precedence test
1851
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1852
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
1853
    def test_get_mail_client(self):
1854
        config = self.get_branch_config()
1855
        client = config.get_mail_client()
2681.1.24 by Aaron Bentley
Handle default mail client by trying xdg-email, falling back to editor
1856
        self.assertIsInstance(client, mail_client.DefaultMail)
1857
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1858
        # Specific clients
2681.1.21 by Aaron Bentley
Refactor prompt generation to make it testable, test it with unicode
1859
        config.set_user_option('mail_client', 'evolution')
1860
        client = config.get_mail_client()
1861
        self.assertIsInstance(client, mail_client.Evolution)
1862
2681.5.1 by ghigo
Add KMail support to bzr send
1863
        config.set_user_option('mail_client', 'kmail')
1864
        client = config.get_mail_client()
1865
        self.assertIsInstance(client, mail_client.KMail)
1866
2790.2.1 by Keir Mierle
Add Mutt as a supported client email program. Also rearranges various listings
1867
        config.set_user_option('mail_client', 'mutt')
1868
        client = config.get_mail_client()
1869
        self.assertIsInstance(client, mail_client.Mutt)
1870
1871
        config.set_user_option('mail_client', 'thunderbird')
1872
        client = config.get_mail_client()
1873
        self.assertIsInstance(client, mail_client.Thunderbird)
1874
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1875
        # Generic options
1876
        config.set_user_option('mail_client', 'default')
1877
        client = config.get_mail_client()
1878
        self.assertIsInstance(client, mail_client.DefaultMail)
1879
1880
        config.set_user_option('mail_client', 'editor')
1881
        client = config.get_mail_client()
1882
        self.assertIsInstance(client, mail_client.Editor)
1883
1884
        config.set_user_option('mail_client', 'mapi')
1885
        client = config.get_mail_client()
1886
        self.assertIsInstance(client, mail_client.MAPIClient)
1887
2681.1.23 by Aaron Bentley
Add support for xdg-email
1888
        config.set_user_option('mail_client', 'xdg-email')
1889
        client = config.get_mail_client()
1890
        self.assertIsInstance(client, mail_client.XDGEmail)
1891
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
1892
        config.set_user_option('mail_client', 'firebird')
1893
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1894
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1895
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1896
class TestMailAddressExtraction(tests.TestCase):
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1897
1898
    def test_extract_email_address(self):
1899
        self.assertEqual('jane@test.com',
1900
                         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
1901
        self.assertRaises(errors.NoEmailInUsername,
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1902
                          config.extract_email_address, 'Jane Tester')
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1903
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1904
    def test_parse_username(self):
1905
        self.assertEqual(('', 'jdoe@example.com'),
1906
                         config.parse_username('jdoe@example.com'))
1907
        self.assertEqual(('', 'jdoe@example.com'),
1908
                         config.parse_username('<jdoe@example.com>'))
1909
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1910
                         config.parse_username('John Doe <jdoe@example.com>'))
1911
        self.assertEqual(('John Doe', ''),
1912
                         config.parse_username('John Doe'))
3063.3.3 by Lukáš Lalinský
Add one more test for config.parse_username().
1913
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1914
                         config.parse_username('John Doe jdoe@example.com'))
2562.1.2 by John Arbash Meinel
Clean up whitespace
1915
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1916
class TestTreeConfig(tests.TestCaseWithTransport):
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1917
1918
    def test_get_value(self):
1919
        """Test that retreiving a value from a section is possible"""
1920
        branch = self.make_branch('.')
1921
        tree_config = config.TreeConfig(branch)
1922
        tree_config.set_option('value', 'key', 'SECTION')
1923
        tree_config.set_option('value2', 'key2')
1924
        tree_config.set_option('value3-top', 'key3')
1925
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1926
        value = tree_config.get_option('key', 'SECTION')
1927
        self.assertEqual(value, 'value')
1928
        value = tree_config.get_option('key2')
1929
        self.assertEqual(value, 'value2')
1930
        self.assertEqual(tree_config.get_option('non-existant'), None)
1931
        value = tree_config.get_option('non-existant', 'SECTION')
1932
        self.assertEqual(value, None)
1933
        value = tree_config.get_option('non-existant', default='default')
1934
        self.assertEqual(value, 'default')
1935
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1936
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1937
        self.assertEqual(value, 'default')
1938
        value = tree_config.get_option('key3')
1939
        self.assertEqual(value, 'value3-top')
1940
        value = tree_config.get_option('key3', 'SECTION')
1941
        self.assertEqual(value, 'value3-section')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1942
1943
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1944
class TestTransportConfig(tests.TestCaseWithTransport):
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1945
5987.1.4 by Vincent Ladeuil
Proper error messages for config files with content in non-utf encoding or that cannot be parsed
1946
    def test_load_utf8(self):
1947
        """Ensure we can load an utf8-encoded file."""
1948
        t = self.get_transport()
1949
        unicode_user = u'b\N{Euro Sign}ar'
1950
        unicode_content = u'user=%s' % (unicode_user,)
1951
        utf8_content = unicode_content.encode('utf8')
1952
        # Store the raw content in the config file
1953
        t.put_bytes('foo.conf', utf8_content)
1954
        conf = config.TransportConfig(t, 'foo.conf')
1955
        self.assertEquals(unicode_user, conf.get_option('user'))
1956
1957
    def test_load_non_ascii(self):
1958
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
1959
        t = self.get_transport()
1960
        t.put_bytes('foo.conf', 'user=foo\n#\xff\n')
1961
        conf = config.TransportConfig(t, 'foo.conf')
1962
        self.assertRaises(errors.ConfigContentError, conf._get_configobj)
1963
1964
    def test_load_erroneous_content(self):
1965
        """Ensure we display a proper error on content that can't be parsed."""
1966
        t = self.get_transport()
1967
        t.put_bytes('foo.conf', '[open_section\n')
1968
        conf = config.TransportConfig(t, 'foo.conf')
1969
        self.assertRaises(errors.ParseConfigError, conf._get_configobj)
1970
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1971
    def test_get_value(self):
1972
        """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
1973
        bzrdir_config = config.TransportConfig(self.get_transport('.'),
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1974
                                               'control.conf')
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1975
        bzrdir_config.set_option('value', 'key', 'SECTION')
1976
        bzrdir_config.set_option('value2', 'key2')
1977
        bzrdir_config.set_option('value3-top', 'key3')
1978
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1979
        value = bzrdir_config.get_option('key', 'SECTION')
1980
        self.assertEqual(value, 'value')
1981
        value = bzrdir_config.get_option('key2')
1982
        self.assertEqual(value, 'value2')
1983
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1984
        value = bzrdir_config.get_option('non-existant', 'SECTION')
1985
        self.assertEqual(value, None)
1986
        value = bzrdir_config.get_option('non-existant', default='default')
1987
        self.assertEqual(value, 'default')
1988
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1989
        value = bzrdir_config.get_option('key2', 'NOSECTION',
1990
                                         default='default')
1991
        self.assertEqual(value, 'default')
1992
        value = bzrdir_config.get_option('key3')
1993
        self.assertEqual(value, 'value3-top')
1994
        value = bzrdir_config.get_option('key3', 'SECTION')
1995
        self.assertEqual(value, 'value3-section')
1996
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1997
    def test_set_unset_default_stack_on(self):
1998
        my_dir = self.make_bzrdir('.')
4288.1.3 by Robert Collins
Fix BzrDirConfig tests.
1999
        bzrdir_config = config.BzrDirConfig(my_dir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
2000
        self.assertIs(None, bzrdir_config.get_default_stack_on())
2001
        bzrdir_config.set_default_stack_on('Foo')
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
2002
        self.assertEqual('Foo', bzrdir_config._config.get_option(
2003
                         'default_stack_on'))
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
2004
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
2005
        bzrdir_config.set_default_stack_on(None)
2006
        self.assertIs(None, bzrdir_config.get_default_stack_on())
2007
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2008
5743.8.19 by Vincent Ladeuil
Revert the mixin addition, no way to share with remote configs which implements a different API.
2009
class TestOldConfigHooks(tests.TestCaseWithTransport):
2010
2011
    def setUp(self):
2012
        super(TestOldConfigHooks, self).setUp()
2013
        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.
2014
2015
    def assertGetHook(self, conf, name, value):
2016
        calls = []
2017
        def hook(*args):
2018
            calls.append(args)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2019
        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).
2020
        self.addCleanup(
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2021
            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.
2022
        self.assertLength(0, calls)
2023
        actual_value = conf.get_user_option(name)
2024
        self.assertEquals(value, actual_value)
2025
        self.assertLength(1, calls)
2026
        self.assertEquals((conf, name, value), calls[0])
2027
2028
    def test_get_hook_bazaar(self):
2029
        self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
2030
2031
    def test_get_hook_locations(self):
2032
        self.assertGetHook(self.locations_config, 'file', 'locations')
2033
2034
    def test_get_hook_branch(self):
2035
        # Since locations masks branch, we define a different option
2036
        self.branch_config.set_user_option('file2', 'branch')
2037
        self.assertGetHook(self.branch_config, 'file2', 'branch')
2038
5743.8.19 by Vincent Ladeuil
Revert the mixin addition, no way to share with remote configs which implements a different API.
2039
    def assertSetHook(self, conf, name, value):
2040
        calls = []
2041
        def hook(*args):
2042
            calls.append(args)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2043
        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).
2044
        self.addCleanup(
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2045
            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.
2046
        self.assertLength(0, calls)
2047
        conf.set_user_option(name, value)
2048
        self.assertLength(1, calls)
2049
        # We can't assert the conf object below as different configs use
2050
        # different means to implement set_user_option and we care only about
2051
        # coverage here.
2052
        self.assertEquals((name, value), calls[0][1:])
2053
5743.8.15 by Vincent Ladeuil
Add tests for old config hooks covering bazaar.conf, locations.conf and branch.conf.
2054
    def test_set_hook_bazaar(self):
2055
        self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
2056
2057
    def test_set_hook_locations(self):
2058
        self.assertSetHook(self.locations_config, 'foo', 'locations')
2059
2060
    def test_set_hook_branch(self):
2061
        self.assertSetHook(self.branch_config, 'foo', 'branch')
2062
5743.8.19 by Vincent Ladeuil
Revert the mixin addition, no way to share with remote configs which implements a different API.
2063
    def assertRemoveHook(self, conf, name, section_name=None):
2064
        calls = []
2065
        def hook(*args):
2066
            calls.append(args)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2067
        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).
2068
        self.addCleanup(
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2069
            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.
2070
        self.assertLength(0, calls)
2071
        conf.remove_user_option(name, section_name)
2072
        self.assertLength(1, calls)
2073
        # We can't assert the conf object below as different configs use
2074
        # different means to implement remove_user_option and we care only about
2075
        # coverage here.
2076
        self.assertEquals((name,), calls[0][1:])
2077
5743.8.15 by Vincent Ladeuil
Add tests for old config hooks covering bazaar.conf, locations.conf and branch.conf.
2078
    def test_remove_hook_bazaar(self):
2079
        self.assertRemoveHook(self.bazaar_config, 'file')
2080
2081
    def test_remove_hook_locations(self):
2082
        self.assertRemoveHook(self.locations_config, 'file',
2083
                              self.locations_config.location)
2084
2085
    def test_remove_hook_branch(self):
2086
        self.assertRemoveHook(self.branch_config, 'file')
2087
5743.8.19 by Vincent Ladeuil
Revert the mixin addition, no way to share with remote configs which implements a different API.
2088
    def assertLoadHook(self, name, conf_class, *conf_args):
2089
        calls = []
2090
        def hook(*args):
2091
            calls.append(args)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2092
        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).
2093
        self.addCleanup(
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2094
            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.
2095
        self.assertLength(0, calls)
2096
        # Build a config
2097
        conf = conf_class(*conf_args)
2098
        # Access an option to trigger a load
2099
        conf.get_user_option(name)
2100
        self.assertLength(1, calls)
2101
        # Since we can't assert about conf, we just use the number of calls ;-/
2102
5743.8.15 by Vincent Ladeuil
Add tests for old config hooks covering bazaar.conf, locations.conf and branch.conf.
2103
    def test_load_hook_bazaar(self):
2104
        self.assertLoadHook('file', config.GlobalConfig)
2105
2106
    def test_load_hook_locations(self):
2107
        self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
2108
2109
    def test_load_hook_branch(self):
2110
        self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
2111
5743.8.19 by Vincent Ladeuil
Revert the mixin addition, no way to share with remote configs which implements a different API.
2112
    def assertSaveHook(self, conf):
2113
        calls = []
2114
        def hook(*args):
2115
            calls.append(args)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2116
        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).
2117
        self.addCleanup(
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2118
            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.
2119
        self.assertLength(0, calls)
2120
        # Setting an option triggers a save
2121
        conf.set_user_option('foo', 'bar')
2122
        self.assertLength(1, calls)
2123
        # Since we can't assert about conf, we just use the number of calls ;-/
2124
5743.8.15 by Vincent Ladeuil
Add tests for old config hooks covering bazaar.conf, locations.conf and branch.conf.
2125
    def test_save_hook_bazaar(self):
2126
        self.assertSaveHook(self.bazaar_config)
2127
2128
    def test_save_hook_locations(self):
2129
        self.assertSaveHook(self.locations_config)
2130
2131
    def test_save_hook_branch(self):
2132
        self.assertSaveHook(self.branch_config)
2133
2134
5743.8.20 by Vincent Ladeuil
Add tests for set hook.
2135
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
2136
    """Tests config hooks for remote configs.
2137
2138
    No tests for the remove hook as this is not implemented there.
2139
    """
5743.8.17 by Vincent Ladeuil
Add config old_get hook for remote config.
2140
2141
    def setUp(self):
2142
        super(TestOldConfigHooksForRemote, self).setUp()
2143
        self.transport_server = test_server.SmartTCPServer_for_testing
2144
        create_configs_with_file_option(self)
2145
5743.8.18 by Vincent Ladeuil
Add a test for remote bzr dir.
2146
    def assertGetHook(self, conf, name, value):
2147
        calls = []
2148
        def hook(*args):
2149
            calls.append(args)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2150
        config.OldConfigHooks.install_named_hook('get', hook, None)
5743.8.21 by Vincent Ladeuil
Add test for config load hook for remote configs.
2151
        self.addCleanup(
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2152
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
5743.8.18 by Vincent Ladeuil
Add a test for remote bzr dir.
2153
        self.assertLength(0, calls)
2154
        actual_value = conf.get_option(name)
2155
        self.assertEquals(value, actual_value)
2156
        self.assertLength(1, calls)
2157
        self.assertEquals((conf, name, value), calls[0])
2158
2159
    def test_get_hook_remote_branch(self):
5743.8.17 by Vincent Ladeuil
Add config old_get hook for remote config.
2160
        remote_branch = branch.Branch.open(self.get_url('tree'))
5743.8.18 by Vincent Ladeuil
Add a test for remote bzr dir.
2161
        self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
5743.8.17 by Vincent Ladeuil
Add config old_get hook for remote config.
2162
5743.8.18 by Vincent Ladeuil
Add a test for remote bzr dir.
2163
    def test_get_hook_remote_bzrdir(self):
2164
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2165
        conf = remote_bzrdir._get_config()
2166
        conf.set_option('remotedir', 'file')
2167
        self.assertGetHook(conf, 'file', 'remotedir')
5743.8.17 by Vincent Ladeuil
Add config old_get hook for remote config.
2168
5743.8.20 by Vincent Ladeuil
Add tests for set hook.
2169
    def assertSetHook(self, conf, name, value):
2170
        calls = []
2171
        def hook(*args):
2172
            calls.append(args)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2173
        config.OldConfigHooks.install_named_hook('set', hook, None)
5743.8.21 by Vincent Ladeuil
Add test for config load hook for remote configs.
2174
        self.addCleanup(
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2175
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
5743.8.20 by Vincent Ladeuil
Add tests for set hook.
2176
        self.assertLength(0, calls)
2177
        conf.set_option(value, name)
2178
        self.assertLength(1, calls)
2179
        # We can't assert the conf object below as different configs use
2180
        # different means to implement set_user_option and we care only about
2181
        # coverage here.
2182
        self.assertEquals((name, value), calls[0][1:])
2183
2184
    def test_set_hook_remote_branch(self):
2185
        remote_branch = branch.Branch.open(self.get_url('tree'))
2186
        self.addCleanup(remote_branch.lock_write().unlock)
2187
        self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
2188
2189
    def test_set_hook_remote_bzrdir(self):
2190
        remote_branch = branch.Branch.open(self.get_url('tree'))
2191
        self.addCleanup(remote_branch.lock_write().unlock)
2192
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2193
        self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2194
5743.8.21 by Vincent Ladeuil
Add test for config load hook for remote configs.
2195
    def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2196
        calls = []
2197
        def hook(*args):
2198
            calls.append(args)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2199
        config.OldConfigHooks.install_named_hook('load', hook, None)
5743.8.21 by Vincent Ladeuil
Add test for config load hook for remote configs.
2200
        self.addCleanup(
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2201
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
5743.8.21 by Vincent Ladeuil
Add test for config load hook for remote configs.
2202
        self.assertLength(0, calls)
2203
        # Build a config
2204
        conf = conf_class(*conf_args)
2205
        # Access an option to trigger a load
2206
        conf.get_option(name)
2207
        self.assertLength(expected_nb_calls, calls)
2208
        # Since we can't assert about conf, we just use the number of calls ;-/
2209
2210
    def test_load_hook_remote_branch(self):
2211
        remote_branch = branch.Branch.open(self.get_url('tree'))
2212
        self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2213
2214
    def test_load_hook_remote_bzrdir(self):
2215
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2216
        # The config file doesn't exist, set an option to force its creation
2217
        conf = remote_bzrdir._get_config()
2218
        conf.set_option('remotedir', 'file')
2219
        # We get one call for the server and one call for the client, this is
2220
        # caused by the differences in implementations betwen
2221
        # SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
2222
        # SmartServerBranchGetConfigFile (in smart/branch.py)
2223
        self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
2224
5743.8.22 by Vincent Ladeuil
Add tests for config save hook for remote configs.
2225
    def assertSaveHook(self, conf):
2226
        calls = []
2227
        def hook(*args):
2228
            calls.append(args)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2229
        config.OldConfigHooks.install_named_hook('save', hook, None)
5743.8.22 by Vincent Ladeuil
Add tests for config save hook for remote configs.
2230
        self.addCleanup(
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2231
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
5743.8.22 by Vincent Ladeuil
Add tests for config save hook for remote configs.
2232
        self.assertLength(0, calls)
2233
        # Setting an option triggers a save
2234
        conf.set_option('foo', 'bar')
2235
        self.assertLength(1, calls)
2236
        # Since we can't assert about conf, we just use the number of calls ;-/
2237
2238
    def test_save_hook_remote_branch(self):
2239
        remote_branch = branch.Branch.open(self.get_url('tree'))
2240
        self.addCleanup(remote_branch.lock_write().unlock)
2241
        self.assertSaveHook(remote_branch._get_config())
2242
2243
    def test_save_hook_remote_bzrdir(self):
2244
        remote_branch = branch.Branch.open(self.get_url('tree'))
2245
        self.addCleanup(remote_branch.lock_write().unlock)
2246
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2247
        self.assertSaveHook(remote_bzrdir._get_config())
2248
5743.8.17 by Vincent Ladeuil
Add config old_get hook for remote config.
2249
5743.12.4 by Vincent Ladeuil
An option can provide a default value.
2250
class TestOption(tests.TestCase):
2251
2252
    def test_default_value(self):
2253
        opt = config.Option('foo', default='bar')
2254
        self.assertEquals('bar', opt.get_default())
5743.12.5 by Vincent Ladeuil
Remove spurious spaces.
2255
6082.2.1 by Vincent Ladeuil
Implement default values from environment for config options
2256
    def test_default_value_from_env(self):
2257
        opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2258
        self.overrideEnv('FOO', 'quux')
2259
        # Env variable provides a default taking over the option one
2260
        self.assertEquals('quux', opt.get_default())
6091.3.1 by Vincent Ladeuil
Add convert_from_unicode to Option and rewrite the tests to need only an
2261
6082.2.1 by Vincent Ladeuil
Implement default values from environment for config options
2262
    def test_first_default_value_from_env_wins(self):
2263
        opt = config.Option('foo', default='bar',
2264
                            default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2265
        self.overrideEnv('FOO', 'foo')
2266
        self.overrideEnv('BAZ', 'baz')
2267
        # The first env var set wins
2268
        self.assertEquals('foo', opt.get_default())
2269
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
2270
    def test_not_supported_list_default_value(self):
2271
        self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2272
2273
    def test_not_supported_object_default_value(self):
2274
        self.assertRaises(AssertionError, config.Option, 'foo',
2275
                          default=object())
2276
5743.12.4 by Vincent Ladeuil
An option can provide a default value.
2277
6091.3.1 by Vincent Ladeuil
Add convert_from_unicode to Option and rewrite the tests to need only an
2278
class TestOptionConverterMixin(object):
2279
2280
    def assertConverted(self, expected, opt, value):
2281
        self.assertEquals(expected, opt.convert_from_unicode(value))
2282
2283
    def assertWarns(self, opt, value):
2284
        warnings = []
2285
        def warning(*args):
2286
            warnings.append(args[0] % args[1:])
2287
        self.overrideAttr(trace, 'warning', warning)
2288
        self.assertEquals(None, opt.convert_from_unicode(value))
2289
        self.assertLength(1, warnings)
2290
        self.assertEquals(
2291
            'Value "%s" is not valid for "%s"' % (value, opt.name),
2292
            warnings[0])
2293
2294
    def assertErrors(self, opt, value):
2295
        self.assertRaises(errors.ConfigOptionValueError,
2296
                          opt.convert_from_unicode, value)
2297
2298
    def assertConvertInvalid(self, opt, invalid_value):
2299
        opt.invalid = None
2300
        self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2301
        opt.invalid = 'warning'
2302
        self.assertWarns(opt, invalid_value)
2303
        opt.invalid = 'error'
2304
        self.assertErrors(opt, invalid_value)
2305
2306
2307
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2308
2309
    def get_option(self):
2310
        return config.Option('foo', help='A boolean.',
2311
                             from_unicode=config.bool_from_store)
2312
2313
    def test_convert_invalid(self):
2314
        opt = self.get_option()
2315
        # A string that is not recognized as a boolean
2316
        self.assertConvertInvalid(opt, u'invalid-boolean')
2317
        # A list of strings is never recognized as a boolean
2318
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2319
2320
    def test_convert_valid(self):
2321
        opt = self.get_option()
2322
        self.assertConverted(True, opt, u'True')
2323
        self.assertConverted(True, opt, u'1')
2324
        self.assertConverted(False, opt, u'False')
2325
2326
2327
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2328
2329
    def get_option(self):
2330
        return config.Option('foo', help='An integer.',
2331
                             from_unicode=config.int_from_store)
2332
2333
    def test_convert_invalid(self):
2334
        opt = self.get_option()
2335
        # A string that is not recognized as an integer
2336
        self.assertConvertInvalid(opt, u'forty-two')
2337
        # A list of strings is never recognized as an integer
2338
        self.assertConvertInvalid(opt, [u'a', u'list'])
2339
2340
    def test_convert_valid(self):
2341
        opt = self.get_option()
2342
        self.assertConverted(16, opt, u'16')
2343
2344
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2345
2346
    def get_option(self):
2347
        return config.Option('foo', help='A list.',
2348
                             from_unicode=config.list_from_store)
2349
2350
    def test_convert_invalid(self):
2351
        # No string is invalid as all forms can be converted to a list
2352
        pass
2353
2354
    def test_convert_valid(self):
2355
        opt = self.get_option()
2356
        # An empty string is an empty list
2357
        self.assertConverted([], opt, '') # Using a bare str() just in case
2358
        self.assertConverted([], opt, u'')
2359
        # A boolean
2360
        self.assertConverted([u'True'], opt, u'True')
2361
        # An integer
2362
        self.assertConverted([u'42'], opt, u'42')
2363
        # A single string
2364
        self.assertConverted([u'bar'], opt, u'bar')
2365
        # A list remains a list (configObj will turn a string containing commas
2366
        # into a list, but that's not what we're testing here)
2367
        self.assertConverted([u'foo', u'1', u'True'],
2368
                             opt, [u'foo', u'1', u'True'])
2369
2370
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2371
class TestOptionRegistry(tests.TestCase):
5743.12.5 by Vincent Ladeuil
Remove spurious spaces.
2372
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2373
    def setUp(self):
2374
        super(TestOptionRegistry, self).setUp()
2375
        # Always start with an empty registry
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2376
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2377
        self.registry = config.option_registry
2378
2379
    def test_register(self):
2380
        opt = config.Option('foo')
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2381
        self.registry.register(opt)
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2382
        self.assertIs(opt, self.registry.get('foo'))
2383
5743.12.3 by Vincent Ladeuil
More basic tests for options. Start tests for all registered options.
2384
    def test_registered_help(self):
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2385
        opt = config.Option('foo', help='A simple option')
2386
        self.registry.register(opt)
5743.12.3 by Vincent Ladeuil
More basic tests for options. Start tests for all registered options.
2387
        self.assertEquals('A simple option', self.registry.get_help('foo'))
2388
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2389
    lazy_option = config.Option('lazy_foo', help='Lazy help')
2390
2391
    def test_register_lazy(self):
2392
        self.registry.register_lazy('lazy_foo', self.__module__,
2393
                                    'TestOptionRegistry.lazy_option')
2394
        self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2395
2396
    def test_registered_lazy_help(self):
2397
        self.registry.register_lazy('lazy_foo', self.__module__,
2398
                                    'TestOptionRegistry.lazy_option')
2399
        self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2400
5743.12.3 by Vincent Ladeuil
More basic tests for options. Start tests for all registered options.
2401
2402
class TestRegisteredOptions(tests.TestCase):
2403
    """All registered options should verify some constraints."""
2404
2405
    scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2406
                 in config.option_registry.iteritems()]
2407
2408
    def setUp(self):
2409
        super(TestRegisteredOptions, self).setUp()
2410
        self.registry = config.option_registry
2411
2412
    def test_proper_name(self):
2413
        # An option should be registered under its own name, this can't be
2414
        # checked at registration time for the lazy ones.
2415
        self.assertEquals(self.option_name, self.option.name)
2416
2417
    def test_help_is_set(self):
2418
        option_help = self.registry.get_help(self.option_name)
2419
        self.assertNotEquals(None, option_help)
6056.2.5 by Vincent Ladeuil
Fix typos caught by jelmer.
2420
        # 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.
2421
        # option is about
6056.2.5 by Vincent Ladeuil
Fix typos caught by jelmer.
2422
        self.assertIsNot(None, option_help)
5743.12.3 by Vincent Ladeuil
More basic tests for options. Start tests for all registered options.
2423
        self.assertNotEquals('', option_help)
2424
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2425
5743.3.12 by Vincent Ladeuil
Add an ad-hoc __repr__.
2426
class TestSection(tests.TestCase):
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2427
2428
    # FIXME: Parametrize so that all sections produced by Stores run these
5743.3.1 by Vincent Ladeuil
Add a docstring and dates to FIXMEs.
2429
    # tests -- vila 2011-04-01
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2430
2431
    def test_get_a_value(self):
2432
        a_dict = dict(foo='bar')
5743.3.11 by Vincent Ladeuil
Config sections only implement read access.
2433
        section = config.Section('myID', a_dict)
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2434
        self.assertEquals('bar', section.get('foo'))
2435
5743.3.10 by Vincent Ladeuil
Fix typos mentioned in reviews.
2436
    def test_get_unknown_option(self):
5743.2.2 by Vincent Ladeuil
Add tests for remove.
2437
        a_dict = dict()
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
2438
        section = config.Section(None, a_dict)
5743.2.2 by Vincent Ladeuil
Add tests for remove.
2439
        self.assertEquals('out of thin air',
2440
                          section.get('foo', 'out of thin air'))
2441
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2442
    def test_options_is_shared(self):
2443
        a_dict = dict()
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
2444
        section = config.Section(None, a_dict)
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2445
        self.assertIs(a_dict, section.options)
2446
2447
5743.3.12 by Vincent Ladeuil
Add an ad-hoc __repr__.
2448
class TestMutableSection(tests.TestCase):
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2449
5743.4.20 by Vincent Ladeuil
Fix typo.
2450
    # FIXME: Parametrize so that all sections (including os.environ and the
5743.3.1 by Vincent Ladeuil
Add a docstring and dates to FIXMEs.
2451
    # 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.
2452
2453
    def test_set(self):
2454
        a_dict = dict(foo='bar')
2455
        section = config.MutableSection('myID', a_dict)
2456
        section.set('foo', 'new_value')
2457
        self.assertEquals('new_value', section.get('foo'))
2458
        # The change appears in the shared section
2459
        self.assertEquals('new_value', a_dict.get('foo'))
2460
        # We keep track of the change
2461
        self.assertTrue('foo' in section.orig)
2462
        self.assertEquals('bar', section.orig.get('foo'))
2463
2464
    def test_set_preserve_original_once(self):
2465
        a_dict = dict(foo='bar')
2466
        section = config.MutableSection('myID', a_dict)
2467
        section.set('foo', 'first_value')
2468
        section.set('foo', 'second_value')
2469
        # We keep track of the original value
2470
        self.assertTrue('foo' in section.orig)
2471
        self.assertEquals('bar', section.orig.get('foo'))
2472
5743.2.2 by Vincent Ladeuil
Add tests for remove.
2473
    def test_remove(self):
2474
        a_dict = dict(foo='bar')
2475
        section = config.MutableSection('myID', a_dict)
2476
        section.remove('foo')
2477
        # We get None for unknown options via the default value
2478
        self.assertEquals(None, section.get('foo'))
2479
        # Or we just get the default value
2480
        self.assertEquals('unknown', section.get('foo', 'unknown'))
2481
        self.assertFalse('foo' in section.options)
2482
        # We keep track of the deletion
2483
        self.assertTrue('foo' in section.orig)
2484
        self.assertEquals('bar', section.orig.get('foo'))
2485
2486
    def test_remove_new_option(self):
2487
        a_dict = dict()
2488
        section = config.MutableSection('myID', a_dict)
2489
        section.set('foo', 'bar')
2490
        section.remove('foo')
2491
        self.assertFalse('foo' in section.options)
2492
        # The option didn't exist initially so it we need to keep track of it
2493
        # with a special value
2494
        self.assertTrue('foo' in section.orig)
5743.3.6 by Vincent Ladeuil
Use a name less likely to be reused.
2495
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
5743.2.2 by Vincent Ladeuil
Add tests for remove.
2496
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2497
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2498
class TestStore(tests.TestCaseWithTransport):
2499
2500
    def assertSectionContent(self, expected, section):
2501
        """Assert that some options have the proper values in a section."""
2502
        expected_name, expected_options = expected
2503
        self.assertEquals(expected_name, section.id)
2504
        self.assertEquals(
2505
            expected_options,
2506
            dict([(k, section.get(k)) for k in expected_options.keys()]))
2507
2508
2509
class TestReadonlyStore(TestStore):
2510
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2511
    scenarios = [(key, {'get_store': builder}) for key, builder
2512
                 in config.test_store_builder_registry.iteritems()]
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2513
2514
    def setUp(self):
2515
        super(TestReadonlyStore, self).setUp()
2516
2517
    def test_building_delays_load(self):
2518
        store = self.get_store(self)
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2519
        self.assertEquals(False, store.is_loaded())
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2520
        store._load_from_string('')
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2521
        self.assertEquals(True, store.is_loaded())
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2522
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2523
    def test_get_no_sections_for_empty(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2524
        store = self.get_store(self)
2525
        store._load_from_string('')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2526
        self.assertEquals([], list(store.get_sections()))
2527
2528
    def test_get_default_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2529
        store = self.get_store(self)
2530
        store._load_from_string('foo=bar')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2531
        sections = list(store.get_sections())
2532
        self.assertLength(1, sections)
2533
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2534
2535
    def test_get_named_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2536
        store = self.get_store(self)
2537
        store._load_from_string('[baz]\nfoo=bar')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2538
        sections = list(store.get_sections())
2539
        self.assertLength(1, sections)
2540
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2541
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2542
    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.
2543
        store = self.get_store(self)
2544
        store._load_from_string('foo=bar')
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2545
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2546
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2547
5987.1.2 by Vincent Ladeuil
Reproduce bug #502060, bug #688677 and bug #792246.
2548
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2549
    """Simulate loading a config store without content of various encodings.
2550
2551
    All files produced by bzr are in utf8 content.
2552
2553
    Users may modify them manually and end up with a file that can't be
2554
    loaded. We need to issue proper error messages in this case.
2555
    """
2556
2557
    invalid_utf8_char = '\xff'
2558
2559
    def test_load_utf8(self):
2560
        """Ensure we can load an utf8-encoded file."""
5987.1.1 by Vincent Ladeuil
Properly load utf8-encoded config files
2561
        t = self.get_transport()
2562
        # From http://pad.lv/799212
5987.1.2 by Vincent Ladeuil
Reproduce bug #502060, bug #688677 and bug #792246.
2563
        unicode_user = u'b\N{Euro Sign}ar'
5987.1.1 by Vincent Ladeuil
Properly load utf8-encoded config files
2564
        unicode_content = u'user=%s' % (unicode_user,)
2565
        utf8_content = unicode_content.encode('utf8')
2566
        # Store the raw content in the config file
2567
        t.put_bytes('foo.conf', utf8_content)
2568
        store = config.IniFileStore(t, 'foo.conf')
2569
        store.load()
2570
        stack = config.Stack([store.get_sections], store)
2571
        self.assertEquals(unicode_user, stack.get('user'))
2572
5987.1.2 by Vincent Ladeuil
Reproduce bug #502060, bug #688677 and bug #792246.
2573
    def test_load_non_ascii(self):
2574
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2575
        t = self.get_transport()
2576
        t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2577
        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
2578
        self.assertRaises(errors.ConfigContentError, store.load)
5987.1.2 by Vincent Ladeuil
Reproduce bug #502060, bug #688677 and bug #792246.
2579
2580
    def test_load_erroneous_content(self):
2581
        """Ensure we display a proper error on content that can't be parsed."""
2582
        t = self.get_transport()
2583
        t.put_bytes('foo.conf', '[open_section\n')
2584
        store = config.IniFileStore(t, 'foo.conf')
2585
        self.assertRaises(errors.ParseConfigError, store.load)
2586
2587
2588
class TestIniConfigContent(tests.TestCaseWithTransport):
2589
    """Simulate loading a IniBasedConfig without content of various encodings.
2590
2591
    All files produced by bzr are in utf8 content.
2592
2593
    Users may modify them manually and end up with a file that can't be
2594
    loaded. We need to issue proper error messages in this case.
2595
    """
2596
2597
    invalid_utf8_char = '\xff'
2598
2599
    def test_load_utf8(self):
2600
        """Ensure we can load an utf8-encoded file."""
2601
        # From http://pad.lv/799212
2602
        unicode_user = u'b\N{Euro Sign}ar'
2603
        unicode_content = u'user=%s' % (unicode_user,)
2604
        utf8_content = unicode_content.encode('utf8')
2605
        # Store the raw content in the config file
2606
        with open('foo.conf', 'wb') as f:
2607
            f.write(utf8_content)
2608
        conf = config.IniBasedConfig(file_name='foo.conf')
2609
        self.assertEquals(unicode_user, conf.get_user_option('user'))
2610
2611
    def test_load_badly_encoded_content(self):
2612
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2613
        with open('foo.conf', 'wb') as f:
2614
            f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2615
        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
2616
        self.assertRaises(errors.ConfigContentError, conf._get_parser)
5987.1.2 by Vincent Ladeuil
Reproduce bug #502060, bug #688677 and bug #792246.
2617
2618
    def test_load_erroneous_content(self):
2619
        """Ensure we display a proper error on content that can't be parsed."""
2620
        with open('foo.conf', 'wb') as f:
2621
            f.write('[open_section\n')
2622
        conf = config.IniBasedConfig(file_name='foo.conf')
2623
        self.assertRaises(errors.ParseConfigError, conf._get_parser)
2624
5987.1.1 by Vincent Ladeuil
Properly load utf8-encoded config files
2625
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2626
class TestMutableStore(TestStore):
2627
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2628
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2629
                 in config.test_store_builder_registry.iteritems()]
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2630
2631
    def setUp(self):
2632
        super(TestMutableStore, self).setUp()
2633
        self.transport = self.get_transport()
2634
2635
    def has_store(self, store):
2636
        store_basename = urlutils.relative_url(self.transport.external_url(),
2637
                                               store.external_url())
2638
        return self.transport.has(store_basename)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2639
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2640
    def test_save_empty_creates_no_file(self):
5743.10.4 by Vincent Ladeuil
Add FIXME.
2641
        # FIXME: There should be a better way than relying on the test
2642
        # 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.
2643
        if self.store_id in ('branch', 'remote_branch'):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2644
            raise tests.TestNotApplicable(
2645
                'branch.conf is *always* created when a branch is initialized')
2646
        store = self.get_store(self)
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2647
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2648
        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.
2649
2650
    def test_save_emptied_succeeds(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2651
        store = self.get_store(self)
2652
        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.
2653
        section = store.get_mutable_section(None)
2654
        section.remove('foo')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2655
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2656
        self.assertEquals(True, self.has_store(store))
2657
        modified_store = self.get_store(self)
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2658
        sections = list(modified_store.get_sections())
2659
        self.assertLength(0, sections)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2660
2661
    def test_save_with_content_succeeds(self):
5743.10.4 by Vincent Ladeuil
Add FIXME.
2662
        # FIXME: There should be a better way than relying on the test
2663
        # 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.
2664
        if self.store_id in ('branch', 'remote_branch'):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2665
            raise tests.TestNotApplicable(
2666
                'branch.conf is *always* created when a branch is initialized')
2667
        store = self.get_store(self)
2668
        store._load_from_string('foo=bar\n')
2669
        self.assertEquals(False, self.has_store(store))
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2670
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2671
        self.assertEquals(True, self.has_store(store))
2672
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2673
        sections = list(modified_store.get_sections())
2674
        self.assertLength(1, sections)
2675
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2676
2677
    def test_set_option_in_empty_store(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2678
        store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2679
        section = store.get_mutable_section(None)
2680
        section.set('foo', 'bar')
2681
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2682
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2683
        sections = list(modified_store.get_sections())
2684
        self.assertLength(1, sections)
2685
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2686
2687
    def test_set_option_in_default_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2688
        store = self.get_store(self)
2689
        store._load_from_string('')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2690
        section = store.get_mutable_section(None)
2691
        section.set('foo', 'bar')
2692
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2693
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2694
        sections = list(modified_store.get_sections())
2695
        self.assertLength(1, sections)
2696
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2697
2698
    def test_set_option_in_named_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2699
        store = self.get_store(self)
2700
        store._load_from_string('')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2701
        section = store.get_mutable_section('baz')
2702
        section.set('foo', 'bar')
2703
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2704
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2705
        sections = list(modified_store.get_sections())
2706
        self.assertLength(1, sections)
2707
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2708
5743.8.8 by Vincent Ladeuil
Puth the load hook in the right place.
2709
    def test_load_hook(self):
2710
        # We first needs to ensure that the store exists
2711
        store = self.get_store(self)
2712
        section = store.get_mutable_section('baz')
2713
        section.set('foo', 'bar')
2714
        store.save()
2715
        # Now we can try to load it
5743.8.11 by Vincent Ladeuil
Restrict the scope when testing hooks to avoid spurious failures.
2716
        store = self.get_store(self)
5743.8.8 by Vincent Ladeuil
Puth the load hook in the right place.
2717
        calls = []
2718
        def hook(*args):
2719
            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.
2720
        config.ConfigHooks.install_named_hook('load', hook, None)
5743.8.8 by Vincent Ladeuil
Puth the load hook in the right place.
2721
        self.assertLength(0, calls)
2722
        store.load()
2723
        self.assertLength(1, calls)
2724
        self.assertEquals((store,), calls[0])
2725
5743.8.7 by Vincent Ladeuil
Add hooks for config stores (but the load one is not in the right place).
2726
    def test_save_hook(self):
2727
        calls = []
2728
        def hook(*args):
2729
            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.
2730
        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).
2731
        self.assertLength(0, calls)
2732
        store = self.get_store(self)
2733
        section = store.get_mutable_section('baz')
2734
        section.set('foo', 'bar')
2735
        store.save()
2736
        self.assertLength(1, calls)
2737
        self.assertEquals((store,), calls[0])
2738
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2739
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2740
class TestIniFileStore(TestStore):
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2741
5743.4.3 by Vincent Ladeuil
Implement get_mutable_section.
2742
    def test_loading_unknown_file_fails(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2743
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
5743.4.3 by Vincent Ladeuil
Implement get_mutable_section.
2744
        self.assertRaises(errors.NoSuchFile, store.load)
2745
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2746
    def test_invalid_content(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2747
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2748
        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.
2749
        exc = self.assertRaises(
2750
            errors.ParseConfigError, store._load_from_string,
2751
            'this is invalid !')
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2752
        self.assertEndsWith(exc.filename, 'foo.conf')
2753
        # And the load failed
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2754
        self.assertEquals(False, store.is_loaded())
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2755
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2756
    def test_get_embedded_sections(self):
5743.2.11 by Vincent Ladeuil
Basic store.set implementation.
2757
        # A more complicated example (which also shows that section names and
2758
        # 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.
2759
        # FIXME: This should be fixed by forbidding dicts as values ?
2760
        # -- vila 2011-04-05
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2761
        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.
2762
        store._load_from_string('''
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2763
foo=bar
2764
l=1,2
2765
[DEFAULT]
2766
foo_in_DEFAULT=foo_DEFAULT
2767
[bar]
2768
foo_in_bar=barbar
2769
[baz]
2770
foo_in_baz=barbaz
2771
[[qux]]
2772
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.
2773
''')
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2774
        sections = list(store.get_sections())
2775
        self.assertLength(4, sections)
2776
        # The default section has no name.
2777
        # List values are provided as lists
5743.4.1 by Vincent Ladeuil
Use proper ReadOnly sections in ConfigObjStore.get_sections().
2778
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
2779
                                  sections[0])
2780
        self.assertSectionContent(
2781
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2782
        self.assertSectionContent(
2783
            ('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.
2784
        # sub sections are provided as embedded dicts.
5743.4.1 by Vincent Ladeuil
Use proper ReadOnly sections in ConfigObjStore.get_sections().
2785
        self.assertSectionContent(
2786
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2787
            sections[3])
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2788
5743.4.5 by Vincent Ladeuil
Split store tests between readonly and mutable ones.
2789
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2790
class TestLockableIniFileStore(TestStore):
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2791
2792
    def test_create_store_in_created_dir(self):
5743.6.21 by Vincent Ladeuil
Tighten the test.
2793
        self.assertPathDoesNotExist('dir')
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2794
        t = self.get_transport('dir/subdir')
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2795
        store = config.LockableIniFileStore(t, 'foo.conf')
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2796
        store.get_mutable_section(None).set('foo', 'bar')
2797
        store.save()
5743.6.21 by Vincent Ladeuil
Tighten the test.
2798
        self.assertPathExists('dir/subdir')
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2799
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2800
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2801
class TestConcurrentStoreUpdates(TestStore):
5743.10.13 by Vincent Ladeuil
Mention that the the concurrent update tests are not targeted at *all* Store implementations.
2802
    """Test that Stores properly handle conccurent updates.
2803
2804
    New Store implementation may fail some of these tests but until such
2805
    implementations exist it's hard to properly filter them from the scenarios
2806
    applied here. If you encounter such a case, contact the bzr devs.
2807
    """
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2808
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2809
    scenarios = [(key, {'get_stack': builder}) for key, builder
2810
                 in config.test_stack_builder_registry.iteritems()]
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2811
2812
    def setUp(self):
2813
        super(TestConcurrentStoreUpdates, self).setUp()
2814
        self._content = 'one=1\ntwo=2\n'
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2815
        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
2816
        if not isinstance(self.stack, config._CompatibleStack):
2817
            raise tests.TestNotApplicable(
2818
                '%s is not meant to be compatible with the old config design'
2819
                % (self.stack,))
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2820
        self.stack.store._load_from_string(self._content)
2821
        # Flush the store
2822
        self.stack.store.save()
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2823
2824
    def test_simple_read_access(self):
2825
        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
2826
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2827
    def test_simple_write_access(self):
2828
        self.stack.set('one', 'one')
2829
        self.assertEquals('one', self.stack.get('one'))
2830
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2831
    def test_listen_to_the_last_speaker(self):
2832
        c1 = self.stack
2833
        c2 = self.get_stack(self)
2834
        c1.set('one', 'ONE')
2835
        c2.set('two', 'TWO')
2836
        self.assertEquals('ONE', c1.get('one'))
2837
        self.assertEquals('TWO', c2.get('two'))
2838
        # The second update respect the first one
2839
        self.assertEquals('ONE', c2.get('one'))
2840
2841
    def test_last_speaker_wins(self):
2842
        # If the same config is not shared, the same variable modified twice
2843
        # can only see a single result.
2844
        c1 = self.stack
2845
        c2 = self.get_stack(self)
2846
        c1.set('one', 'c1')
2847
        c2.set('one', 'c2')
2848
        self.assertEquals('c2', c2.get('one'))
2849
        # The first modification is still available until another refresh
2850
        # occur
2851
        self.assertEquals('c1', c1.get('one'))
2852
        c1.set('two', 'done')
2853
        self.assertEquals('c2', c1.get('one'))
2854
5743.6.24 by Vincent Ladeuil
One more test with a ugly hack to allow the test to stop in the right place.
2855
    def test_writes_are_serialized(self):
2856
        c1 = self.stack
2857
        c2 = self.get_stack(self)
2858
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2859
        # 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.
2860
        before_writing = threading.Event()
2861
        after_writing = threading.Event()
2862
        writing_done = threading.Event()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2863
        c1_save_without_locking_orig = c1.store.save_without_locking
2864
        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.
2865
            before_writing.set()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2866
            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.
2867
            # The lock is held. We wait for the main thread to decide when to
2868
            # continue
2869
            after_writing.wait()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2870
        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.
2871
        def c1_set():
2872
            c1.set('one', 'c1')
2873
            writing_done.set()
2874
        t1 = threading.Thread(target=c1_set)
2875
        # Collect the thread after the test
2876
        self.addCleanup(t1.join)
2877
        # Be ready to unblock the thread if the test goes wrong
2878
        self.addCleanup(after_writing.set)
2879
        t1.start()
2880
        before_writing.wait()
2881
        self.assertRaises(errors.LockContention,
2882
                          c2.set, 'one', 'c2')
2883
        self.assertEquals('c1', c1.get('one'))
2884
        # Let the lock be released
2885
        after_writing.set()
2886
        writing_done.wait()
2887
        c2.set('one', 'c2')
2888
        self.assertEquals('c2', c2.get('one'))
2889
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2890
    def test_read_while_writing(self):
2891
       c1 = self.stack
2892
       # We spawn a thread that will pause *during* the write
2893
       ready_to_write = threading.Event()
2894
       do_writing = threading.Event()
2895
       writing_done = threading.Event()
2896
       # We override the _save implementation so we know the store is locked
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2897
       c1_save_without_locking_orig = c1.store.save_without_locking
2898
       def c1_save_without_locking():
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2899
           ready_to_write.set()
2900
           # The lock is held. We wait for the main thread to decide when to
2901
           # continue
2902
           do_writing.wait()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2903
           c1_save_without_locking_orig()
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2904
           writing_done.set()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2905
       c1.store.save_without_locking = c1_save_without_locking
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2906
       def c1_set():
2907
           c1.set('one', 'c1')
2908
       t1 = threading.Thread(target=c1_set)
2909
       # Collect the thread after the test
2910
       self.addCleanup(t1.join)
2911
       # Be ready to unblock the thread if the test goes wrong
2912
       self.addCleanup(do_writing.set)
2913
       t1.start()
2914
       # Ensure the thread is ready to write
2915
       ready_to_write.wait()
2916
       self.assertEquals('c1', c1.get('one'))
2917
       # If we read during the write, we get the old value
2918
       c2 = self.get_stack(self)
2919
       self.assertEquals('1', c2.get('one'))
2920
       # Let the writing occur and ensure it occurred
2921
       do_writing.set()
2922
       writing_done.wait()
2923
       # Now we get the updated value
2924
       c3 = self.get_stack(self)
2925
       self.assertEquals('c1', c3.get('one'))
2926
2927
    # FIXME: It may be worth looking into removing the lock dir when it's not
2928
    # needed anymore and look at possible fallouts for concurrent lockers. This
2929
    # will matter if/when we use config files outside of bazaar directories
2930
    # (.bazaar or .bzr) -- vila 20110-04-11
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2931
2932
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2933
class TestSectionMatcher(TestStore):
2934
2935
    scenarios = [('location', {'matcher': config.LocationMatcher})]
2936
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2937
    def get_store(self, file_name):
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2938
        return config.IniFileStore(self.get_readonly_transport(), file_name)
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2939
2940
    def test_no_matches_for_empty_stores(self):
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2941
        store = self.get_store('foo.conf')
2942
        store._load_from_string('')
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2943
        matcher = self.matcher(store, '/bar')
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2944
        self.assertEquals([], list(matcher.get_sections()))
2945
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2946
    def test_build_doesnt_load_store(self):
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2947
        store = self.get_store('foo.conf')
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2948
        matcher = self.matcher(store, '/bar')
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2949
        self.assertFalse(store.is_loaded())
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2950
2951
2952
class TestLocationSection(tests.TestCase):
2953
2954
    def get_section(self, options, extra_path):
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2955
        section = config.Section('foo', options)
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2956
        # We don't care about the length so we use '0'
2957
        return config.LocationSection(section, 0, extra_path)
2958
2959
    def test_simple_option(self):
2960
        section = self.get_section({'foo': 'bar'}, '')
2961
        self.assertEquals('bar', section.get('foo'))
2962
2963
    def test_option_with_extra_path(self):
2964
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
2965
                                   'baz')
2966
        self.assertEquals('bar/baz', section.get('foo'))
2967
2968
    def test_invalid_policy(self):
2969
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
2970
                                   'baz')
2971
        # invalid policies are ignored
2972
        self.assertEquals('bar', section.get('foo'))
2973
2974
2975
class TestLocationMatcher(TestStore):
2976
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2977
    def get_store(self, file_name):
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2978
        return config.IniFileStore(self.get_readonly_transport(), file_name)
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2979
6015.22.1 by Vincent Ladeuil
config.LocationMatcher properly excludes unrelated sections
2980
    def test_unrelated_section_excluded(self):
2981
        store = self.get_store('foo.conf')
2982
        store._load_from_string('''
2983
[/foo]
2984
section=/foo
2985
[/foo/baz]
2986
section=/foo/baz
2987
[/foo/bar]
2988
section=/foo/bar
2989
[/foo/bar/baz]
2990
section=/foo/bar/baz
2991
[/quux/quux]
2992
section=/quux/quux
2993
''')
2994
        self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
2995
                           '/quux/quux'],
2996
                          [section.id for section in store.get_sections()])
2997
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
2998
        sections = list(matcher.get_sections())
2999
        self.assertEquals([3, 2],
3000
                          [section.length for section in sections])
3001
        self.assertEquals(['/foo/bar', '/foo'],
3002
                          [section.id for section in sections])
3003
        self.assertEquals(['quux', 'bar/quux'],
3004
                          [section.extra_path for section in sections])
3005
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3006
    def test_more_specific_sections_first(self):
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
3007
        store = self.get_store('foo.conf')
3008
        store._load_from_string('''
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3009
[/foo]
3010
section=/foo
3011
[/foo/bar]
3012
section=/foo/bar
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
3013
''')
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3014
        self.assertEquals(['/foo', '/foo/bar'],
3015
                          [section.id for section in store.get_sections()])
3016
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
3017
        sections = list(matcher.get_sections())
3018
        self.assertEquals([3, 2],
3019
                          [section.length for section in sections])
3020
        self.assertEquals(['/foo/bar', '/foo'],
3021
                          [section.id for section in sections])
3022
        self.assertEquals(['baz', 'bar/baz'],
3023
                          [section.extra_path for section in sections])
3024
5743.6.18 by Vincent Ladeuil
Add a test for appendpath support in no-name section.
3025
    def test_appendpath_in_no_name_section(self):
3026
        # It's a bit weird to allow appendpath in a no-name section, but
3027
        # someone may found a use for it
3028
        store = self.get_store('foo.conf')
3029
        store._load_from_string('''
3030
foo=bar
3031
foo:policy = appendpath
3032
''')
3033
        matcher = config.LocationMatcher(store, 'dir/subdir')
3034
        sections = list(matcher.get_sections())
3035
        self.assertLength(1, sections)
3036
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
3037
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
3038
    def test_file_urls_are_normalized(self):
3039
        store = self.get_store('foo.conf')
5912.3.1 by Vincent Ladeuil
Fix spurious windows-specific test failure
3040
        if sys.platform == 'win32':
3041
            expected_url = 'file:///C:/dir/subdir'
3042
            expected_location = 'C:/dir/subdir'
3043
        else:
3044
            expected_url = 'file:///dir/subdir'
3045
            expected_location = '/dir/subdir'
3046
        matcher = config.LocationMatcher(store, expected_url)
3047
        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).
3048
5743.1.20 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
3049
5743.1.35 by Vincent Ladeuil
Address some review comments from jelmer and poolie.
3050
class TestStackGet(tests.TestCase):
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
3051
5743.1.35 by Vincent Ladeuil
Address some review comments from jelmer and poolie.
3052
    # 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.
3053
    # paramerized tests created to avoid bloating -- vila 2011-03-31
3054
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
3055
    def overrideOptionRegistry(self):
3056
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3057
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
3058
    def test_single_config_get(self):
3059
        conf = dict(foo='bar')
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
3060
        conf_stack = config.Stack([conf])
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
3061
        self.assertEquals('bar', conf_stack.get('foo'))
3062
5743.12.7 by Vincent Ladeuil
Test that providing a default value doesn't break for non-registered options.
3063
    def test_get_with_registered_default_value(self):
5743.12.6 by Vincent Ladeuil
Stack.get() provides the registered option default value.
3064
        conf_stack = config.Stack([dict()])
3065
        opt = config.Option('foo', default='bar')
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
3066
        self.overrideOptionRegistry()
5743.12.6 by Vincent Ladeuil
Stack.get() provides the registered option default value.
3067
        config.option_registry.register('foo', opt)
3068
        self.assertEquals('bar', conf_stack.get('foo'))
3069
5743.12.7 by Vincent Ladeuil
Test that providing a default value doesn't break for non-registered options.
3070
    def test_get_without_registered_default_value(self):
3071
        conf_stack = config.Stack([dict()])
3072
        opt = config.Option('foo')
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
3073
        self.overrideOptionRegistry()
5743.12.7 by Vincent Ladeuil
Test that providing a default value doesn't break for non-registered options.
3074
        config.option_registry.register('foo', opt)
3075
        self.assertEquals(None, conf_stack.get('foo'))
3076
3077
    def test_get_without_default_value_for_not_registered(self):
3078
        conf_stack = config.Stack([dict()])
3079
        opt = config.Option('foo')
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
3080
        self.overrideOptionRegistry()
5743.12.7 by Vincent Ladeuil
Test that providing a default value doesn't break for non-registered options.
3081
        self.assertEquals(None, conf_stack.get('foo'))
3082
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
3083
    def test_get_first_definition(self):
3084
        conf1 = dict(foo='bar')
3085
        conf2 = dict(foo='baz')
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
3086
        conf_stack = config.Stack([conf1, conf2])
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
3087
        self.assertEquals('bar', conf_stack.get('foo'))
3088
5743.1.2 by Vincent Ladeuil
Stacks can be used as read-only sections.
3089
    def test_get_embedded_definition(self):
3090
        conf1 = dict(yy='12')
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
3091
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
3092
        conf_stack = config.Stack([conf1, conf2])
5743.1.2 by Vincent Ladeuil
Stacks can be used as read-only sections.
3093
        self.assertEquals('baz', conf_stack.get('foo'))
3094
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
3095
    def test_get_for_empty_section_callable(self):
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
3096
        conf_stack = config.Stack([lambda : []])
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
3097
        self.assertEquals(None, conf_stack.get('foo'))
3098
5743.1.35 by Vincent Ladeuil
Address some review comments from jelmer and poolie.
3099
    def test_get_for_broken_callable(self):
3100
        # Trying to use and invalid callable raises an exception on first use
3101
        conf_stack = config.Stack([lambda : object()])
3102
        self.assertRaises(TypeError, conf_stack.get, 'foo')
3103
3104
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3105
class TestStackWithTransport(tests.TestCaseWithTransport):
3106
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
3107
    scenarios = [(key, {'get_stack': builder}) for key, builder
3108
                 in config.test_stack_builder_registry.iteritems()]
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3109
3110
5743.11.1 by Vincent Ladeuil
Add a note about config store builders being called several times by some tests.
3111
class TestConcreteStacks(TestStackWithTransport):
3112
3113
    def test_build_stack(self):
3114
        # Just a smoke test to help debug builders
3115
        stack = self.get_stack(self)
3116
3117
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3118
class TestStackGet(TestStackWithTransport):
3119
6059.1.1 by Vincent Ladeuil
Implement from_unicode to convert config option values from store.
3120
    def setUp(self):
3121
        super(TestStackGet, self).setUp()
3122
        self.conf = self.get_stack(self)
3123
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3124
    def test_get_for_empty_stack(self):
6059.1.1 by Vincent Ladeuil
Implement from_unicode to convert config option values from store.
3125
        self.assertEquals(None, self.conf.get('foo'))
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3126
3127
    def test_get_hook(self):
6059.1.1 by Vincent Ladeuil
Implement from_unicode to convert config option values from store.
3128
        self.conf.store._load_from_string('foo=bar')
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3129
        calls = []
3130
        def hook(*args):
3131
            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.
3132
        config.ConfigHooks.install_named_hook('get', hook, None)
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3133
        self.assertLength(0, calls)
6059.1.1 by Vincent Ladeuil
Implement from_unicode to convert config option values from store.
3134
        value = self.conf.get('foo')
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3135
        self.assertEquals('bar', value)
3136
        self.assertLength(1, calls)
6059.1.1 by Vincent Ladeuil
Implement from_unicode to convert config option values from store.
3137
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3138
3139
3140
class TestStackGetWithConverter(TestStackGet):
3141
3142
    def setUp(self):
3143
        super(TestStackGetWithConverter, self).setUp()
3144
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3145
        self.registry = config.option_registry
3146
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3147
    def register_bool_option(self, name, default=None, default_from_env=None):
3148
        b = config.Option(name, help='A boolean.',
3149
                          default=default, default_from_env=default_from_env,
3150
                          from_unicode=config.bool_from_store)
6059.1.1 by Vincent Ladeuil
Implement from_unicode to convert config option values from store.
3151
        self.registry.register(b)
3152
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3153
    def test_get_default_bool_None(self):
3154
        self.register_bool_option('foo')
3155
        self.assertEquals(None, self.conf.get('foo'))
3156
3157
    def test_get_default_bool_True(self):
3158
        self.register_bool_option('foo', u'True')
3159
        self.assertEquals(True, self.conf.get('foo'))
3160
3161
    def test_get_default_bool_False(self):
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
3162
        self.register_bool_option('foo', False)
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3163
        self.assertEquals(False, self.conf.get('foo'))
3164
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
3165
    def test_get_default_bool_False_as_string(self):
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3166
        self.register_bool_option('foo', u'False')
3167
        self.assertEquals(False, self.conf.get('foo'))
3168
6091.3.3 by Vincent Ladeuil
Update registered option default values and also convert the default value if the first conversion fails.
3169
    def test_get_default_bool_from_env_converted(self):
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3170
        self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3171
        self.overrideEnv('FOO', 'False')
3172
        self.assertEquals(False, self.conf.get('foo'))
3173
6091.3.3 by Vincent Ladeuil
Update registered option default values and also convert the default value if the first conversion fails.
3174
    def test_get_default_bool_when_conversion_fails(self):
3175
        self.register_bool_option('foo', default='True')
3176
        self.conf.store._load_from_string('foo=invalid boolean')
3177
        self.assertEquals(True, self.conf.get('foo'))
3178
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3179
    def register_integer_option(self, name,
3180
                                default=None, default_from_env=None):
3181
        i = config.Option(name, help='An integer.',
3182
                          default=default, default_from_env=default_from_env,
6059.1.6 by Vincent Ladeuil
Implement integer config options.
3183
                          from_unicode=config.int_from_store)
3184
        self.registry.register(i)
3185
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3186
    def test_get_default_integer_None(self):
3187
        self.register_integer_option('foo')
3188
        self.assertEquals(None, self.conf.get('foo'))
3189
3190
    def test_get_default_integer(self):
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
3191
        self.register_integer_option('foo', 42)
3192
        self.assertEquals(42, self.conf.get('foo'))
3193
3194
    def test_get_default_integer_as_string(self):
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3195
        self.register_integer_option('foo', u'42')
6059.1.6 by Vincent Ladeuil
Implement integer config options.
3196
        self.assertEquals(42, self.conf.get('foo'))
3197
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3198
    def test_get_default_integer_from_env(self):
3199
        self.register_integer_option('foo', default_from_env=['FOO'])
3200
        self.overrideEnv('FOO', '18')
3201
        self.assertEquals(18, self.conf.get('foo'))
3202
6091.3.3 by Vincent Ladeuil
Update registered option default values and also convert the default value if the first conversion fails.
3203
    def test_get_default_integer_when_conversion_fails(self):
3204
        self.register_integer_option('foo', default='12')
3205
        self.conf.store._load_from_string('foo=invalid integer')
3206
        self.assertEquals(12, self.conf.get('foo'))
3207
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3208
    def register_list_option(self, name, default=None, default_from_env=None):
3209
        l = config.Option(name, help='A list.',
3210
                          default=default, default_from_env=default_from_env,
6059.2.1 by Vincent Ladeuil
Implement list config options.
3211
                          from_unicode=config.list_from_store)
3212
        self.registry.register(l)
3213
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3214
    def test_get_default_list_None(self):
3215
        self.register_list_option('foo')
3216
        self.assertEquals(None, self.conf.get('foo'))
3217
3218
    def test_get_default_list_empty(self):
3219
        self.register_list_option('foo', '')
6059.2.1 by Vincent Ladeuil
Implement list config options.
3220
        self.assertEquals([], self.conf.get('foo'))
3221
6091.3.2 by Vincent Ladeuil
Cleanup now duplicated tests, always convert default value so environment variables can be used for more option types.
3222
    def test_get_default_list_from_env(self):
3223
        self.register_list_option('foo', default_from_env=['FOO'])
3224
        self.overrideEnv('FOO', '')
6059.2.1 by Vincent Ladeuil
Implement list config options.
3225
        self.assertEquals([], self.conf.get('foo'))
3226
3227
    def test_get_with_list_converter_no_item(self):
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
3228
        self.register_list_option('foo', None)
6059.2.1 by Vincent Ladeuil
Implement list config options.
3229
        self.conf.store._load_from_string('foo=,')
3230
        self.assertEquals([], self.conf.get('foo'))
3231
3232
    def test_get_with_list_converter_many_items(self):
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
3233
        self.register_list_option('foo', None)
6059.2.1 by Vincent Ladeuil
Implement list config options.
3234
        self.conf.store._load_from_string('foo=m,o,r,e')
3235
        self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
3236
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3237
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3238
class TestStackSet(TestStackWithTransport):
3239
5743.1.7 by Vincent Ladeuil
Simple set implementation.
3240
    def test_simple_set(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3241
        conf = self.get_stack(self)
3242
        conf.store._load_from_string('foo=bar')
5743.1.7 by Vincent Ladeuil
Simple set implementation.
3243
        self.assertEquals('bar', conf.get('foo'))
3244
        conf.set('foo', 'baz')
3245
        # Did we get it back ?
3246
        self.assertEquals('baz', conf.get('foo'))
3247
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.
3248
    def test_set_creates_a_new_section(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3249
        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.
3250
        conf.set('foo', 'baz')
5743.1.9 by Vincent Ladeuil
Fix the issue by allowing delayed section acquisition.
3251
        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.
3252
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3253
    def test_set_hook(self):
3254
        calls = []
3255
        def hook(*args):
3256
            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.
3257
        config.ConfigHooks.install_named_hook('set', hook, None)
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3258
        self.assertLength(0, calls)
3259
        conf = self.get_stack(self)
3260
        conf.set('foo', 'bar')
3261
        self.assertLength(1, calls)
3262
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
3263
5743.1.7 by Vincent Ladeuil
Simple set implementation.
3264
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3265
class TestStackRemove(TestStackWithTransport):
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
3266
3267
    def test_remove_existing(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3268
        conf = self.get_stack(self)
3269
        conf.store._load_from_string('foo=bar')
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
3270
        self.assertEquals('bar', conf.get('foo'))
3271
        conf.remove('foo')
3272
        # Did we get it back ?
3273
        self.assertEquals(None, conf.get('foo'))
3274
3275
    def test_remove_unknown(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3276
        conf = self.get_stack(self)
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
3277
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3278
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3279
    def test_remove_hook(self):
3280
        calls = []
3281
        def hook(*args):
3282
            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.
3283
        config.ConfigHooks.install_named_hook('remove', hook, None)
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3284
        self.assertLength(0, calls)
3285
        conf = self.get_stack(self)
3286
        conf.store._load_from_string('foo=bar')
3287
        conf.remove('foo')
3288
        self.assertLength(1, calls)
3289
        self.assertEquals((conf, 'foo'), calls[0])
3290
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
3291
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
3292
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
3293
3294
    def setUp(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
3295
        super(TestConfigGetOptions, self).setUp()
3296
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
3297
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
3298
    def test_no_variable(self):
3299
        # 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.
3300
        self.assertOptions([], self.branch_config)
3301
3302
    def test_option_in_bazaar(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
3303
        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.
3304
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
3305
                           self.bazaar_config)
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
3306
3307
    def test_option_in_locations(self):
3308
        self.locations_config.set_user_option('file', 'locations')
3309
        self.assertOptions(
3310
            [('file', 'locations', self.tree.basedir, 'locations')],
3311
            self.locations_config)
3312
3313
    def test_option_in_branch(self):
3314
        self.branch_config.set_user_option('file', 'branch')
3315
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
3316
                           self.branch_config)
3317
3318
    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.
3319
        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.
3320
        self.branch_config.set_user_option('file', 'branch')
3321
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
3322
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3323
                           self.branch_config)
3324
3325
    def test_option_in_branch_and_locations(self):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
3326
        # Hmm, locations override branch :-/
3327
        self.locations_config.set_user_option('file', 'locations')
3328
        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.
3329
        self.assertOptions(
3330
            [('file', 'locations', self.tree.basedir, 'locations'),
3331
             ('file', 'branch', 'DEFAULT', 'branch'),],
3332
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
3333
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
3334
    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.
3335
        self.bazaar_config.set_user_option('file', 'bazaar')
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
3336
        self.locations_config.set_user_option('file', 'locations')
3337
        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.
3338
        self.assertOptions(
3339
            [('file', 'locations', self.tree.basedir, 'locations'),
3340
             ('file', 'branch', 'DEFAULT', 'branch'),
3341
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3342
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
3343
3344
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
3345
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
3346
3347
    def setUp(self):
3348
        super(TestConfigRemoveOption, self).setUp()
3349
        create_configs_with_file_option(self)
3350
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
3351
    def test_remove_in_locations(self):
3352
        self.locations_config.remove_user_option('file', self.tree.basedir)
3353
        self.assertOptions(
3354
            [('file', 'branch', 'DEFAULT', 'branch'),
3355
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3356
            self.branch_config)
3357
3358
    def test_remove_in_branch(self):
3359
        self.branch_config.remove_user_option('file')
3360
        self.assertOptions(
3361
            [('file', 'locations', self.tree.basedir, 'locations'),
3362
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3363
            self.branch_config)
3364
3365
    def test_remove_in_bazaar(self):
3366
        self.bazaar_config.remove_user_option('file')
3367
        self.assertOptions(
3368
            [('file', 'locations', self.tree.basedir, 'locations'),
3369
             ('file', 'branch', 'DEFAULT', 'branch'),],
3370
            self.branch_config)
3371
5447.4.7 by Vincent Ladeuil
Check error message if the test is checking for errors or we have unexpected success for wrong errors.
3372
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
3373
class TestConfigGetSections(tests.TestCaseWithTransport):
3374
3375
    def setUp(self):
3376
        super(TestConfigGetSections, self).setUp()
3377
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
3378
3379
    def assertSectionNames(self, expected, conf, name=None):
3380
        """Check which sections are returned for a given config.
3381
3382
        If fallback configurations exist their sections can be included.
3383
3384
        :param expected: A list of section names.
3385
3386
        :param conf: The configuration that will be queried.
3387
3388
        :param name: An optional section name that will be passed to
3389
            get_sections().
3390
        """
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.
3391
        sections = list(conf._get_sections(name))
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
3392
        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.
3393
        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.
3394
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
3395
    def test_bazaar_default_section(self):
3396
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
3397
3398
    def test_locations_default_section(self):
3399
        # No sections are defined in an empty file
3400
        self.assertSectionNames([], self.locations_config)
3401
3402
    def test_locations_named_section(self):
3403
        self.locations_config.set_user_option('file', 'locations')
3404
        self.assertSectionNames([self.tree.basedir], self.locations_config)
3405
3406
    def test_locations_matching_sections(self):
3407
        loc_config = self.locations_config
3408
        loc_config.set_user_option('file', 'locations')
3409
        # We need to cheat a bit here to create an option in sections above and
3410
        # below the 'location' one.
3411
        parser = loc_config._get_parser()
3412
        # locations.cong deals with '/' ignoring native os.sep
3413
        location_names = self.tree.basedir.split('/')
3414
        parent = '/'.join(location_names[:-1])
3415
        child = '/'.join(location_names + ['child'])
3416
        parser[parent] = {}
3417
        parser[parent]['file'] = 'parent'
3418
        parser[child] = {}
3419
        parser[child]['file'] = 'child'
3420
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
3421
3422
    def test_branch_data_default_section(self):
3423
        self.assertSectionNames([None],
3424
                                self.branch_config._get_branch_data_config())
3425
3426
    def test_branch_default_sections(self):
3427
        # No sections are defined in an empty locations file
3428
        self.assertSectionNames([None, 'DEFAULT'],
3429
                                self.branch_config)
3430
        # Unless we define an option
3431
        self.branch_config._get_location_config().set_user_option(
3432
            'file', 'locations')
3433
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
3434
                                self.branch_config)
3435
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
3436
    def test_bazaar_named_section(self):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
3437
        # We need to cheat as the API doesn't give direct access to sections
3438
        # other than DEFAULT.
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
3439
        self.bazaar_config.set_alias('bazaar', 'bzr')
3440
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
3441
3442
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
3443
class TestAuthenticationConfigFile(tests.TestCase):
2900.2.14 by Vincent Ladeuil
More tests.
3444
    """Test the authentication.conf file matching"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
3445
3446
    def _got_user_passwd(self, expected_user, expected_password,
3447
                         config, *args, **kwargs):
3448
        credentials = config.get_credentials(*args, **kwargs)
3449
        if credentials is None:
3450
            user = None
3451
            password = None
3452
        else:
3453
            user = credentials['user']
3454
            password = credentials['password']
3455
        self.assertEquals(expected_user, user)
3456
        self.assertEquals(expected_password, password)
3457
2978.5.1 by John Arbash Meinel
Fix bug #162494, 'bzr register-branch' needs proper auth handling.
3458
    def test_empty_config(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
3459
        conf = config.AuthenticationConfig(_file=StringIO())
3460
        self.assertEquals({}, conf._get_config())
3461
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
3462
5987.1.2 by Vincent Ladeuil
Reproduce bug #502060, bug #688677 and bug #792246.
3463
    def test_non_utf8_config(self):
3464
        conf = config.AuthenticationConfig(_file=StringIO(
3465
                'foo = bar\xff'))
5987.1.3 by Vincent Ladeuil
Proper message when authentication.conf has non-utf8 content
3466
        self.assertRaises(errors.ConfigContentError, conf._get_config)
6059.1.1 by Vincent Ladeuil
Implement from_unicode to convert config option values from store.
3467
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
3468
    def test_missing_auth_section_header(self):
3469
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
3470
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3471
3472
    def test_auth_section_header_not_closed(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
3473
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
3474
        self.assertRaises(errors.ParseConfigError, conf._get_config)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
3475
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
3476
    def test_auth_value_not_boolean(self):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
3477
        conf = config.AuthenticationConfig(_file=StringIO(
3478
                """[broken]
3479
scheme=ftp
3480
user=joe
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
3481
verify_certificates=askme # Error: Not a boolean
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
3482
"""))
3483
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
3484
3485
    def test_auth_value_not_int(self):
2900.2.22 by Vincent Ladeuil
Polishing.
3486
        conf = config.AuthenticationConfig(_file=StringIO(
3487
                """[broken]
3488
scheme=ftp
3489
user=joe
3490
port=port # Error: Not an int
3491
"""))
3492
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
3493
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
3494
    def test_unknown_password_encoding(self):
3495
        conf = config.AuthenticationConfig(_file=StringIO(
3496
                """[broken]
3497
scheme=ftp
3498
user=joe
3499
password_encoding=unknown
3500
"""))
3501
        self.assertRaises(ValueError, conf.get_password,
3502
                          'ftp', 'foo.net', 'joe')
3503
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
3504
    def test_credentials_for_scheme_host(self):
3505
        conf = config.AuthenticationConfig(_file=StringIO(
3506
                """# Identity on foo.net
3507
[ftp definition]
3508
scheme=ftp
3509
host=foo.net
3510
user=joe
3511
password=secret-pass
3512
"""))
3513
        # Basic matching
3514
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
3515
        # different scheme
3516
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
3517
        # different host
3518
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
3519
3520
    def test_credentials_for_host_port(self):
3521
        conf = config.AuthenticationConfig(_file=StringIO(
3522
                """# Identity on foo.net
3523
[ftp definition]
3524
scheme=ftp
3525
port=10021
3526
host=foo.net
3527
user=joe
3528
password=secret-pass
3529
"""))
3530
        # No port
3531
        self._got_user_passwd('joe', 'secret-pass',
3532
                              conf, 'ftp', 'foo.net', port=10021)
3533
        # different port
3534
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
3535
3536
    def test_for_matching_host(self):
3537
        conf = config.AuthenticationConfig(_file=StringIO(
3538
                """# Identity on foo.net
3539
[sourceforge]
3540
scheme=bzr
3541
host=bzr.sf.net
3542
user=joe
3543
password=joepass
3544
[sourceforge domain]
3545
scheme=bzr
3546
host=.bzr.sf.net
3547
user=georges
3548
password=bendover
3549
"""))
3550
        # matching domain
3551
        self._got_user_passwd('georges', 'bendover',
3552
                              conf, 'bzr', 'foo.bzr.sf.net')
3553
        # phishing attempt
3554
        self._got_user_passwd(None, None,
3555
                              conf, 'bzr', 'bbzr.sf.net')
3556
3557
    def test_for_matching_host_None(self):
3558
        conf = config.AuthenticationConfig(_file=StringIO(
3559
                """# Identity on foo.net
3560
[catchup bzr]
3561
scheme=bzr
3562
user=joe
3563
password=joepass
3564
[DEFAULT]
3565
user=georges
3566
password=bendover
3567
"""))
3568
        # match no host
3569
        self._got_user_passwd('joe', 'joepass',
3570
                              conf, 'bzr', 'quux.net')
3571
        # no host but different scheme
3572
        self._got_user_passwd('georges', 'bendover',
3573
                              conf, 'ftp', 'quux.net')
3574
3575
    def test_credentials_for_path(self):
3576
        conf = config.AuthenticationConfig(_file=StringIO(
3577
                """
3578
[http dir1]
3579
scheme=http
3580
host=bar.org
3581
path=/dir1
3582
user=jim
3583
password=jimpass
3584
[http dir2]
3585
scheme=http
3586
host=bar.org
3587
path=/dir2
3588
user=georges
3589
password=bendover
3590
"""))
3591
        # no path no dice
3592
        self._got_user_passwd(None, None,
3593
                              conf, 'http', host='bar.org', path='/dir3')
3594
        # matching path
3595
        self._got_user_passwd('georges', 'bendover',
3596
                              conf, 'http', host='bar.org', path='/dir2')
3597
        # matching subdir
3598
        self._got_user_passwd('jim', 'jimpass',
3599
                              conf, 'http', host='bar.org',path='/dir1/subdir')
3600
3601
    def test_credentials_for_user(self):
3602
        conf = config.AuthenticationConfig(_file=StringIO(
3603
                """
3604
[with user]
3605
scheme=http
3606
host=bar.org
3607
user=jim
3608
password=jimpass
3609
"""))
3610
        # Get user
3611
        self._got_user_passwd('jim', 'jimpass',
3612
                              conf, 'http', 'bar.org')
3613
        # Get same user
3614
        self._got_user_passwd('jim', 'jimpass',
3615
                              conf, 'http', 'bar.org', user='jim')
3616
        # Don't get a different user if one is specified
3617
        self._got_user_passwd(None, None,
3618
                              conf, 'http', 'bar.org', user='georges')
3619
3418.4.1 by Vincent Ladeuil
Reproduce bug 199440.
3620
    def test_credentials_for_user_without_password(self):
3621
        conf = config.AuthenticationConfig(_file=StringIO(
3622
                """
3623
[without password]
3624
scheme=http
3625
host=bar.org
3626
user=jim
3627
"""))
3628
        # Get user but no password
3629
        self._got_user_passwd('jim', None,
3630
                              conf, 'http', 'bar.org')
3631
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
3632
    def test_verify_certificates(self):
3633
        conf = config.AuthenticationConfig(_file=StringIO(
3634
                """
3635
[self-signed]
3636
scheme=https
3637
host=bar.org
3638
user=jim
3639
password=jimpass
3640
verify_certificates=False
3641
[normal]
3642
scheme=https
3643
host=foo.net
3644
user=georges
3645
password=bendover
3646
"""))
3647
        credentials = conf.get_credentials('https', 'bar.org')
3648
        self.assertEquals(False, credentials.get('verify_certificates'))
3649
        credentials = conf.get_credentials('https', 'foo.net')
3650
        self.assertEquals(True, credentials.get('verify_certificates'))
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
3651
3777.1.10 by Aaron Bentley
Ensure credentials are stored
3652
3653
class TestAuthenticationStorage(tests.TestCaseInTempDir):
3654
3777.1.8 by Aaron Bentley
Commit work-in-progress
3655
    def test_set_credentials(self):
3777.1.10 by Aaron Bentley
Ensure credentials are stored
3656
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
3657
        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
3658
        99, path='/foo', verify_certificates=False, realm='realm')
3777.1.8 by Aaron Bentley
Commit work-in-progress
3659
        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
3660
                                           port=99, path='/foo',
3661
                                           realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
3662
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
3663
                       'verify_certificates': False, 'scheme': 'scheme', 
3664
                       'host': 'host', 'port': 99, 'path': '/foo', 
3665
                       'realm': 'realm'}
3777.1.10 by Aaron Bentley
Ensure credentials are stored
3666
        self.assertEqual(CREDENTIALS, credentials)
3667
        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
3668
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
3669
        self.assertEqual(CREDENTIALS, credentials_from_disk)
3777.1.8 by Aaron Bentley
Commit work-in-progress
3670
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
3671
    def test_reset_credentials_different_name(self):
3672
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
3673
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
3674
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
3675
        self.assertIs(None, conf._get_config().get('name'))
3676
        credentials = conf.get_credentials(host='host', scheme='scheme')
3677
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
3678
                       'password', 'verify_certificates': True, 
3679
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
3680
                       'path': None, 'realm': None}
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
3681
        self.assertEqual(CREDENTIALS, credentials)
3682
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
3683
2900.2.14 by Vincent Ladeuil
More tests.
3684
class TestAuthenticationConfig(tests.TestCase):
3685
    """Test AuthenticationConfig behaviour"""
3686
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
3687
    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.
3688
                                       host=None, port=None, realm=None,
3689
                                       path=None):
2900.2.14 by Vincent Ladeuil
More tests.
3690
        if host is None:
3691
            host = 'bar.org'
3692
        user, password = 'jim', 'precious'
3693
        expected_prompt = expected_prompt_format % {
3694
            'scheme': scheme, 'host': host, 'port': port,
3695
            'user': user, 'realm': realm}
3696
3697
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
3698
        stderr = tests.StringIOWrapper()
2900.2.14 by Vincent Ladeuil
More tests.
3699
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
3700
                                            stdout=stdout, stderr=stderr)
2900.2.14 by Vincent Ladeuil
More tests.
3701
        # We use an empty conf so that the user is always prompted
3702
        conf = config.AuthenticationConfig()
3703
        self.assertEquals(password,
3704
                          conf.get_password(scheme, host, user, port=port,
3705
                                            realm=realm, path=path))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
3706
        self.assertEquals(expected_prompt, stderr.getvalue())
3707
        self.assertEquals('', stdout.getvalue())
2900.2.14 by Vincent Ladeuil
More tests.
3708
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3709
    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.
3710
                                       host=None, port=None, realm=None,
3711
                                       path=None):
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3712
        if host is None:
3713
            host = 'bar.org'
3714
        username = 'jim'
3715
        expected_prompt = expected_prompt_format % {
3716
            'scheme': scheme, 'host': host, 'port': port,
3717
            'realm': realm}
3718
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
3719
        stderr = tests.StringIOWrapper()
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3720
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
3721
                                            stdout=stdout, stderr=stderr)
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3722
        # We use an empty conf so that the user is always prompted
3723
        conf = config.AuthenticationConfig()
4222.3.5 by Jelmer Vernooij
Fix test.
3724
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
3725
                          realm=realm, path=path, ask=True))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
3726
        self.assertEquals(expected_prompt, stderr.getvalue())
3727
        self.assertEquals('', stdout.getvalue())
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3728
3729
    def test_username_defaults_prompts(self):
3730
        # 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.
3731
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
3732
        self._check_default_username_prompt(
3733
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
3734
        self._check_default_username_prompt(
3735
            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.
3736
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
3737
    def test_username_default_no_prompt(self):
3738
        conf = config.AuthenticationConfig()
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
3739
        self.assertEquals(None,
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
3740
            conf.get_user('ftp', 'example.com'))
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
3741
        self.assertEquals("explicitdefault",
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
3742
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
3743
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
3744
    def test_password_default_prompts(self):
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
3745
        # HTTP prompts can't be tested here, see test_http.py
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
3746
        self._check_default_password_prompt(
5923.1.3 by Vincent Ladeuil
Even more unicode prompts fixes revealed by pqm.
3747
            u'FTP %(user)s@%(host)s password: ', 'ftp')
3748
        self._check_default_password_prompt(
3749
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
3750
        self._check_default_password_prompt(
3751
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
2900.2.14 by Vincent Ladeuil
More tests.
3752
        # SMTP port handling is a bit special (it's handled if embedded in the
3753
        # host too)
2900.2.22 by Vincent Ladeuil
Polishing.
3754
        # FIXME: should we: forbid that, extend it to other schemes, leave
3755
        # things as they are that's fine thank you ?
5923.1.3 by Vincent Ladeuil
Even more unicode prompts fixes revealed by pqm.
3756
        self._check_default_password_prompt(
3757
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
3758
        self._check_default_password_prompt(
3759
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
3760
        self._check_default_password_prompt(
3761
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
2900.2.14 by Vincent Ladeuil
More tests.
3762
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
3763
    def test_ssh_password_emits_warning(self):
3764
        conf = config.AuthenticationConfig(_file=StringIO(
3765
                """
3766
[ssh with password]
3767
scheme=ssh
3768
host=bar.org
3769
user=jim
3770
password=jimpass
3771
"""))
3772
        entered_password = 'typed-by-hand'
3773
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
3774
        stderr = tests.StringIOWrapper()
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
3775
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
3776
                                            stdout=stdout, stderr=stderr)
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
3777
3778
        # Since the password defined in the authentication config is ignored,
3779
        # the user is prompted
3780
        self.assertEquals(entered_password,
3781
                          conf.get_password('ssh', 'bar.org', user='jim'))
3782
        self.assertContainsRe(
4794.1.17 by Robert Collins
Fix from vila for type log_log.
3783
            self.get_log(),
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
3784
            'password ignored in section \[ssh with password\]')
3785
3420.1.3 by Vincent Ladeuil
John's review feedback.
3786
    def test_ssh_without_password_doesnt_emit_warning(self):
3787
        conf = config.AuthenticationConfig(_file=StringIO(
3788
                """
3789
[ssh with password]
3790
scheme=ssh
3791
host=bar.org
3792
user=jim
3793
"""))
3794
        entered_password = 'typed-by-hand'
3795
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
3796
        stderr = tests.StringIOWrapper()
3420.1.3 by Vincent Ladeuil
John's review feedback.
3797
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
3798
                                            stdout=stdout,
3799
                                            stderr=stderr)
3420.1.3 by Vincent Ladeuil
John's review feedback.
3800
3801
        # Since the password defined in the authentication config is ignored,
3802
        # the user is prompted
3803
        self.assertEquals(entered_password,
3804
                          conf.get_password('ssh', 'bar.org', user='jim'))
3420.1.4 by Vincent Ladeuil
Fix comment.
3805
        # No warning shoud be emitted since there is no password. We are only
3806
        # providing "user".
3420.1.3 by Vincent Ladeuil
John's review feedback.
3807
        self.assertNotContainsRe(
4794.1.15 by Robert Collins
Review feedback.
3808
            self.get_log(),
3420.1.3 by Vincent Ladeuil
John's review feedback.
3809
            'password ignored in section \[ssh with password\]')
3810
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
3811
    def test_uses_fallback_stores(self):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
3812
        self.overrideAttr(config, 'credential_store_registry',
3813
                          config.CredentialStoreRegistry())
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
3814
        store = StubCredentialStore()
3815
        store.add_credentials("http", "example.com", "joe", "secret")
3816
        config.credential_store_registry.register("stub", store, fallback=True)
3817
        conf = config.AuthenticationConfig(_file=StringIO())
3818
        creds = conf.get_credentials("http", "example.com")
3819
        self.assertEquals("joe", creds["user"])
3820
        self.assertEquals("secret", creds["password"])
3821
2900.2.14 by Vincent Ladeuil
More tests.
3822
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3823
class StubCredentialStore(config.CredentialStore):
3824
3825
    def __init__(self):
3826
        self._username = {}
3827
        self._password = {}
3828
3829
    def add_credentials(self, scheme, host, user, password=None):
3830
        self._username[(scheme, host)] = user
3831
        self._password[(scheme, host)] = password
3832
3833
    def get_credentials(self, scheme, host, port=None, user=None,
3834
        path=None, realm=None):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3835
        key = (scheme, host)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3836
        if not key in self._username:
3837
            return None
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3838
        return { "scheme": scheme, "host": host, "port": port,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3839
                "user": self._username[key], "password": self._password[key]}
3840
3841
3842
class CountingCredentialStore(config.CredentialStore):
3843
3844
    def __init__(self):
3845
        self._calls = 0
3846
3847
    def get_credentials(self, scheme, host, port=None, user=None,
3848
        path=None, realm=None):
3849
        self._calls += 1
3850
        return None
3851
3852
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
3853
class TestCredentialStoreRegistry(tests.TestCase):
3854
3855
    def _get_cs_registry(self):
3856
        return config.credential_store_registry
3857
3858
    def test_default_credential_store(self):
3859
        r = self._get_cs_registry()
3860
        default = r.get_credential_store(None)
3861
        self.assertIsInstance(default, config.PlainTextCredentialStore)
3862
3863
    def test_unknown_credential_store(self):
3864
        r = self._get_cs_registry()
3865
        # It's hard to imagine someone creating a credential store named
3866
        # 'unknown' so we use that as an never registered key.
3867
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
3868
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3869
    def test_fallback_none_registered(self):
3870
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3871
        self.assertEquals(None,
3872
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3873
3874
    def test_register(self):
3875
        r = config.CredentialStoreRegistry()
3876
        r.register("stub", StubCredentialStore(), fallback=False)
3877
        r.register("another", StubCredentialStore(), fallback=True)
3878
        self.assertEquals(["another", "stub"], r.keys())
3879
3880
    def test_register_lazy(self):
3881
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3882
        r.register_lazy("stub", "bzrlib.tests.test_config",
3883
                        "StubCredentialStore", fallback=False)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3884
        self.assertEquals(["stub"], r.keys())
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3885
        self.assertIsInstance(r.get_credential_store("stub"),
3886
                              StubCredentialStore)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3887
3888
    def test_is_fallback(self):
3889
        r = config.CredentialStoreRegistry()
3890
        r.register("stub1", None, fallback=False)
3891
        r.register("stub2", None, fallback=True)
3892
        self.assertEquals(False, r.is_fallback("stub1"))
3893
        self.assertEquals(True, r.is_fallback("stub2"))
3894
3895
    def test_no_fallback(self):
3896
        r = config.CredentialStoreRegistry()
3897
        store = CountingCredentialStore()
3898
        r.register("count", store, fallback=False)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3899
        self.assertEquals(None,
3900
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3901
        self.assertEquals(0, store._calls)
3902
3903
    def test_fallback_credentials(self):
3904
        r = config.CredentialStoreRegistry()
3905
        store = StubCredentialStore()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3906
        store.add_credentials("http", "example.com",
3907
                              "somebody", "geheim")
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3908
        r.register("stub", store, fallback=True)
3909
        creds = r.get_fallback_credentials("http", "example.com")
3910
        self.assertEquals("somebody", creds["user"])
3911
        self.assertEquals("geheim", creds["password"])
3912
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3913
    def test_fallback_first_wins(self):
3914
        r = config.CredentialStoreRegistry()
3915
        stub1 = StubCredentialStore()
3916
        stub1.add_credentials("http", "example.com",
3917
                              "somebody", "stub1")
3918
        r.register("stub1", stub1, fallback=True)
3919
        stub2 = StubCredentialStore()
3920
        stub2.add_credentials("http", "example.com",
3921
                              "somebody", "stub2")
3922
        r.register("stub2", stub1, fallback=True)
3923
        creds = r.get_fallback_credentials("http", "example.com")
3924
        self.assertEquals("somebody", creds["user"])
3925
        self.assertEquals("stub1", creds["password"])
3926
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
3927
3928
class TestPlainTextCredentialStore(tests.TestCase):
3929
3930
    def test_decode_password(self):
3931
        r = config.credential_store_registry
3932
        plain_text = r.get_credential_store()
3933
        decoded = plain_text.decode_password(dict(password='secret'))
3934
        self.assertEquals('secret', decoded)
3935
3936
2900.2.14 by Vincent Ladeuil
More tests.
3937
# 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.
3938
# can implement generic tests.
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
3939
# test_user_password_in_url
3940
# test_user_in_url_password_from_config
3941
# test_user_in_url_password_prompted
3942
# test_user_in_config
3943
# test_user_getpass.getuser
3944
# test_user_prompted ?
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
3945
class TestAuthenticationRing(tests.TestCaseWithTransport):
3946
    pass
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
3947
3948
3949
class TestAutoUserId(tests.TestCase):
3950
    """Test inferring an automatic user name."""
3951
3952
    def test_auto_user_id(self):
3953
        """Automatic inference of user name.
3954
        
3955
        This is a bit hard to test in an isolated way, because it depends on
3956
        system functions that go direct to /etc or perhaps somewhere else.
3957
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
3958
        to be able to choose a user name with no configuration.
3959
        """
3960
        if sys.platform == 'win32':
5743.8.17 by Vincent Ladeuil
Add config old_get hook for remote config.
3961
            raise tests.TestSkipped(
3962
                "User name inference not implemented on win32")
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
3963
        realname, address = config._auto_user_id()
3964
        if os.path.exists('/etc/mailname'):
5813.1.1 by Jelmer Vernooij
Allow realname to be empty in tests.
3965
            self.assertIsNot(None, realname)
3966
            self.assertIsNot(None, address)
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
3967
        else:
3968
            self.assertEquals((None, None), (realname, address))
3969