/brz/remove-bazaar

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