/brz/remove-bazaar

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