/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,
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
40
    tests,
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
41
    trace,
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
42
    transport,
1878.1.3 by John Arbash Meinel
some test cleanups
43
    )
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
44
from bzrlib.transport import remote
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
45
from bzrlib.tests import (
46
    features,
47
    TestSkipped,
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
48
    scenarios,
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
49
    )
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
50
from bzrlib.util.configobj import configobj
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
51
52
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
53
def lockable_config_scenarios():
54
    return [
55
        ('global',
56
         {'config_class': config.GlobalConfig,
57
          'config_args': [],
58
          'config_section': 'DEFAULT'}),
59
        ('locations',
60
         {'config_class': config.LocationConfig,
61
          'config_args': ['.'],
62
          'config_section': '.'}),]
63
64
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
65
load_tests = scenarios.load_tests_apply_scenarios
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
66
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
67
# Register helpers to build stores
68
config.test_store_builder_registry.register(
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
69
    'configobj', lambda test: config.IniFileStore(test.get_transport(),
70
                                                  'configobj.conf'))
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
71
config.test_store_builder_registry.register(
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
72
    '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
73
config.test_store_builder_registry.register(
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
74
    '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
75
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
76
77
def build_backing_branch(test, relpath,
78
                         transport_class=None, server_class=None):
79
    """Test helper to create a backing branch only once.
80
81
    Some tests needs multiple stores/stacks to check concurrent update
82
    behaviours. As such, they need to build different branch *objects* even if
83
    they share the branch on disk.
84
85
    :param relpath: The relative path to the branch. (Note that the helper
86
        should always specify the same relpath).
87
88
    :param transport_class: The Transport class the test needs to use.
89
90
    :param server_class: The server associated with the ``transport_class``
91
        above.
92
5743.10.9 by Vincent Ladeuil
Fix use of none where neither is required.
93
    Either both or neither of ``transport_class`` and ``server_class`` should
94
    be specified.
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
95
    """
96
    if transport_class is not None and server_class is not None:
97
        test.transport_class = transport_class
98
        test.transport_server = server_class
99
    elif not (transport_class is None and server_class is None):
100
        raise AssertionError('Specify both ``transport_class`` and '
5743.10.9 by Vincent Ladeuil
Fix use of none where neither is required.
101
                             '``server_class`` or neither of them')
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
102
    if getattr(test, 'backing_branch', None) is None:
103
        # First call, let's build the branch on disk
104
        test.backing_branch = test.make_branch(relpath)
105
106
5743.10.11 by Vincent Ladeuil
Remove the duplicated comment so we can make the comment bigger :)
107
def keep_branch_alive(test, b):
108
    """Keep a branch alive for the duration of a test.
109
110
    :param tests: the test that should hold the branch alive.
111
112
    :param b: the branch that should be kept alive.
113
114
    Several tests need to keep a reference to a branch object as they are
115
    testing a Store which uses a weak reference. This is achieved by embedding
116
    a reference to the branch object in a lambda passed to a cleanup. When the
117
    test finish the cleanup method is deleted and so does the reference to the
118
    branch.
119
    """
120
    test.addCleanup(lambda : b)
121
5743.10.12 by Vincent Ladeuil
PEP8
122
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
123
def build_branch_store(test):
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
124
    build_backing_branch(test, 'branch')
125
    b = branch.Branch.open('branch')
5743.10.11 by Vincent Ladeuil
Remove the duplicated comment so we can make the comment bigger :)
126
    keep_branch_alive(test, b)
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
127
    return config.BranchStore(b)
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
128
config.test_store_builder_registry.register('branch', build_branch_store)
129
130
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
131
def build_remote_branch_store(test):
132
    # There is only one permutation (but we won't be able to handle more with
133
    # this design anyway)
134
    (transport_class, server_class) = remote.get_test_permutations()[0]
135
    build_backing_branch(test, 'branch', transport_class, server_class)
136
    b = branch.Branch.open(test.get_url('branch'))
5743.10.11 by Vincent Ladeuil
Remove the duplicated comment so we can make the comment bigger :)
137
    keep_branch_alive(test, b)
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
138
    return config.BranchStore(b)
139
config.test_store_builder_registry.register('remote_branch',
140
                                            build_remote_branch_store)
141
142
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
143
config.test_stack_builder_registry.register(
144
    'bazaar', lambda test: config.GlobalStack())
145
config.test_stack_builder_registry.register(
146
    'location', lambda test: config.LocationStack('.'))
147
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
148
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
149
def build_branch_stack(test):
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
150
    build_backing_branch(test, 'branch')
151
    b = branch.Branch.open('branch')
5743.10.11 by Vincent Ladeuil
Remove the duplicated comment so we can make the comment bigger :)
152
    keep_branch_alive(test, b)
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
153
    return config.BranchStack(b)
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
154
config.test_stack_builder_registry.register('branch', build_branch_stack)
155
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
156
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
157
def build_remote_branch_stack(test):
158
    # There is only one permutation (but we won't be able to handle more with
159
    # this design anyway)
160
    (transport_class, server_class) = remote.get_test_permutations()[0]
161
    build_backing_branch(test, 'branch', transport_class, server_class)
162
    b = branch.Branch.open(test.get_url('branch'))
5743.10.11 by Vincent Ladeuil
Remove the duplicated comment so we can make the comment bigger :)
163
    keep_branch_alive(test, b)
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
164
    return config.BranchStack(b)
165
config.test_stack_builder_registry.register('remote_branch',
166
                                            build_remote_branch_stack)
167
168
1553.6.12 by Erik BÃ¥gfors
remove AliasConfig, based on input from abentley
169
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
170
sample_config_text = u"""
171
[DEFAULT]
172
email=Erik B\u00e5gfors <erik@bagfors.nu>
173
editor=vim
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
174
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
175
gpg_signing_command=gnome-gpg
176
log_format=short
177
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.
178
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
5321.2.3 by Vincent Ladeuil
Prefix mergetools option names with 'bzr.'.
179
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.
180
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
181
[ALIASES]
182
h=help
183
ll=""" + sample_long_alias + "\n"
184
185
186
sample_always_signatures = """
187
[DEFAULT]
188
check_signatures=ignore
189
create_signatures=always
190
"""
191
192
sample_ignore_signatures = """
193
[DEFAULT]
194
check_signatures=require
195
create_signatures=never
196
"""
197
198
sample_maybe_signatures = """
199
[DEFAULT]
200
check_signatures=ignore
201
create_signatures=when-required
202
"""
203
204
sample_branches_text = """
205
[http://www.example.com]
206
# Top level policy
207
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
208
normal_option = normal
209
appendpath_option = append
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
210
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
211
norecurse_option = norecurse
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
212
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
213
[http://www.example.com/ignoreparent]
214
# different project: ignore parent dir config
215
ignore_parents=true
216
[http://www.example.com/norecurse]
217
# configuration items that only apply to this dir
218
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
219
normal_option = norecurse
220
[http://www.example.com/dir]
221
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
222
[/b/]
223
check_signatures=require
224
# test trailing / matching with no children
225
[/a/]
226
check_signatures=check-available
227
gpg_signing_command=false
228
user_local_option=local
229
# test trailing / matching
230
[/a/*]
231
#subdirs will match but not the parent
232
[/a/c]
233
check_signatures=ignore
234
post_commit=bzrlib.tests.test_config.post_commit
235
#testing explicit beats globs
236
"""
1553.6.3 by Erik BÃ¥gfors
tests for AliasesConfig
237
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
238
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
239
def create_configs(test):
240
    """Create configuration files for a given test.
241
242
    This requires creating a tree (and populate the ``test.tree`` attribute)
243
    and its associated branch and will populate the following attributes:
244
245
    - branch_config: A BranchConfig for the associated branch.
246
247
    - locations_config : A LocationConfig for the associated branch
248
249
    - bazaar_config: A GlobalConfig.
250
251
    The tree and branch are created in a 'tree' subdirectory so the tests can
252
    still use the test directory to stay outside of the branch.
253
    """
254
    tree = test.make_branch_and_tree('tree')
255
    test.tree = tree
256
    test.branch_config = config.BranchConfig(tree.branch)
257
    test.locations_config = config.LocationConfig(tree.basedir)
258
    test.bazaar_config = config.GlobalConfig()
259
5533.2.4 by Vincent Ladeuil
Fix whitespace issue.
260
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
261
def create_configs_with_file_option(test):
262
    """Create configuration files with a ``file`` option set in each.
263
264
    This builds on ``create_configs`` and add one ``file`` option in each
265
    configuration with a value which allows identifying the configuration file.
266
    """
267
    create_configs(test)
268
    test.bazaar_config.set_user_option('file', 'bazaar')
269
    test.locations_config.set_user_option('file', 'locations')
270
    test.branch_config.set_user_option('file', 'branch')
271
272
273
class TestOptionsMixin:
274
275
    def assertOptions(self, expected, conf):
276
        # We don't care about the parser (as it will make tests hard to write
277
        # and error-prone anyway)
278
        self.assertThat([opt[:4] for opt in conf._get_options()],
279
                        matchers.Equals(expected))
280
281
1474 by Robert Collins
Merge from Aaron Bentley.
282
class InstrumentedConfigObj(object):
283
    """A config obj look-enough-alike to record calls made to it."""
284
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
285
    def __contains__(self, thing):
286
        self._calls.append(('__contains__', thing))
287
        return False
288
289
    def __getitem__(self, key):
290
        self._calls.append(('__getitem__', key))
291
        return self
292
1551.2.20 by Aaron Bentley
Treated config files as utf-8
293
    def __init__(self, input, encoding=None):
294
        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.
295
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
296
    def __setitem__(self, key, value):
297
        self._calls.append(('__setitem__', key, value))
298
2120.6.4 by James Henstridge
add support for specifying policy when storing options
299
    def __delitem__(self, key):
300
        self._calls.append(('__delitem__', key))
301
302
    def keys(self):
303
        self._calls.append(('keys',))
304
        return []
305
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
306
    def reload(self):
307
        self._calls.append(('reload',))
308
1551.2.49 by abentley
Made ConfigObj output binary-identical files on win32 and *nix
309
    def write(self, arg):
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
310
        self._calls.append(('write',))
311
2120.6.4 by James Henstridge
add support for specifying policy when storing options
312
    def as_bool(self, value):
313
        self._calls.append(('as_bool', value))
314
        return False
315
316
    def get_value(self, section, name):
317
        self._calls.append(('get_value', section, name))
318
        return None
319
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
320
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
321
class FakeBranch(object):
322
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
323
    def __init__(self, base=None, user_id=None):
324
        if base is None:
325
            self.base = "http://example.com/branches/demo"
326
        else:
327
            self.base = base
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
328
        self._transport = self.control_files = \
329
            FakeControlFilesAndTransport(user_id=user_id)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
330
4226.1.7 by Robert Collins
Alter test_config.FakeBranch in accordance with the Branch change to have a _get_config.
331
    def _get_config(self):
332
        return config.TransportConfig(self._transport, 'branch.conf')
333
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
334
    def lock_write(self):
335
        pass
336
337
    def unlock(self):
338
        pass
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
339
340
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
341
class FakeControlFilesAndTransport(object):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
342
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
343
    def __init__(self, user_id=None):
344
        self.files = {}
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
345
        if user_id:
346
            self.files['email'] = user_id
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
347
        self._transport = self
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
348
1185.65.29 by Robert Collins
Implement final review suggestions.
349
    def get_utf8(self, filename):
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
350
        # from LockableFiles
351
        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
352
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
353
    def get(self, filename):
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
354
        # from Transport
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
355
        try:
356
            return StringIO(self.files[filename])
357
        except KeyError:
358
            raise errors.NoSuchFile(filename)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
359
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
360
    def get_bytes(self, filename):
361
        # from Transport
362
        try:
363
            return self.files[filename]
364
        except KeyError:
365
            raise errors.NoSuchFile(filename)
366
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
367
    def put(self, filename, fileobj):
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
368
        self.files[filename] = fileobj.read()
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
369
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
370
    def put_file(self, filename, fileobj):
371
        return self.put(filename, fileobj)
372
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
373
374
class InstrumentedConfig(config.Config):
375
    """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.
376
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
377
    def __init__(self):
378
        super(InstrumentedConfig, self).__init__()
379
        self._calls = []
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
380
        self._signatures = config.CHECK_NEVER
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
381
382
    def _get_user_id(self):
383
        self._calls.append('_get_user_id')
384
        return "Robert Collins <robert.collins@example.org>"
385
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
386
    def _get_signature_checking(self):
387
        self._calls.append('_get_signature_checking')
388
        return self._signatures
389
4603.1.10 by Aaron Bentley
Provide change editor via config.
390
    def _get_change_editor(self):
391
        self._calls.append('_get_change_editor')
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
392
        return 'vimdiff -fo @new_path @old_path'
4603.1.10 by Aaron Bentley
Provide change editor via config.
393
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
394
1556.2.2 by Aaron Bentley
Fixed get_bool
395
bool_config = """[DEFAULT]
396
active = true
397
inactive = false
398
[UPPERCASE]
399
active = True
400
nonactive = False
401
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
402
403
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
404
class TestConfigObj(tests.TestCase):
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
405
1556.2.2 by Aaron Bentley
Fixed get_bool
406
    def test_get_bool(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
407
        co = config.ConfigObj(StringIO(bool_config))
1556.2.2 by Aaron Bentley
Fixed get_bool
408
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
409
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
410
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
411
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
412
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
413
    def test_hash_sign_in_value(self):
414
        """
415
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
416
        treated as comments when read in again. (#86838)
417
        """
418
        co = config.ConfigObj()
419
        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.
420
        outfile = StringIO()
421
        co.write(outfile=outfile)
422
        lines = outfile.getvalue().splitlines()
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
423
        self.assertEqual(lines, ['test = "foo#bar"'])
424
        co2 = config.ConfigObj(lines)
425
        self.assertEqual(co2['test'], 'foo#bar')
426
5050.62.10 by Alexander Belchenko
test to illustrate the problem
427
    def test_triple_quotes(self):
428
        # Bug #710410: if the value string has triple quotes
429
        # then ConfigObj versions up to 4.7.2 will quote them wrong
5050.62.12 by Alexander Belchenko
added NEWS entry
430
        # and won't able to read them back
5050.62.10 by Alexander Belchenko
test to illustrate the problem
431
        triple_quotes_value = '''spam
432
""" that's my spam """
433
eggs'''
434
        co = config.ConfigObj()
435
        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.
436
        # While writing this test another bug in ConfigObj has been found:
5050.62.10 by Alexander Belchenko
test to illustrate the problem
437
        # method co.write() without arguments produces list of lines
438
        # one option per line, and multiline values are not split
439
        # 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.
440
        # and that breaks the parsing these lines back by ConfigObj.
441
        # This issue only affects test, but it's better to avoid
442
        # `co.write()` construct at all.
443
        # [bialix 20110222] bug report sent to ConfigObj's author
5050.62.10 by Alexander Belchenko
test to illustrate the problem
444
        outfile = StringIO()
445
        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.
446
        output = outfile.getvalue()
5050.62.10 by Alexander Belchenko
test to illustrate the problem
447
        # 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.
448
        co2 = config.ConfigObj(StringIO(output))
5050.62.10 by Alexander Belchenko
test to illustrate the problem
449
        self.assertEquals(triple_quotes_value, co2['test'])
450
1556.2.2 by Aaron Bentley
Fixed get_bool
451
2900.1.1 by Vincent Ladeuil
452
erroneous_config = """[section] # line 1
453
good=good # line 2
454
[section] # line 3
455
whocares=notme # line 4
456
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
457
458
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
459
class TestConfigObjErrors(tests.TestCase):
2900.1.1 by Vincent Ladeuil
460
461
    def test_duplicate_section_name_error_line(self):
462
        try:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
463
            co = configobj.ConfigObj(StringIO(erroneous_config),
464
                                     raise_errors=True)
2900.1.1 by Vincent Ladeuil
465
        except config.configobj.DuplicateError, e:
466
            self.assertEqual(3, e.line_number)
467
        else:
468
            self.fail('Error in config file not detected')
469
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
470
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
471
class TestConfig(tests.TestCase):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
472
473
    def test_constructs(self):
474
        config.Config()
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
475
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
476
    def test_no_default_editor(self):
477
        self.assertRaises(NotImplementedError, config.Config().get_editor)
478
479
    def test_user_email(self):
480
        my_config = InstrumentedConfig()
481
        self.assertEqual('robert.collins@example.org', my_config.user_email())
482
        self.assertEqual(['_get_user_id'], my_config._calls)
483
484
    def test_username(self):
485
        my_config = InstrumentedConfig()
486
        self.assertEqual('Robert Collins <robert.collins@example.org>',
487
                         my_config.username())
488
        self.assertEqual(['_get_user_id'], my_config._calls)
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
489
490
    def test_signatures_default(self):
491
        my_config = config.Config()
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
492
        self.assertFalse(my_config.signature_needed())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
493
        self.assertEqual(config.CHECK_IF_POSSIBLE,
494
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
495
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
496
                         my_config.signing_policy())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
497
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
498
    def test_signatures_template_method(self):
499
        my_config = InstrumentedConfig()
500
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
501
        self.assertEqual(['_get_signature_checking'], my_config._calls)
502
503
    def test_signatures_template_method_none(self):
504
        my_config = InstrumentedConfig()
505
        my_config._signatures = None
506
        self.assertEqual(config.CHECK_IF_POSSIBLE,
507
                         my_config.signature_checking())
508
        self.assertEqual(['_get_signature_checking'], my_config._calls)
509
1442.1.56 by Robert Collins
gpg_signing_command configuration item
510
    def test_gpg_signing_command_default(self):
511
        my_config = config.Config()
512
        self.assertEqual('gpg', my_config.gpg_signing_command())
513
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
514
    def test_get_user_option_default(self):
515
        my_config = config.Config()
516
        self.assertEqual(None, my_config.get_user_option('no_option'))
517
1472 by Robert Collins
post commit hook, first pass implementation
518
    def test_post_commit_default(self):
519
        my_config = config.Config()
520
        self.assertEqual(None, my_config.post_commit())
521
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
522
    def test_log_format_default(self):
1553.2.8 by Erik BÃ¥gfors
tests for config log_formatter
523
        my_config = config.Config()
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
524
        self.assertEqual('long', my_config.log_format())
1553.2.8 by Erik BÃ¥gfors
tests for config log_formatter
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)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1191
        self.assertEqual("vim", my_config.get_editor())
1192
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
1193
    def test_signatures_always(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1194
        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
1195
        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
1196
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1197
        self.assertEqual(config.SIGN_ALWAYS,
1198
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1199
        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
1200
1201
    def test_signatures_if_possible(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1202
        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
1203
        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
1204
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1205
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
1206
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1207
        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
1208
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1209
    def test_signatures_ignore(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1210
        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
1211
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1212
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1213
        self.assertEqual(config.SIGN_NEVER,
1214
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1215
        self.assertEqual(False, my_config.signature_needed())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1216
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1217
    def _get_sample_config(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1218
        my_config = config.GlobalConfig.from_string(sample_config_text)
1534.7.154 by Aaron Bentley
Removed changes from bzr.ab 1529..1536
1219
        return my_config
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1220
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1221
    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.
1222
        my_config = self._get_sample_config()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1223
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
1224
        self.assertEqual(False, my_config.signature_needed())
1225
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1226
    def _get_empty_config(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1227
        my_config = config.GlobalConfig()
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1228
        return my_config
1229
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
1230
    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.
1231
        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.
1232
        self.assertEqual("gpg", my_config.gpg_signing_command())
1233
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1234
    def test_get_user_option_default(self):
1235
        my_config = self._get_empty_config()
1236
        self.assertEqual(None, my_config.get_user_option('no_option'))
1237
1238
    def test_get_user_option_global(self):
1239
        my_config = self._get_sample_config()
1240
        self.assertEqual("something",
1241
                         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.
1242
1472 by Robert Collins
post commit hook, first pass implementation
1243
    def test_post_commit_default(self):
1244
        my_config = self._get_sample_config()
1245
        self.assertEqual(None, my_config.post_commit())
1246
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
1247
    def test_configured_logformat(self):
1553.2.8 by Erik BÃ¥gfors
tests for config log_formatter
1248
        my_config = self._get_sample_config()
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
1249
        self.assertEqual("short", my_config.log_format())
1553.2.8 by Erik BÃ¥gfors
tests for config log_formatter
1250
1553.6.12 by Erik BÃ¥gfors
remove AliasConfig, based on input from abentley
1251
    def test_get_alias(self):
1252
        my_config = self._get_sample_config()
1253
        self.assertEqual('help', my_config.get_alias('h'))
1254
2900.3.6 by Tim Penhey
Added tests.
1255
    def test_get_aliases(self):
1256
        my_config = self._get_sample_config()
1257
        aliases = my_config.get_aliases()
1258
        self.assertEqual(2, len(aliases))
1259
        sorted_keys = sorted(aliases)
1260
        self.assertEqual('help', aliases[sorted_keys[0]])
1261
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
1262
1553.6.12 by Erik BÃ¥gfors
remove AliasConfig, based on input from abentley
1263
    def test_get_no_alias(self):
1264
        my_config = self._get_sample_config()
1265
        self.assertEqual(None, my_config.get_alias('foo'))
1266
1267
    def test_get_long_alias(self):
1268
        my_config = self._get_sample_config()
1269
        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.
1270
4603.1.10 by Aaron Bentley
Provide change editor via config.
1271
    def test_get_change_editor(self):
1272
        my_config = self._get_sample_config()
1273
        change_editor = my_config.get_change_editor('old', 'new')
1274
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
1275
        self.assertEqual('vimdiff -of @new_path @old_path',
4603.1.10 by Aaron Bentley
Provide change editor via config.
1276
                         ' '.join(change_editor.command_template))
1277
1278
    def test_get_no_change_editor(self):
1279
        my_config = self._get_empty_config()
1280
        change_editor = my_config.get_change_editor('old', 'new')
1281
        self.assertIs(None, change_editor)
1282
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
1283
    def test_get_merge_tools(self):
1284
        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.
1285
        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.
1286
        self.log(repr(tools))
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1287
        self.assertEqual(
1288
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
1289
            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.
1290
            tools)
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
1291
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1292
    def test_get_merge_tools_empty(self):
5321.1.93 by Gordon Tyler
Added tests for get_default_merge_tool.
1293
        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.
1294
        tools = conf.get_merge_tools()
1295
        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.
1296
1297
    def test_find_merge_tool(self):
1298
        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.
1299
        cmdline = conf.find_merge_tool('sometool')
1300
        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.
1301
1302
    def test_find_merge_tool_not_found(self):
1303
        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.
1304
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
1305
        self.assertIs(cmdline, None)
5321.1.93 by Gordon Tyler
Added tests for get_default_merge_tool.
1306
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.
1307
    def test_find_merge_tool_known(self):
1308
        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.
1309
        cmdline = conf.find_merge_tool('kdiff3')
1310
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
1311
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.
1312
    def test_find_merge_tool_override_known(self):
1313
        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.
1314
        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.
1315
        cmdline = conf.find_merge_tool('kdiff3')
1316
        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.
1317
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1318
2900.3.6 by Tim Penhey
Added tests.
1319
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
1320
1321
    def test_empty(self):
1322
        my_config = config.GlobalConfig()
1323
        self.assertEqual(0, len(my_config.get_aliases()))
1324
1325
    def test_set_alias(self):
1326
        my_config = config.GlobalConfig()
1327
        alias_value = 'commit --strict'
1328
        my_config.set_alias('commit', alias_value)
1329
        new_config = config.GlobalConfig()
1330
        self.assertEqual(alias_value, new_config.get_alias('commit'))
1331
1332
    def test_remove_alias(self):
1333
        my_config = config.GlobalConfig()
1334
        my_config.set_alias('commit', 'commit --strict')
1335
        # Now remove the alias again.
1336
        my_config.unset_alias('commit')
1337
        new_config = config.GlobalConfig()
1338
        self.assertIs(None, new_config.get_alias('commit'))
1339
1340
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1341
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1342
1343
    def test_constructs(self):
1344
        my_config = config.LocationConfig('http://example.com')
1345
        self.assertRaises(TypeError, config.LocationConfig)
1346
1347
    def test_branch_calls_read_filenames(self):
1474 by Robert Collins
Merge from Aaron Bentley.
1348
        # This is testing the correct file names are provided.
1349
        # TODO: consolidate with the test for GlobalConfigs filename checks.
1350
        #
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1351
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
1352
        oldparserclass = config.ConfigObj
1353
        config.ConfigObj = InstrumentedConfigObj
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1354
        try:
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1355
            my_config = config.LocationConfig('http://www.example.com')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1356
            parser = my_config._get_parser()
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1357
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
1358
            config.ConfigObj = oldparserclass
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1359
        self.assertIsInstance(parser, InstrumentedConfigObj)
1474 by Robert Collins
Merge from Aaron Bentley.
1360
        self.assertEqual(parser._calls,
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1361
                         [('__init__', config.locations_config_filename(),
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1362
                           'utf-8')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1363
1364
    def test_get_global_config(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1365
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1366
        global_config = my_config._get_global_config()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1367
        self.assertIsInstance(global_config, config.GlobalConfig)
1368
        self.assertIs(global_config, my_config._get_global_config())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1369
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1370
    def assertLocationMatching(self, expected):
1371
        self.assertEqual(expected,
1372
                         list(self.my_location_config._get_matching_sections()))
1373
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1374
    def test__get_matching_sections_no_match(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1375
        self.get_branch_config('/')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1376
        self.assertLocationMatching([])
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1377
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1378
    def test__get_matching_sections_exact(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1379
        self.get_branch_config('http://www.example.com')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1380
        self.assertLocationMatching([('http://www.example.com', '')])
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1381
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1382
    def test__get_matching_sections_suffix_does_not(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1383
        self.get_branch_config('http://www.example.com-com')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1384
        self.assertLocationMatching([])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1385
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1386
    def test__get_matching_sections_subdir_recursive(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1387
        self.get_branch_config('http://www.example.com/com')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1388
        self.assertLocationMatching([('http://www.example.com', 'com')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1389
1993.3.5 by James Henstridge
add back recurse=False option to config file
1390
    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
1391
        self.get_branch_config('http://www.example.com/ignoreparent')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1392
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1393
                                      '')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1394
1993.3.5 by James Henstridge
add back recurse=False option to config file
1395
    def test__get_matching_sections_ignoreparent_subdir(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1396
        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
1397
            'http://www.example.com/ignoreparent/childbranch')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1398
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1399
                                      'childbranch')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1400
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1401
    def test__get_matching_sections_subdir_trailing_slash(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1402
        self.get_branch_config('/b')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1403
        self.assertLocationMatching([('/b/', '')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1404
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1405
    def test__get_matching_sections_subdir_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1406
        self.get_branch_config('/a/foo')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1407
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1408
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1409
    def test__get_matching_sections_subdir_child_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1410
        self.get_branch_config('/a/foo/bar')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1411
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1412
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1413
    def test__get_matching_sections_trailing_slash_with_children(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1414
        self.get_branch_config('/a/')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1415
        self.assertLocationMatching([('/a/', '')])
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1416
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1417
    def test__get_matching_sections_explicit_over_glob(self):
1418
        # XXX: 2006-09-08 jamesh
1419
        # This test only passes because ord('c') > ord('*').  If there
1420
        # was a config section for '/a/?', it would get precedence
1421
        # over '/a/c'.
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1422
        self.get_branch_config('/a/c')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1423
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1424
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
1425
    def test__get_option_policy_normal(self):
1426
        self.get_branch_config('http://www.example.com')
1427
        self.assertEqual(
1428
            self.my_location_config._get_config_policy(
1429
            'http://www.example.com', 'normal_option'),
1430
            config.POLICY_NONE)
1431
1432
    def test__get_option_policy_norecurse(self):
1433
        self.get_branch_config('http://www.example.com')
1434
        self.assertEqual(
1435
            self.my_location_config._get_option_policy(
1436
            'http://www.example.com', 'norecurse_option'),
1437
            config.POLICY_NORECURSE)
1438
        # Test old recurse=False setting:
1439
        self.assertEqual(
1440
            self.my_location_config._get_option_policy(
1441
            'http://www.example.com/norecurse', 'normal_option'),
1442
            config.POLICY_NORECURSE)
1443
1444
    def test__get_option_policy_normal(self):
1445
        self.get_branch_config('http://www.example.com')
1446
        self.assertEqual(
1447
            self.my_location_config._get_option_policy(
1448
            'http://www.example.com', 'appendpath_option'),
1449
            config.POLICY_APPENDPATH)
1450
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1451
    def test__get_options_with_policy(self):
1452
        self.get_branch_config('/dir/subdir',
1453
                               location_config="""\
1454
[/dir]
1455
other_url = /other-dir
1456
other_url:policy = appendpath
1457
[/dir/subdir]
1458
other_url = /other-subdir
1459
""")
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1460
        self.assertOptions(
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1461
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
1462
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
1463
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1464
            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.
1465
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1466
    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
1467
        self.get_branch_config('http://www.example.com/ignoreparent')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1468
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1469
                         self.my_config.username())
1470
1471
    def test_location_not_listed(self):
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1472
        """Test that the global username is used when no location matches"""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1473
        self.get_branch_config('/home/robertc/sources')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1474
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1475
                         self.my_config.username())
1476
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
1477
    def test_overriding_location(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1478
        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
1479
        self.assertEqual('Robert Collins <robertc@example.org>',
1480
                         self.my_config.username())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1481
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1482
    def test_signatures_not_set(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1483
        self.get_branch_config('http://www.example.com',
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1484
                                 global_config=sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1485
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1486
                         self.my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1487
        self.assertEqual(config.SIGN_NEVER,
1488
                         self.my_config.signing_policy())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1489
1490
    def test_signatures_never(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1491
        self.get_branch_config('/a/c')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1492
        self.assertEqual(config.CHECK_NEVER,
1493
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1494
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1495
    def test_signatures_when_available(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1496
        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
1497
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1498
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1499
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1500
    def test_signatures_always(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1501
        self.get_branch_config('/b')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1502
        self.assertEqual(config.CHECK_ALWAYS,
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.56 by Robert Collins
gpg_signing_command configuration item
1505
    def test_gpg_signing_command(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1506
        self.get_branch_config('/b')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1507
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
1508
1509
    def test_gpg_signing_command_missing(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1510
        self.get_branch_config('/a')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1511
        self.assertEqual("false", self.my_config.gpg_signing_command())
1512
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1513
    def test_get_user_option_global(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1514
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1515
        self.assertEqual('something',
1516
                         self.my_config.get_user_option('user_global_option'))
1517
1518
    def test_get_user_option_local(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1519
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1520
        self.assertEqual('local',
1521
                         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
1522
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
1523
    def test_get_user_option_appendpath(self):
1524
        # returned as is for the base path:
1525
        self.get_branch_config('http://www.example.com')
1526
        self.assertEqual('append',
1527
                         self.my_config.get_user_option('appendpath_option'))
1528
        # Extra path components get appended:
1529
        self.get_branch_config('http://www.example.com/a/b/c')
1530
        self.assertEqual('append/a/b/c',
1531
                         self.my_config.get_user_option('appendpath_option'))
1532
        # Overriden for http://www.example.com/dir, where it is a
1533
        # normal option:
1534
        self.get_branch_config('http://www.example.com/dir/a/b/c')
1535
        self.assertEqual('normal',
1536
                         self.my_config.get_user_option('appendpath_option'))
1537
1538
    def test_get_user_option_norecurse(self):
1539
        self.get_branch_config('http://www.example.com')
1540
        self.assertEqual('norecurse',
1541
                         self.my_config.get_user_option('norecurse_option'))
1542
        self.get_branch_config('http://www.example.com/dir')
1543
        self.assertEqual(None,
1544
                         self.my_config.get_user_option('norecurse_option'))
1545
        # http://www.example.com/norecurse is a recurse=False section
1546
        # that redefines normal_option.  Subdirectories do not pick up
1547
        # this redefinition.
1548
        self.get_branch_config('http://www.example.com/norecurse')
1549
        self.assertEqual('norecurse',
1550
                         self.my_config.get_user_option('normal_option'))
1551
        self.get_branch_config('http://www.example.com/norecurse/subdir')
1552
        self.assertEqual('normal',
1553
                         self.my_config.get_user_option('normal_option'))
1554
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1555
    def test_set_user_option_norecurse(self):
1556
        self.get_branch_config('http://www.example.com')
1557
        self.my_config.set_user_option('foo', 'bar',
1558
                                       store=config.STORE_LOCATION_NORECURSE)
1559
        self.assertEqual(
1560
            self.my_location_config._get_option_policy(
1561
            'http://www.example.com', 'foo'),
1562
            config.POLICY_NORECURSE)
1563
1564
    def test_set_user_option_appendpath(self):
1565
        self.get_branch_config('http://www.example.com')
1566
        self.my_config.set_user_option('foo', 'bar',
1567
                                       store=config.STORE_LOCATION_APPENDPATH)
1568
        self.assertEqual(
1569
            self.my_location_config._get_option_policy(
1570
            'http://www.example.com', 'foo'),
1571
            config.POLICY_APPENDPATH)
1572
1573
    def test_set_user_option_change_policy(self):
1574
        self.get_branch_config('http://www.example.com')
1575
        self.my_config.set_user_option('norecurse_option', 'normal',
1576
                                       store=config.STORE_LOCATION)
1577
        self.assertEqual(
1578
            self.my_location_config._get_option_policy(
1579
            'http://www.example.com', 'norecurse_option'),
1580
            config.POLICY_NONE)
1581
1582
    def test_set_user_option_recurse_false_section(self):
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1583
        # The following section has recurse=False set.  The test is to
1584
        # make sure that a normal option can be added to the section,
1585
        # converting recurse=False to the norecurse policy.
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1586
        self.get_branch_config('http://www.example.com/norecurse')
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
1587
        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
1588
                             'The section "http://www.example.com/norecurse" '
1589
                             'has been converted to use policies.'],
1590
                            self.my_config.set_user_option,
1591
                            'foo', 'bar', store=config.STORE_LOCATION)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1592
        self.assertEqual(
1593
            self.my_location_config._get_option_policy(
1594
            'http://www.example.com/norecurse', 'foo'),
1595
            config.POLICY_NONE)
1596
        # The previously existing option is still norecurse:
1597
        self.assertEqual(
1598
            self.my_location_config._get_option_policy(
1599
            'http://www.example.com/norecurse', 'normal_option'),
1600
            config.POLICY_NORECURSE)
1601
1472 by Robert Collins
post commit hook, first pass implementation
1602
    def test_post_commit_default(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1603
        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
1604
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1605
                         self.my_config.post_commit())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1606
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1607
    def get_branch_config(self, location, global_config=None,
1608
                          location_config=None):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1609
        my_branch = FakeBranch(location)
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
1610
        if global_config is None:
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1611
            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.
1612
        if location_config is None:
1613
            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.
1614
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1615
        my_global_config = config.GlobalConfig.from_string(global_config,
1616
                                                           save=True)
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1617
        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.
1618
            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.
1619
        my_config = config.BranchConfig(my_branch)
1620
        self.my_config = my_config
1621
        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.
1622
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1623
    def test_set_user_setting_sets_and_saves(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1624
        self.get_branch_config('/a/c')
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1625
        record = InstrumentedConfigObj("foo")
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1626
        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
1627
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1628
        self.callDeprecated(['The recurse option is deprecated as of '
1629
                             '0.14.  The section "/a/c" has been '
1630
                             'converted to use policies.'],
1631
                            self.my_config.set_user_option,
1632
                            'foo', 'bar', store=config.STORE_LOCATION)
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
1633
        self.assertEqual([('reload',),
1634
                          ('__contains__', '/a/c'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1635
                          ('__contains__', '/a/c/'),
1636
                          ('__setitem__', '/a/c', {}),
1637
                          ('__getitem__', '/a/c'),
1638
                          ('__setitem__', 'foo', 'bar'),
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1639
                          ('__getitem__', '/a/c'),
1640
                          ('as_bool', 'recurse'),
1641
                          ('__getitem__', '/a/c'),
1642
                          ('__delitem__', 'recurse'),
1643
                          ('__getitem__', '/a/c'),
1644
                          ('keys',),
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1645
                          ('__getitem__', '/a/c'),
1646
                          ('__contains__', 'foo:policy'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1647
                          ('write',)],
1648
                         record._calls[1:])
1649
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1650
    def test_set_user_setting_sets_and_saves2(self):
1651
        self.get_branch_config('/a/c')
1652
        self.assertIs(self.my_config.get_user_option('foo'), None)
1653
        self.my_config.set_user_option('foo', 'bar')
1654
        self.assertEqual(
3616.2.6 by Mark Hammond
Fix test_set_user_setting_sets_and_saves2 on windows by stripping EOL
1655
            self.my_config.branch.control_files.files['branch.conf'].strip(),
1656
            'foo = bar')
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1657
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1658
        self.my_config.set_user_option('foo', 'baz',
1659
                                       store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1660
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1661
        self.my_config.set_user_option('foo', 'qux')
1662
        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.
1663
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1664
    def test_get_bzr_remote_path(self):
1665
        my_config = config.LocationConfig('/a/c')
1666
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1667
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1668
        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.
1669
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1670
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1671
1185.62.7 by John Arbash Meinel
Whitespace cleanup.
1672
1770.2.8 by Aaron Bentley
Add precedence test
1673
precedence_global = 'option = global'
1674
precedence_branch = 'option = branch'
1675
precedence_location = """
1676
[http://]
1677
recurse = true
1678
option = recurse
1679
[http://example.com/specific]
1680
option = exact
1681
"""
1682
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1683
class TestBranchConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1684
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1685
    def get_branch_config(self, global_config=None, location=None,
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1686
                          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.
1687
        my_branch = FakeBranch(location)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1688
        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
1689
            my_global_config = config.GlobalConfig.from_string(global_config,
1690
                                                               save=True)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1691
        if location_config is not None:
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1692
            my_location_config = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1693
                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.
1694
        my_config = config.BranchConfig(my_branch)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1695
        if branch_data_config is not None:
1696
            my_config.branch.control_files.files['branch.conf'] = \
1697
                branch_data_config
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1698
        return my_config
1699
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1700
    def test_user_id(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1701
        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
1702
        my_config = config.BranchConfig(branch)
1703
        self.assertEqual("Robert Collins <robertc@example.net>",
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1704
                         my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1705
        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.
1706
        my_config.set_user_option('email',
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1707
                                  "Robert Collins <robertc@example.org>")
1708
        self.assertEqual("John", my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1709
        del my_config.branch.control_files.files['email']
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1710
        self.assertEqual("Robert Collins <robertc@example.org>",
1711
                         my_config.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1712
1713
    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.
1714
        my_config = self.get_branch_config(global_config=sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1715
        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
1716
                         my_config._get_user_id())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1717
        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
1718
        self.assertEqual("John", my_config._get_user_id())
1719
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
1720
    def test_BZR_EMAIL_OVERRIDES(self):
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
1721
        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
1722
        branch = FakeBranch()
1723
        my_config = config.BranchConfig(branch)
1724
        self.assertEqual("Robert Collins <robertc@example.org>",
1725
                         my_config.username())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1726
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1727
    def test_signatures_forced(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1728
        my_config = self.get_branch_config(
1729
            global_config=sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1730
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1731
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1732
        self.assertTrue(my_config.signature_needed())
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1733
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1734
    def test_signatures_forced_branch(self):
1735
        my_config = self.get_branch_config(
1736
            global_config=sample_ignore_signatures,
1737
            branch_data_config=sample_always_signatures)
1738
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1739
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1740
        self.assertTrue(my_config.signature_needed())
1741
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1742
    def test_gpg_signing_command(self):
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1743
        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.
1744
            global_config=sample_config_text,
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1745
            # branch data cannot set gpg_signing_command
1746
            branch_data_config="gpg_signing_command=pgp")
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1747
        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.
1748
1749
    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.
1750
        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.
1751
        self.assertEqual('something',
1752
                         my_config.get_user_option('user_global_option'))
1472 by Robert Collins
post commit hook, first pass implementation
1753
1754
    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.
1755
        my_config = self.get_branch_config(global_config=sample_config_text,
1756
                                      location='/a/c',
1757
                                      location_config=sample_branches_text)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1758
        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
1759
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1760
                         my_config.post_commit())
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1761
        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.
1762
        # post-commit is ignored when present in branch data
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1763
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1764
                         my_config.post_commit())
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1765
        my_config.set_user_option('post_commit', 'rmtree_root',
1766
                                  store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1767
        self.assertEqual('rmtree_root', my_config.post_commit())
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1768
1770.2.8 by Aaron Bentley
Add precedence test
1769
    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.
1770
        # FIXME: eager test, luckily no persitent config file makes it fail
1771
        # -- vila 20100716
1770.2.8 by Aaron Bentley
Add precedence test
1772
        my_config = self.get_branch_config(global_config=precedence_global)
1773
        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.
1774
        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.
1775
                                           branch_data_config=precedence_branch)
1770.2.8 by Aaron Bentley
Add precedence test
1776
        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.
1777
        my_config = self.get_branch_config(
1778
            global_config=precedence_global,
1779
            branch_data_config=precedence_branch,
1780
            location_config=precedence_location)
1770.2.8 by Aaron Bentley
Add precedence test
1781
        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.
1782
        my_config = self.get_branch_config(
1783
            global_config=precedence_global,
1784
            branch_data_config=precedence_branch,
1785
            location_config=precedence_location,
1786
            location='http://example.com/specific')
1770.2.8 by Aaron Bentley
Add precedence test
1787
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1788
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
1789
    def test_get_mail_client(self):
1790
        config = self.get_branch_config()
1791
        client = config.get_mail_client()
2681.1.24 by Aaron Bentley
Handle default mail client by trying xdg-email, falling back to editor
1792
        self.assertIsInstance(client, mail_client.DefaultMail)
1793
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1794
        # Specific clients
2681.1.21 by Aaron Bentley
Refactor prompt generation to make it testable, test it with unicode
1795
        config.set_user_option('mail_client', 'evolution')
1796
        client = config.get_mail_client()
1797
        self.assertIsInstance(client, mail_client.Evolution)
1798
2681.5.1 by ghigo
Add KMail support to bzr send
1799
        config.set_user_option('mail_client', 'kmail')
1800
        client = config.get_mail_client()
1801
        self.assertIsInstance(client, mail_client.KMail)
1802
2790.2.1 by Keir Mierle
Add Mutt as a supported client email program. Also rearranges various listings
1803
        config.set_user_option('mail_client', 'mutt')
1804
        client = config.get_mail_client()
1805
        self.assertIsInstance(client, mail_client.Mutt)
1806
1807
        config.set_user_option('mail_client', 'thunderbird')
1808
        client = config.get_mail_client()
1809
        self.assertIsInstance(client, mail_client.Thunderbird)
1810
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1811
        # Generic options
1812
        config.set_user_option('mail_client', 'default')
1813
        client = config.get_mail_client()
1814
        self.assertIsInstance(client, mail_client.DefaultMail)
1815
1816
        config.set_user_option('mail_client', 'editor')
1817
        client = config.get_mail_client()
1818
        self.assertIsInstance(client, mail_client.Editor)
1819
1820
        config.set_user_option('mail_client', 'mapi')
1821
        client = config.get_mail_client()
1822
        self.assertIsInstance(client, mail_client.MAPIClient)
1823
2681.1.23 by Aaron Bentley
Add support for xdg-email
1824
        config.set_user_option('mail_client', 'xdg-email')
1825
        client = config.get_mail_client()
1826
        self.assertIsInstance(client, mail_client.XDGEmail)
1827
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
1828
        config.set_user_option('mail_client', 'firebird')
1829
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1830
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1831
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1832
class TestMailAddressExtraction(tests.TestCase):
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1833
1834
    def test_extract_email_address(self):
1835
        self.assertEqual('jane@test.com',
1836
                         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
1837
        self.assertRaises(errors.NoEmailInUsername,
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1838
                          config.extract_email_address, 'Jane Tester')
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1839
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1840
    def test_parse_username(self):
1841
        self.assertEqual(('', 'jdoe@example.com'),
1842
                         config.parse_username('jdoe@example.com'))
1843
        self.assertEqual(('', 'jdoe@example.com'),
1844
                         config.parse_username('<jdoe@example.com>'))
1845
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1846
                         config.parse_username('John Doe <jdoe@example.com>'))
1847
        self.assertEqual(('John Doe', ''),
1848
                         config.parse_username('John Doe'))
3063.3.3 by Lukáš Lalinský
Add one more test for config.parse_username().
1849
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1850
                         config.parse_username('John Doe jdoe@example.com'))
2562.1.2 by John Arbash Meinel
Clean up whitespace
1851
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1852
class TestTreeConfig(tests.TestCaseWithTransport):
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1853
1854
    def test_get_value(self):
1855
        """Test that retreiving a value from a section is possible"""
1856
        branch = self.make_branch('.')
1857
        tree_config = config.TreeConfig(branch)
1858
        tree_config.set_option('value', 'key', 'SECTION')
1859
        tree_config.set_option('value2', 'key2')
1860
        tree_config.set_option('value3-top', 'key3')
1861
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1862
        value = tree_config.get_option('key', 'SECTION')
1863
        self.assertEqual(value, 'value')
1864
        value = tree_config.get_option('key2')
1865
        self.assertEqual(value, 'value2')
1866
        self.assertEqual(tree_config.get_option('non-existant'), None)
1867
        value = tree_config.get_option('non-existant', 'SECTION')
1868
        self.assertEqual(value, None)
1869
        value = tree_config.get_option('non-existant', default='default')
1870
        self.assertEqual(value, 'default')
1871
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1872
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1873
        self.assertEqual(value, 'default')
1874
        value = tree_config.get_option('key3')
1875
        self.assertEqual(value, 'value3-top')
1876
        value = tree_config.get_option('key3', 'SECTION')
1877
        self.assertEqual(value, 'value3-section')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1878
1879
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1880
class TestTransportConfig(tests.TestCaseWithTransport):
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1881
1882
    def test_get_value(self):
1883
        """Test that retreiving a value from a section is possible"""
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1884
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1885
                                               'control.conf')
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1886
        bzrdir_config.set_option('value', 'key', 'SECTION')
1887
        bzrdir_config.set_option('value2', 'key2')
1888
        bzrdir_config.set_option('value3-top', 'key3')
1889
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1890
        value = bzrdir_config.get_option('key', 'SECTION')
1891
        self.assertEqual(value, 'value')
1892
        value = bzrdir_config.get_option('key2')
1893
        self.assertEqual(value, 'value2')
1894
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1895
        value = bzrdir_config.get_option('non-existant', 'SECTION')
1896
        self.assertEqual(value, None)
1897
        value = bzrdir_config.get_option('non-existant', default='default')
1898
        self.assertEqual(value, 'default')
1899
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1900
        value = bzrdir_config.get_option('key2', 'NOSECTION',
1901
                                         default='default')
1902
        self.assertEqual(value, 'default')
1903
        value = bzrdir_config.get_option('key3')
1904
        self.assertEqual(value, 'value3-top')
1905
        value = bzrdir_config.get_option('key3', 'SECTION')
1906
        self.assertEqual(value, 'value3-section')
1907
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1908
    def test_set_unset_default_stack_on(self):
1909
        my_dir = self.make_bzrdir('.')
4288.1.3 by Robert Collins
Fix BzrDirConfig tests.
1910
        bzrdir_config = config.BzrDirConfig(my_dir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1911
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1912
        bzrdir_config.set_default_stack_on('Foo')
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1913
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1914
                         'default_stack_on'))
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1915
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1916
        bzrdir_config.set_default_stack_on(None)
1917
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1918
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1919
5743.3.12 by Vincent Ladeuil
Add an ad-hoc __repr__.
1920
class TestSection(tests.TestCase):
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
1921
1922
    # FIXME: Parametrize so that all sections produced by Stores run these
5743.3.1 by Vincent Ladeuil
Add a docstring and dates to FIXMEs.
1923
    # tests -- vila 2011-04-01
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
1924
1925
    def test_get_a_value(self):
1926
        a_dict = dict(foo='bar')
5743.3.11 by Vincent Ladeuil
Config sections only implement read access.
1927
        section = config.Section('myID', a_dict)
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
1928
        self.assertEquals('bar', section.get('foo'))
1929
5743.3.10 by Vincent Ladeuil
Fix typos mentioned in reviews.
1930
    def test_get_unknown_option(self):
5743.2.2 by Vincent Ladeuil
Add tests for remove.
1931
        a_dict = dict()
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
1932
        section = config.Section(None, a_dict)
5743.2.2 by Vincent Ladeuil
Add tests for remove.
1933
        self.assertEquals('out of thin air',
1934
                          section.get('foo', 'out of thin air'))
1935
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
1936
    def test_options_is_shared(self):
1937
        a_dict = dict()
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
1938
        section = config.Section(None, a_dict)
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
1939
        self.assertIs(a_dict, section.options)
1940
1941
5743.3.12 by Vincent Ladeuil
Add an ad-hoc __repr__.
1942
class TestMutableSection(tests.TestCase):
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
1943
5743.4.20 by Vincent Ladeuil
Fix typo.
1944
    # FIXME: Parametrize so that all sections (including os.environ and the
5743.3.1 by Vincent Ladeuil
Add a docstring and dates to FIXMEs.
1945
    # 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.
1946
1947
    def test_set(self):
1948
        a_dict = dict(foo='bar')
1949
        section = config.MutableSection('myID', a_dict)
1950
        section.set('foo', 'new_value')
1951
        self.assertEquals('new_value', section.get('foo'))
1952
        # The change appears in the shared section
1953
        self.assertEquals('new_value', a_dict.get('foo'))
1954
        # We keep track of the change
1955
        self.assertTrue('foo' in section.orig)
1956
        self.assertEquals('bar', section.orig.get('foo'))
1957
1958
    def test_set_preserve_original_once(self):
1959
        a_dict = dict(foo='bar')
1960
        section = config.MutableSection('myID', a_dict)
1961
        section.set('foo', 'first_value')
1962
        section.set('foo', 'second_value')
1963
        # We keep track of the original value
1964
        self.assertTrue('foo' in section.orig)
1965
        self.assertEquals('bar', section.orig.get('foo'))
1966
5743.2.2 by Vincent Ladeuil
Add tests for remove.
1967
    def test_remove(self):
1968
        a_dict = dict(foo='bar')
1969
        section = config.MutableSection('myID', a_dict)
1970
        section.remove('foo')
1971
        # We get None for unknown options via the default value
1972
        self.assertEquals(None, section.get('foo'))
1973
        # Or we just get the default value
1974
        self.assertEquals('unknown', section.get('foo', 'unknown'))
1975
        self.assertFalse('foo' in section.options)
1976
        # We keep track of the deletion
1977
        self.assertTrue('foo' in section.orig)
1978
        self.assertEquals('bar', section.orig.get('foo'))
1979
1980
    def test_remove_new_option(self):
1981
        a_dict = dict()
1982
        section = config.MutableSection('myID', a_dict)
1983
        section.set('foo', 'bar')
1984
        section.remove('foo')
1985
        self.assertFalse('foo' in section.options)
1986
        # The option didn't exist initially so it we need to keep track of it
1987
        # with a special value
1988
        self.assertTrue('foo' in section.orig)
5743.3.6 by Vincent Ladeuil
Use a name less likely to be reused.
1989
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
5743.2.2 by Vincent Ladeuil
Add tests for remove.
1990
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
1991
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
1992
class TestStore(tests.TestCaseWithTransport):
1993
1994
    def assertSectionContent(self, expected, section):
1995
        """Assert that some options have the proper values in a section."""
1996
        expected_name, expected_options = expected
1997
        self.assertEquals(expected_name, section.id)
1998
        self.assertEquals(
1999
            expected_options,
2000
            dict([(k, section.get(k)) for k in expected_options.keys()]))
2001
2002
2003
class TestReadonlyStore(TestStore):
2004
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2005
    scenarios = [(key, {'get_store': builder}) for key, builder
2006
                 in config.test_store_builder_registry.iteritems()]
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2007
2008
    def setUp(self):
2009
        super(TestReadonlyStore, self).setUp()
2010
2011
    def test_building_delays_load(self):
2012
        store = self.get_store(self)
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2013
        self.assertEquals(False, store.is_loaded())
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2014
        store._load_from_string('')
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2015
        self.assertEquals(True, store.is_loaded())
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2016
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2017
    def test_get_no_sections_for_empty(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2018
        store = self.get_store(self)
2019
        store._load_from_string('')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2020
        self.assertEquals([], list(store.get_sections()))
2021
2022
    def test_get_default_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2023
        store = self.get_store(self)
2024
        store._load_from_string('foo=bar')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2025
        sections = list(store.get_sections())
2026
        self.assertLength(1, sections)
2027
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2028
2029
    def test_get_named_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2030
        store = self.get_store(self)
2031
        store._load_from_string('[baz]\nfoo=bar')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2032
        sections = list(store.get_sections())
2033
        self.assertLength(1, sections)
2034
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2035
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2036
    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.
2037
        store = self.get_store(self)
2038
        store._load_from_string('foo=bar')
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2039
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2040
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2041
2042
class TestMutableStore(TestStore):
2043
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2044
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2045
                 in config.test_store_builder_registry.iteritems()]
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2046
2047
    def setUp(self):
2048
        super(TestMutableStore, self).setUp()
2049
        self.transport = self.get_transport()
2050
2051
    def has_store(self, store):
2052
        store_basename = urlutils.relative_url(self.transport.external_url(),
2053
                                               store.external_url())
2054
        return self.transport.has(store_basename)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2055
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2056
    def test_save_empty_creates_no_file(self):
5743.10.4 by Vincent Ladeuil
Add FIXME.
2057
        # FIXME: There should be a better way than relying on the test
2058
        # 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.
2059
        if self.store_id in ('branch', 'remote_branch'):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2060
            raise tests.TestNotApplicable(
2061
                'branch.conf is *always* created when a branch is initialized')
2062
        store = self.get_store(self)
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2063
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2064
        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.
2065
2066
    def test_save_emptied_succeeds(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2067
        store = self.get_store(self)
2068
        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.
2069
        section = store.get_mutable_section(None)
2070
        section.remove('foo')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2071
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2072
        self.assertEquals(True, self.has_store(store))
2073
        modified_store = self.get_store(self)
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2074
        sections = list(modified_store.get_sections())
2075
        self.assertLength(0, sections)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2076
2077
    def test_save_with_content_succeeds(self):
5743.10.4 by Vincent Ladeuil
Add FIXME.
2078
        # FIXME: There should be a better way than relying on the test
2079
        # 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.
2080
        if self.store_id in ('branch', 'remote_branch'):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2081
            raise tests.TestNotApplicable(
2082
                'branch.conf is *always* created when a branch is initialized')
2083
        store = self.get_store(self)
2084
        store._load_from_string('foo=bar\n')
2085
        self.assertEquals(False, self.has_store(store))
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2086
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2087
        self.assertEquals(True, self.has_store(store))
2088
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2089
        sections = list(modified_store.get_sections())
2090
        self.assertLength(1, sections)
2091
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2092
2093
    def test_set_option_in_empty_store(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2094
        store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2095
        section = store.get_mutable_section(None)
2096
        section.set('foo', 'bar')
2097
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2098
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2099
        sections = list(modified_store.get_sections())
2100
        self.assertLength(1, sections)
2101
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2102
2103
    def test_set_option_in_default_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2104
        store = self.get_store(self)
2105
        store._load_from_string('')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2106
        section = store.get_mutable_section(None)
2107
        section.set('foo', 'bar')
2108
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2109
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2110
        sections = list(modified_store.get_sections())
2111
        self.assertLength(1, sections)
2112
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2113
2114
    def test_set_option_in_named_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2115
        store = self.get_store(self)
2116
        store._load_from_string('')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2117
        section = store.get_mutable_section('baz')
2118
        section.set('foo', 'bar')
2119
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2120
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2121
        sections = list(modified_store.get_sections())
2122
        self.assertLength(1, sections)
2123
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2124
2125
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2126
class TestIniFileStore(TestStore):
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2127
5743.4.3 by Vincent Ladeuil
Implement get_mutable_section.
2128
    def test_loading_unknown_file_fails(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2129
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
5743.4.3 by Vincent Ladeuil
Implement get_mutable_section.
2130
        self.assertRaises(errors.NoSuchFile, store.load)
2131
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2132
    def test_invalid_content(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2133
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2134
        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.
2135
        exc = self.assertRaises(
2136
            errors.ParseConfigError, store._load_from_string,
2137
            'this is invalid !')
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2138
        self.assertEndsWith(exc.filename, 'foo.conf')
2139
        # And the load failed
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2140
        self.assertEquals(False, store.is_loaded())
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2141
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2142
    def test_get_embedded_sections(self):
5743.2.11 by Vincent Ladeuil
Basic store.set implementation.
2143
        # A more complicated example (which also shows that section names and
2144
        # 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.
2145
        # FIXME: This should be fixed by forbidding dicts as values ?
2146
        # -- vila 2011-04-05
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2147
        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.
2148
        store._load_from_string('''
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2149
foo=bar
2150
l=1,2
2151
[DEFAULT]
2152
foo_in_DEFAULT=foo_DEFAULT
2153
[bar]
2154
foo_in_bar=barbar
2155
[baz]
2156
foo_in_baz=barbaz
2157
[[qux]]
2158
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.
2159
''')
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2160
        sections = list(store.get_sections())
2161
        self.assertLength(4, sections)
2162
        # The default section has no name.
2163
        # List values are provided as lists
5743.4.1 by Vincent Ladeuil
Use proper ReadOnly sections in ConfigObjStore.get_sections().
2164
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
2165
                                  sections[0])
2166
        self.assertSectionContent(
2167
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2168
        self.assertSectionContent(
2169
            ('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.
2170
        # sub sections are provided as embedded dicts.
5743.4.1 by Vincent Ladeuil
Use proper ReadOnly sections in ConfigObjStore.get_sections().
2171
        self.assertSectionContent(
2172
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2173
            sections[3])
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2174
5743.4.5 by Vincent Ladeuil
Split store tests between readonly and mutable ones.
2175
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2176
class TestLockableIniFileStore(TestStore):
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2177
2178
    def test_create_store_in_created_dir(self):
5743.6.21 by Vincent Ladeuil
Tighten the test.
2179
        self.assertPathDoesNotExist('dir')
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2180
        t = self.get_transport('dir/subdir')
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2181
        store = config.LockableIniFileStore(t, 'foo.conf')
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2182
        store.get_mutable_section(None).set('foo', 'bar')
2183
        store.save()
5743.6.21 by Vincent Ladeuil
Tighten the test.
2184
        self.assertPathExists('dir/subdir')
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2185
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2186
5743.10.5 by Vincent Ladeuil
Give up.
2187
class TestBranchStore(TestStore):
2188
2189
    def test_dead_branch(self):
2190
        build_backing_branch(self, 'branch')
2191
        b = branch.Branch.open('branch')
2192
        store = config.BranchStore(b)
2193
        del b
2194
        # The only reliable way to trigger the error is to explicitly call the
2195
        # garbage collector.
2196
        import gc
2197
        gc.collect()
2198
        store.get_mutable_section(None).set('foo', 'bar')
2199
        self.assertRaises(AssertionError, store.save)
2200
2201
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2202
class TestConcurrentStoreUpdates(TestStore):
5743.10.13 by Vincent Ladeuil
Mention that the the concurrent update tests are not targeted at *all* Store implementations.
2203
    """Test that Stores properly handle conccurent updates.
2204
2205
    New Store implementation may fail some of these tests but until such
2206
    implementations exist it's hard to properly filter them from the scenarios
2207
    applied here. If you encounter such a case, contact the bzr devs.
2208
    """
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2209
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2210
    scenarios = [(key, {'get_stack': builder}) for key, builder
2211
                 in config.test_stack_builder_registry.iteritems()]
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2212
2213
    def setUp(self):
2214
        super(TestConcurrentStoreUpdates, self).setUp()
2215
        self._content = 'one=1\ntwo=2\n'
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2216
        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
2217
        if not isinstance(self.stack, config._CompatibleStack):
2218
            raise tests.TestNotApplicable(
2219
                '%s is not meant to be compatible with the old config design'
2220
                % (self.stack,))
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2221
        self.stack.store._load_from_string(self._content)
2222
        # Flush the store
2223
        self.stack.store.save()
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2224
2225
    def test_simple_read_access(self):
2226
        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
2227
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2228
    def test_simple_write_access(self):
2229
        self.stack.set('one', 'one')
2230
        self.assertEquals('one', self.stack.get('one'))
2231
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2232
    def test_listen_to_the_last_speaker(self):
2233
        c1 = self.stack
2234
        c2 = self.get_stack(self)
2235
        c1.set('one', 'ONE')
2236
        c2.set('two', 'TWO')
2237
        self.assertEquals('ONE', c1.get('one'))
2238
        self.assertEquals('TWO', c2.get('two'))
2239
        # The second update respect the first one
2240
        self.assertEquals('ONE', c2.get('one'))
2241
2242
    def test_last_speaker_wins(self):
2243
        # If the same config is not shared, the same variable modified twice
2244
        # can only see a single result.
2245
        c1 = self.stack
2246
        c2 = self.get_stack(self)
2247
        c1.set('one', 'c1')
2248
        c2.set('one', 'c2')
2249
        self.assertEquals('c2', c2.get('one'))
2250
        # The first modification is still available until another refresh
2251
        # occur
2252
        self.assertEquals('c1', c1.get('one'))
2253
        c1.set('two', 'done')
2254
        self.assertEquals('c2', c1.get('one'))
2255
5743.6.24 by Vincent Ladeuil
One more test with a ugly hack to allow the test to stop in the right place.
2256
    def test_writes_are_serialized(self):
2257
        c1 = self.stack
2258
        c2 = self.get_stack(self)
2259
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2260
        # 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.
2261
        before_writing = threading.Event()
2262
        after_writing = threading.Event()
2263
        writing_done = threading.Event()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2264
        c1_save_without_locking_orig = c1.store.save_without_locking
2265
        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.
2266
            before_writing.set()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2267
            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.
2268
            # The lock is held. We wait for the main thread to decide when to
2269
            # continue
2270
            after_writing.wait()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2271
        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.
2272
        def c1_set():
2273
            c1.set('one', 'c1')
2274
            writing_done.set()
2275
        t1 = threading.Thread(target=c1_set)
2276
        # Collect the thread after the test
2277
        self.addCleanup(t1.join)
2278
        # Be ready to unblock the thread if the test goes wrong
2279
        self.addCleanup(after_writing.set)
2280
        t1.start()
2281
        before_writing.wait()
2282
        self.assertRaises(errors.LockContention,
2283
                          c2.set, 'one', 'c2')
2284
        self.assertEquals('c1', c1.get('one'))
2285
        # Let the lock be released
2286
        after_writing.set()
2287
        writing_done.wait()
2288
        c2.set('one', 'c2')
2289
        self.assertEquals('c2', c2.get('one'))
2290
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2291
    def test_read_while_writing(self):
2292
       c1 = self.stack
2293
       # We spawn a thread that will pause *during* the write
2294
       ready_to_write = threading.Event()
2295
       do_writing = threading.Event()
2296
       writing_done = threading.Event()
2297
       # We override the _save implementation so we know the store is locked
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2298
       c1_save_without_locking_orig = c1.store.save_without_locking
2299
       def c1_save_without_locking():
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2300
           ready_to_write.set()
2301
           # The lock is held. We wait for the main thread to decide when to
2302
           # continue
2303
           do_writing.wait()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2304
           c1_save_without_locking_orig()
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2305
           writing_done.set()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2306
       c1.store.save_without_locking = c1_save_without_locking
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2307
       def c1_set():
2308
           c1.set('one', 'c1')
2309
       t1 = threading.Thread(target=c1_set)
2310
       # Collect the thread after the test
2311
       self.addCleanup(t1.join)
2312
       # Be ready to unblock the thread if the test goes wrong
2313
       self.addCleanup(do_writing.set)
2314
       t1.start()
2315
       # Ensure the thread is ready to write
2316
       ready_to_write.wait()
2317
       self.assertEquals('c1', c1.get('one'))
2318
       # If we read during the write, we get the old value
2319
       c2 = self.get_stack(self)
2320
       self.assertEquals('1', c2.get('one'))
2321
       # Let the writing occur and ensure it occurred
2322
       do_writing.set()
2323
       writing_done.wait()
2324
       # Now we get the updated value
2325
       c3 = self.get_stack(self)
2326
       self.assertEquals('c1', c3.get('one'))
2327
2328
    # FIXME: It may be worth looking into removing the lock dir when it's not
2329
    # needed anymore and look at possible fallouts for concurrent lockers. This
2330
    # will matter if/when we use config files outside of bazaar directories
2331
    # (.bazaar or .bzr) -- vila 20110-04-11
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2332
2333
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2334
class TestSectionMatcher(TestStore):
2335
2336
    scenarios = [('location', {'matcher': config.LocationMatcher})]
2337
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2338
    def get_store(self, file_name):
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2339
        return config.IniFileStore(self.get_readonly_transport(), file_name)
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2340
2341
    def test_no_matches_for_empty_stores(self):
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2342
        store = self.get_store('foo.conf')
2343
        store._load_from_string('')
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2344
        matcher = self.matcher(store, '/bar')
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2345
        self.assertEquals([], list(matcher.get_sections()))
2346
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2347
    def test_build_doesnt_load_store(self):
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2348
        store = self.get_store('foo.conf')
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2349
        matcher = self.matcher(store, '/bar')
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2350
        self.assertFalse(store.is_loaded())
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2351
2352
2353
class TestLocationSection(tests.TestCase):
2354
2355
    def get_section(self, options, extra_path):
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2356
        section = config.Section('foo', options)
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2357
        # We don't care about the length so we use '0'
2358
        return config.LocationSection(section, 0, extra_path)
2359
2360
    def test_simple_option(self):
2361
        section = self.get_section({'foo': 'bar'}, '')
2362
        self.assertEquals('bar', section.get('foo'))
2363
2364
    def test_option_with_extra_path(self):
2365
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
2366
                                   'baz')
2367
        self.assertEquals('bar/baz', section.get('foo'))
2368
2369
    def test_invalid_policy(self):
2370
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
2371
                                   'baz')
2372
        # invalid policies are ignored
2373
        self.assertEquals('bar', section.get('foo'))
2374
2375
2376
class TestLocationMatcher(TestStore):
2377
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2378
    def get_store(self, file_name):
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2379
        return config.IniFileStore(self.get_readonly_transport(), file_name)
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2380
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2381
    def test_more_specific_sections_first(self):
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2382
        store = self.get_store('foo.conf')
2383
        store._load_from_string('''
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2384
[/foo]
2385
section=/foo
2386
[/foo/bar]
2387
section=/foo/bar
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2388
''')
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2389
        self.assertEquals(['/foo', '/foo/bar'],
2390
                          [section.id for section in store.get_sections()])
2391
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
2392
        sections = list(matcher.get_sections())
2393
        self.assertEquals([3, 2],
2394
                          [section.length for section in sections])
2395
        self.assertEquals(['/foo/bar', '/foo'],
2396
                          [section.id for section in sections])
2397
        self.assertEquals(['baz', 'bar/baz'],
2398
                          [section.extra_path for section in sections])
2399
5743.6.18 by Vincent Ladeuil
Add a test for appendpath support in no-name section.
2400
    def test_appendpath_in_no_name_section(self):
2401
        # It's a bit weird to allow appendpath in a no-name section, but
2402
        # someone may found a use for it
2403
        store = self.get_store('foo.conf')
2404
        store._load_from_string('''
2405
foo=bar
2406
foo:policy = appendpath
2407
''')
2408
        matcher = config.LocationMatcher(store, 'dir/subdir')
2409
        sections = list(matcher.get_sections())
2410
        self.assertLength(1, sections)
2411
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
2412
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
2413
    def test_file_urls_are_normalized(self):
2414
        store = self.get_store('foo.conf')
5912.3.1 by Vincent Ladeuil
Fix spurious windows-specific test failure
2415
        if sys.platform == 'win32':
2416
            expected_url = 'file:///C:/dir/subdir'
2417
            expected_location = 'C:/dir/subdir'
2418
        else:
2419
            expected_url = 'file:///dir/subdir'
2420
            expected_location = '/dir/subdir'
2421
        matcher = config.LocationMatcher(store, expected_url)
2422
        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).
2423
5743.1.20 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2424
5743.1.35 by Vincent Ladeuil
Address some review comments from jelmer and poolie.
2425
class TestStackGet(tests.TestCase):
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2426
5743.1.35 by Vincent Ladeuil
Address some review comments from jelmer and poolie.
2427
    # 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.
2428
    # paramerized tests created to avoid bloating -- vila 2011-03-31
2429
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2430
    def test_single_config_get(self):
2431
        conf = dict(foo='bar')
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2432
        conf_stack = config.Stack([conf])
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2433
        self.assertEquals('bar', conf_stack.get('foo'))
2434
2435
    def test_get_first_definition(self):
2436
        conf1 = dict(foo='bar')
2437
        conf2 = dict(foo='baz')
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2438
        conf_stack = config.Stack([conf1, conf2])
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2439
        self.assertEquals('bar', conf_stack.get('foo'))
2440
5743.1.2 by Vincent Ladeuil
Stacks can be used as read-only sections.
2441
    def test_get_embedded_definition(self):
2442
        conf1 = dict(yy='12')
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2443
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
2444
        conf_stack = config.Stack([conf1, conf2])
5743.1.2 by Vincent Ladeuil
Stacks can be used as read-only sections.
2445
        self.assertEquals('baz', conf_stack.get('foo'))
2446
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
2447
    def test_get_for_empty_stack(self):
5743.1.36 by Vincent Ladeuil
Clarify that constructor parameters are here to *define* the stack and as such can be re-used. Also make the sections_def parameter mandatory.
2448
        conf_stack = config.Stack([])
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
2449
        self.assertEquals(None, conf_stack.get('foo'))
2450
2451
    def test_get_for_empty_section_callable(self):
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2452
        conf_stack = config.Stack([lambda : []])
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
2453
        self.assertEquals(None, conf_stack.get('foo'))
2454
5743.1.35 by Vincent Ladeuil
Address some review comments from jelmer and poolie.
2455
    def test_get_for_broken_callable(self):
2456
        # Trying to use and invalid callable raises an exception on first use
2457
        conf_stack = config.Stack([lambda : object()])
2458
        self.assertRaises(TypeError, conf_stack.get, 'foo')
2459
2460
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2461
class TestStackWithTransport(tests.TestCaseWithTransport):
2462
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2463
    scenarios = [(key, {'get_stack': builder}) for key, builder
2464
                 in config.test_stack_builder_registry.iteritems()]
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2465
2466
2467
class TestStackSet(TestStackWithTransport):
2468
5743.1.7 by Vincent Ladeuil
Simple set implementation.
2469
    def test_simple_set(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2470
        conf = self.get_stack(self)
2471
        conf.store._load_from_string('foo=bar')
5743.1.7 by Vincent Ladeuil
Simple set implementation.
2472
        self.assertEquals('bar', conf.get('foo'))
2473
        conf.set('foo', 'baz')
2474
        # Did we get it back ?
2475
        self.assertEquals('baz', conf.get('foo'))
2476
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.
2477
    def test_set_creates_a_new_section(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2478
        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.
2479
        conf.set('foo', 'baz')
5743.1.9 by Vincent Ladeuil
Fix the issue by allowing delayed section acquisition.
2480
        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.
2481
5743.1.7 by Vincent Ladeuil
Simple set implementation.
2482
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2483
class TestStackRemove(TestStackWithTransport):
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
2484
2485
    def test_remove_existing(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2486
        conf = self.get_stack(self)
2487
        conf.store._load_from_string('foo=bar')
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
2488
        self.assertEquals('bar', conf.get('foo'))
2489
        conf.remove('foo')
2490
        # Did we get it back ?
2491
        self.assertEquals(None, conf.get('foo'))
2492
2493
    def test_remove_unknown(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2494
        conf = self.get_stack(self)
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
2495
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
2496
2497
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2498
class TestConcreteStacks(TestStackWithTransport):
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
2499
5743.6.11 by Vincent Ladeuil
Start parameterizing stack tests.
2500
    def test_build_stack(self):
2501
        stack = self.get_stack(self)
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
2502
2503
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2504
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2505
2506
    def setUp(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2507
        super(TestConfigGetOptions, self).setUp()
2508
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2509
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2510
    def test_no_variable(self):
2511
        # 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.
2512
        self.assertOptions([], self.branch_config)
2513
2514
    def test_option_in_bazaar(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2515
        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.
2516
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2517
                           self.bazaar_config)
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
2518
2519
    def test_option_in_locations(self):
2520
        self.locations_config.set_user_option('file', 'locations')
2521
        self.assertOptions(
2522
            [('file', 'locations', self.tree.basedir, 'locations')],
2523
            self.locations_config)
2524
2525
    def test_option_in_branch(self):
2526
        self.branch_config.set_user_option('file', 'branch')
2527
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
2528
                           self.branch_config)
2529
2530
    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.
2531
        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.
2532
        self.branch_config.set_user_option('file', 'branch')
2533
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
2534
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
2535
                           self.branch_config)
2536
2537
    def test_option_in_branch_and_locations(self):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2538
        # Hmm, locations override branch :-/
2539
        self.locations_config.set_user_option('file', 'locations')
2540
        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.
2541
        self.assertOptions(
2542
            [('file', 'locations', self.tree.basedir, 'locations'),
2543
             ('file', 'branch', 'DEFAULT', 'branch'),],
2544
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2545
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
2546
    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.
2547
        self.bazaar_config.set_user_option('file', 'bazaar')
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2548
        self.locations_config.set_user_option('file', 'locations')
2549
        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.
2550
        self.assertOptions(
2551
            [('file', 'locations', self.tree.basedir, 'locations'),
2552
             ('file', 'branch', 'DEFAULT', 'branch'),
2553
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
2554
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2555
2556
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2557
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2558
2559
    def setUp(self):
2560
        super(TestConfigRemoveOption, self).setUp()
2561
        create_configs_with_file_option(self)
2562
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
2563
    def test_remove_in_locations(self):
2564
        self.locations_config.remove_user_option('file', self.tree.basedir)
2565
        self.assertOptions(
2566
            [('file', 'branch', 'DEFAULT', 'branch'),
2567
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
2568
            self.branch_config)
2569
2570
    def test_remove_in_branch(self):
2571
        self.branch_config.remove_user_option('file')
2572
        self.assertOptions(
2573
            [('file', 'locations', self.tree.basedir, 'locations'),
2574
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
2575
            self.branch_config)
2576
2577
    def test_remove_in_bazaar(self):
2578
        self.bazaar_config.remove_user_option('file')
2579
        self.assertOptions(
2580
            [('file', 'locations', self.tree.basedir, 'locations'),
2581
             ('file', 'branch', 'DEFAULT', 'branch'),],
2582
            self.branch_config)
2583
5447.4.7 by Vincent Ladeuil
Check error message if the test is checking for errors or we have unexpected success for wrong errors.
2584
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2585
class TestConfigGetSections(tests.TestCaseWithTransport):
2586
2587
    def setUp(self):
2588
        super(TestConfigGetSections, self).setUp()
2589
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2590
2591
    def assertSectionNames(self, expected, conf, name=None):
2592
        """Check which sections are returned for a given config.
2593
2594
        If fallback configurations exist their sections can be included.
2595
2596
        :param expected: A list of section names.
2597
2598
        :param conf: The configuration that will be queried.
2599
2600
        :param name: An optional section name that will be passed to
2601
            get_sections().
2602
        """
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.
2603
        sections = list(conf._get_sections(name))
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2604
        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.
2605
        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.
2606
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2607
    def test_bazaar_default_section(self):
2608
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2609
2610
    def test_locations_default_section(self):
2611
        # No sections are defined in an empty file
2612
        self.assertSectionNames([], self.locations_config)
2613
2614
    def test_locations_named_section(self):
2615
        self.locations_config.set_user_option('file', 'locations')
2616
        self.assertSectionNames([self.tree.basedir], self.locations_config)
2617
2618
    def test_locations_matching_sections(self):
2619
        loc_config = self.locations_config
2620
        loc_config.set_user_option('file', 'locations')
2621
        # We need to cheat a bit here to create an option in sections above and
2622
        # below the 'location' one.
2623
        parser = loc_config._get_parser()
2624
        # locations.cong deals with '/' ignoring native os.sep
2625
        location_names = self.tree.basedir.split('/')
2626
        parent = '/'.join(location_names[:-1])
2627
        child = '/'.join(location_names + ['child'])
2628
        parser[parent] = {}
2629
        parser[parent]['file'] = 'parent'
2630
        parser[child] = {}
2631
        parser[child]['file'] = 'child'
2632
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
2633
2634
    def test_branch_data_default_section(self):
2635
        self.assertSectionNames([None],
2636
                                self.branch_config._get_branch_data_config())
2637
2638
    def test_branch_default_sections(self):
2639
        # No sections are defined in an empty locations file
2640
        self.assertSectionNames([None, 'DEFAULT'],
2641
                                self.branch_config)
2642
        # Unless we define an option
2643
        self.branch_config._get_location_config().set_user_option(
2644
            'file', 'locations')
2645
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
2646
                                self.branch_config)
2647
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2648
    def test_bazaar_named_section(self):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2649
        # We need to cheat as the API doesn't give direct access to sections
2650
        # other than DEFAULT.
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2651
        self.bazaar_config.set_alias('bazaar', 'bzr')
2652
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2653
2654
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
2655
class TestAuthenticationConfigFile(tests.TestCase):
2900.2.14 by Vincent Ladeuil
More tests.
2656
    """Test the authentication.conf file matching"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2657
2658
    def _got_user_passwd(self, expected_user, expected_password,
2659
                         config, *args, **kwargs):
2660
        credentials = config.get_credentials(*args, **kwargs)
2661
        if credentials is None:
2662
            user = None
2663
            password = None
2664
        else:
2665
            user = credentials['user']
2666
            password = credentials['password']
2667
        self.assertEquals(expected_user, user)
2668
        self.assertEquals(expected_password, password)
2669
2978.5.1 by John Arbash Meinel
Fix bug #162494, 'bzr register-branch' needs proper auth handling.
2670
    def test_empty_config(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2671
        conf = config.AuthenticationConfig(_file=StringIO())
2672
        self.assertEquals({}, conf._get_config())
2673
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
2674
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
2675
    def test_missing_auth_section_header(self):
2676
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
2677
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2678
2679
    def test_auth_section_header_not_closed(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2680
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
2681
        self.assertRaises(errors.ParseConfigError, conf._get_config)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
2682
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
2683
    def test_auth_value_not_boolean(self):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
2684
        conf = config.AuthenticationConfig(_file=StringIO(
2685
                """[broken]
2686
scheme=ftp
2687
user=joe
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
2688
verify_certificates=askme # Error: Not a boolean
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
2689
"""))
2690
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
2691
2692
    def test_auth_value_not_int(self):
2900.2.22 by Vincent Ladeuil
Polishing.
2693
        conf = config.AuthenticationConfig(_file=StringIO(
2694
                """[broken]
2695
scheme=ftp
2696
user=joe
2697
port=port # Error: Not an int
2698
"""))
2699
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2700
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2701
    def test_unknown_password_encoding(self):
2702
        conf = config.AuthenticationConfig(_file=StringIO(
2703
                """[broken]
2704
scheme=ftp
2705
user=joe
2706
password_encoding=unknown
2707
"""))
2708
        self.assertRaises(ValueError, conf.get_password,
2709
                          'ftp', 'foo.net', 'joe')
2710
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2711
    def test_credentials_for_scheme_host(self):
2712
        conf = config.AuthenticationConfig(_file=StringIO(
2713
                """# Identity on foo.net
2714
[ftp definition]
2715
scheme=ftp
2716
host=foo.net
2717
user=joe
2718
password=secret-pass
2719
"""))
2720
        # Basic matching
2721
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
2722
        # different scheme
2723
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
2724
        # different host
2725
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
2726
2727
    def test_credentials_for_host_port(self):
2728
        conf = config.AuthenticationConfig(_file=StringIO(
2729
                """# Identity on foo.net
2730
[ftp definition]
2731
scheme=ftp
2732
port=10021
2733
host=foo.net
2734
user=joe
2735
password=secret-pass
2736
"""))
2737
        # No port
2738
        self._got_user_passwd('joe', 'secret-pass',
2739
                              conf, 'ftp', 'foo.net', port=10021)
2740
        # different port
2741
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
2742
2743
    def test_for_matching_host(self):
2744
        conf = config.AuthenticationConfig(_file=StringIO(
2745
                """# Identity on foo.net
2746
[sourceforge]
2747
scheme=bzr
2748
host=bzr.sf.net
2749
user=joe
2750
password=joepass
2751
[sourceforge domain]
2752
scheme=bzr
2753
host=.bzr.sf.net
2754
user=georges
2755
password=bendover
2756
"""))
2757
        # matching domain
2758
        self._got_user_passwd('georges', 'bendover',
2759
                              conf, 'bzr', 'foo.bzr.sf.net')
2760
        # phishing attempt
2761
        self._got_user_passwd(None, None,
2762
                              conf, 'bzr', 'bbzr.sf.net')
2763
2764
    def test_for_matching_host_None(self):
2765
        conf = config.AuthenticationConfig(_file=StringIO(
2766
                """# Identity on foo.net
2767
[catchup bzr]
2768
scheme=bzr
2769
user=joe
2770
password=joepass
2771
[DEFAULT]
2772
user=georges
2773
password=bendover
2774
"""))
2775
        # match no host
2776
        self._got_user_passwd('joe', 'joepass',
2777
                              conf, 'bzr', 'quux.net')
2778
        # no host but different scheme
2779
        self._got_user_passwd('georges', 'bendover',
2780
                              conf, 'ftp', 'quux.net')
2781
2782
    def test_credentials_for_path(self):
2783
        conf = config.AuthenticationConfig(_file=StringIO(
2784
                """
2785
[http dir1]
2786
scheme=http
2787
host=bar.org
2788
path=/dir1
2789
user=jim
2790
password=jimpass
2791
[http dir2]
2792
scheme=http
2793
host=bar.org
2794
path=/dir2
2795
user=georges
2796
password=bendover
2797
"""))
2798
        # no path no dice
2799
        self._got_user_passwd(None, None,
2800
                              conf, 'http', host='bar.org', path='/dir3')
2801
        # matching path
2802
        self._got_user_passwd('georges', 'bendover',
2803
                              conf, 'http', host='bar.org', path='/dir2')
2804
        # matching subdir
2805
        self._got_user_passwd('jim', 'jimpass',
2806
                              conf, 'http', host='bar.org',path='/dir1/subdir')
2807
2808
    def test_credentials_for_user(self):
2809
        conf = config.AuthenticationConfig(_file=StringIO(
2810
                """
2811
[with user]
2812
scheme=http
2813
host=bar.org
2814
user=jim
2815
password=jimpass
2816
"""))
2817
        # Get user
2818
        self._got_user_passwd('jim', 'jimpass',
2819
                              conf, 'http', 'bar.org')
2820
        # Get same user
2821
        self._got_user_passwd('jim', 'jimpass',
2822
                              conf, 'http', 'bar.org', user='jim')
2823
        # Don't get a different user if one is specified
2824
        self._got_user_passwd(None, None,
2825
                              conf, 'http', 'bar.org', user='georges')
2826
3418.4.1 by Vincent Ladeuil
Reproduce bug 199440.
2827
    def test_credentials_for_user_without_password(self):
2828
        conf = config.AuthenticationConfig(_file=StringIO(
2829
                """
2830
[without password]
2831
scheme=http
2832
host=bar.org
2833
user=jim
2834
"""))
2835
        # Get user but no password
2836
        self._got_user_passwd('jim', None,
2837
                              conf, 'http', 'bar.org')
2838
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2839
    def test_verify_certificates(self):
2840
        conf = config.AuthenticationConfig(_file=StringIO(
2841
                """
2842
[self-signed]
2843
scheme=https
2844
host=bar.org
2845
user=jim
2846
password=jimpass
2847
verify_certificates=False
2848
[normal]
2849
scheme=https
2850
host=foo.net
2851
user=georges
2852
password=bendover
2853
"""))
2854
        credentials = conf.get_credentials('https', 'bar.org')
2855
        self.assertEquals(False, credentials.get('verify_certificates'))
2856
        credentials = conf.get_credentials('https', 'foo.net')
2857
        self.assertEquals(True, credentials.get('verify_certificates'))
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
2858
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2859
2860
class TestAuthenticationStorage(tests.TestCaseInTempDir):
2861
3777.1.8 by Aaron Bentley
Commit work-in-progress
2862
    def test_set_credentials(self):
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2863
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
2864
        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
2865
        99, path='/foo', verify_certificates=False, realm='realm')
3777.1.8 by Aaron Bentley
Commit work-in-progress
2866
        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
2867
                                           port=99, path='/foo',
2868
                                           realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2869
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
2870
                       'verify_certificates': False, 'scheme': 'scheme', 
2871
                       'host': 'host', 'port': 99, 'path': '/foo', 
2872
                       'realm': 'realm'}
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2873
        self.assertEqual(CREDENTIALS, credentials)
2874
        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
2875
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2876
        self.assertEqual(CREDENTIALS, credentials_from_disk)
3777.1.8 by Aaron Bentley
Commit work-in-progress
2877
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2878
    def test_reset_credentials_different_name(self):
2879
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
2880
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
2881
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2882
        self.assertIs(None, conf._get_config().get('name'))
2883
        credentials = conf.get_credentials(host='host', scheme='scheme')
2884
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
2885
                       'password', 'verify_certificates': True, 
2886
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
2887
                       'path': None, 'realm': None}
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2888
        self.assertEqual(CREDENTIALS, credentials)
2889
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
2890
2900.2.14 by Vincent Ladeuil
More tests.
2891
class TestAuthenticationConfig(tests.TestCase):
2892
    """Test AuthenticationConfig behaviour"""
2893
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2894
    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.
2895
                                       host=None, port=None, realm=None,
2896
                                       path=None):
2900.2.14 by Vincent Ladeuil
More tests.
2897
        if host is None:
2898
            host = 'bar.org'
2899
        user, password = 'jim', 'precious'
2900
        expected_prompt = expected_prompt_format % {
2901
            'scheme': scheme, 'host': host, 'port': port,
2902
            'user': user, 'realm': realm}
2903
2904
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2905
        stderr = tests.StringIOWrapper()
2900.2.14 by Vincent Ladeuil
More tests.
2906
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2907
                                            stdout=stdout, stderr=stderr)
2900.2.14 by Vincent Ladeuil
More tests.
2908
        # We use an empty conf so that the user is always prompted
2909
        conf = config.AuthenticationConfig()
2910
        self.assertEquals(password,
2911
                          conf.get_password(scheme, host, user, port=port,
2912
                                            realm=realm, path=path))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2913
        self.assertEquals(expected_prompt, stderr.getvalue())
2914
        self.assertEquals('', stdout.getvalue())
2900.2.14 by Vincent Ladeuil
More tests.
2915
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2916
    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.
2917
                                       host=None, port=None, realm=None,
2918
                                       path=None):
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2919
        if host is None:
2920
            host = 'bar.org'
2921
        username = 'jim'
2922
        expected_prompt = expected_prompt_format % {
2923
            'scheme': scheme, 'host': host, 'port': port,
2924
            'realm': realm}
2925
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2926
        stderr = tests.StringIOWrapper()
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2927
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2928
                                            stdout=stdout, stderr=stderr)
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2929
        # We use an empty conf so that the user is always prompted
2930
        conf = config.AuthenticationConfig()
4222.3.5 by Jelmer Vernooij
Fix test.
2931
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
2932
                          realm=realm, path=path, ask=True))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2933
        self.assertEquals(expected_prompt, stderr.getvalue())
2934
        self.assertEquals('', stdout.getvalue())
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2935
2936
    def test_username_defaults_prompts(self):
2937
        # 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.
2938
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
2939
        self._check_default_username_prompt(
2940
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
2941
        self._check_default_username_prompt(
2942
            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.
2943
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
2944
    def test_username_default_no_prompt(self):
2945
        conf = config.AuthenticationConfig()
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
2946
        self.assertEquals(None,
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
2947
            conf.get_user('ftp', 'example.com'))
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
2948
        self.assertEquals("explicitdefault",
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
2949
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
2950
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2951
    def test_password_default_prompts(self):
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
2952
        # HTTP prompts can't be tested here, see test_http.py
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2953
        self._check_default_password_prompt(
5923.1.3 by Vincent Ladeuil
Even more unicode prompts fixes revealed by pqm.
2954
            u'FTP %(user)s@%(host)s password: ', 'ftp')
2955
        self._check_default_password_prompt(
2956
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
2957
        self._check_default_password_prompt(
2958
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
2900.2.14 by Vincent Ladeuil
More tests.
2959
        # SMTP port handling is a bit special (it's handled if embedded in the
2960
        # host too)
2900.2.22 by Vincent Ladeuil
Polishing.
2961
        # FIXME: should we: forbid that, extend it to other schemes, leave
2962
        # things as they are that's fine thank you ?
5923.1.3 by Vincent Ladeuil
Even more unicode prompts fixes revealed by pqm.
2963
        self._check_default_password_prompt(
2964
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
2965
        self._check_default_password_prompt(
2966
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
2967
        self._check_default_password_prompt(
2968
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
2900.2.14 by Vincent Ladeuil
More tests.
2969
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2970
    def test_ssh_password_emits_warning(self):
2971
        conf = config.AuthenticationConfig(_file=StringIO(
2972
                """
2973
[ssh with password]
2974
scheme=ssh
2975
host=bar.org
2976
user=jim
2977
password=jimpass
2978
"""))
2979
        entered_password = 'typed-by-hand'
2980
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2981
        stderr = tests.StringIOWrapper()
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2982
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2983
                                            stdout=stdout, stderr=stderr)
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2984
2985
        # Since the password defined in the authentication config is ignored,
2986
        # the user is prompted
2987
        self.assertEquals(entered_password,
2988
                          conf.get_password('ssh', 'bar.org', user='jim'))
2989
        self.assertContainsRe(
4794.1.17 by Robert Collins
Fix from vila for type log_log.
2990
            self.get_log(),
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2991
            'password ignored in section \[ssh with password\]')
2992
3420.1.3 by Vincent Ladeuil
John's review feedback.
2993
    def test_ssh_without_password_doesnt_emit_warning(self):
2994
        conf = config.AuthenticationConfig(_file=StringIO(
2995
                """
2996
[ssh with password]
2997
scheme=ssh
2998
host=bar.org
2999
user=jim
3000
"""))
3001
        entered_password = 'typed-by-hand'
3002
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
3003
        stderr = tests.StringIOWrapper()
3420.1.3 by Vincent Ladeuil
John's review feedback.
3004
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
3005
                                            stdout=stdout,
3006
                                            stderr=stderr)
3420.1.3 by Vincent Ladeuil
John's review feedback.
3007
3008
        # Since the password defined in the authentication config is ignored,
3009
        # the user is prompted
3010
        self.assertEquals(entered_password,
3011
                          conf.get_password('ssh', 'bar.org', user='jim'))
3420.1.4 by Vincent Ladeuil
Fix comment.
3012
        # No warning shoud be emitted since there is no password. We are only
3013
        # providing "user".
3420.1.3 by Vincent Ladeuil
John's review feedback.
3014
        self.assertNotContainsRe(
4794.1.15 by Robert Collins
Review feedback.
3015
            self.get_log(),
3420.1.3 by Vincent Ladeuil
John's review feedback.
3016
            'password ignored in section \[ssh with password\]')
3017
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
3018
    def test_uses_fallback_stores(self):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
3019
        self.overrideAttr(config, 'credential_store_registry',
3020
                          config.CredentialStoreRegistry())
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
3021
        store = StubCredentialStore()
3022
        store.add_credentials("http", "example.com", "joe", "secret")
3023
        config.credential_store_registry.register("stub", store, fallback=True)
3024
        conf = config.AuthenticationConfig(_file=StringIO())
3025
        creds = conf.get_credentials("http", "example.com")
3026
        self.assertEquals("joe", creds["user"])
3027
        self.assertEquals("secret", creds["password"])
3028
2900.2.14 by Vincent Ladeuil
More tests.
3029
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3030
class StubCredentialStore(config.CredentialStore):
3031
3032
    def __init__(self):
3033
        self._username = {}
3034
        self._password = {}
3035
3036
    def add_credentials(self, scheme, host, user, password=None):
3037
        self._username[(scheme, host)] = user
3038
        self._password[(scheme, host)] = password
3039
3040
    def get_credentials(self, scheme, host, port=None, user=None,
3041
        path=None, realm=None):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3042
        key = (scheme, host)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3043
        if not key in self._username:
3044
            return None
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3045
        return { "scheme": scheme, "host": host, "port": port,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3046
                "user": self._username[key], "password": self._password[key]}
3047
3048
3049
class CountingCredentialStore(config.CredentialStore):
3050
3051
    def __init__(self):
3052
        self._calls = 0
3053
3054
    def get_credentials(self, scheme, host, port=None, user=None,
3055
        path=None, realm=None):
3056
        self._calls += 1
3057
        return None
3058
3059
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
3060
class TestCredentialStoreRegistry(tests.TestCase):
3061
3062
    def _get_cs_registry(self):
3063
        return config.credential_store_registry
3064
3065
    def test_default_credential_store(self):
3066
        r = self._get_cs_registry()
3067
        default = r.get_credential_store(None)
3068
        self.assertIsInstance(default, config.PlainTextCredentialStore)
3069
3070
    def test_unknown_credential_store(self):
3071
        r = self._get_cs_registry()
3072
        # It's hard to imagine someone creating a credential store named
3073
        # 'unknown' so we use that as an never registered key.
3074
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
3075
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3076
    def test_fallback_none_registered(self):
3077
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3078
        self.assertEquals(None,
3079
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3080
3081
    def test_register(self):
3082
        r = config.CredentialStoreRegistry()
3083
        r.register("stub", StubCredentialStore(), fallback=False)
3084
        r.register("another", StubCredentialStore(), fallback=True)
3085
        self.assertEquals(["another", "stub"], r.keys())
3086
3087
    def test_register_lazy(self):
3088
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3089
        r.register_lazy("stub", "bzrlib.tests.test_config",
3090
                        "StubCredentialStore", fallback=False)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3091
        self.assertEquals(["stub"], r.keys())
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3092
        self.assertIsInstance(r.get_credential_store("stub"),
3093
                              StubCredentialStore)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3094
3095
    def test_is_fallback(self):
3096
        r = config.CredentialStoreRegistry()
3097
        r.register("stub1", None, fallback=False)
3098
        r.register("stub2", None, fallback=True)
3099
        self.assertEquals(False, r.is_fallback("stub1"))
3100
        self.assertEquals(True, r.is_fallback("stub2"))
3101
3102
    def test_no_fallback(self):
3103
        r = config.CredentialStoreRegistry()
3104
        store = CountingCredentialStore()
3105
        r.register("count", store, fallback=False)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3106
        self.assertEquals(None,
3107
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3108
        self.assertEquals(0, store._calls)
3109
3110
    def test_fallback_credentials(self):
3111
        r = config.CredentialStoreRegistry()
3112
        store = StubCredentialStore()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3113
        store.add_credentials("http", "example.com",
3114
                              "somebody", "geheim")
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3115
        r.register("stub", store, fallback=True)
3116
        creds = r.get_fallback_credentials("http", "example.com")
3117
        self.assertEquals("somebody", creds["user"])
3118
        self.assertEquals("geheim", creds["password"])
3119
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3120
    def test_fallback_first_wins(self):
3121
        r = config.CredentialStoreRegistry()
3122
        stub1 = StubCredentialStore()
3123
        stub1.add_credentials("http", "example.com",
3124
                              "somebody", "stub1")
3125
        r.register("stub1", stub1, fallback=True)
3126
        stub2 = StubCredentialStore()
3127
        stub2.add_credentials("http", "example.com",
3128
                              "somebody", "stub2")
3129
        r.register("stub2", stub1, fallback=True)
3130
        creds = r.get_fallback_credentials("http", "example.com")
3131
        self.assertEquals("somebody", creds["user"])
3132
        self.assertEquals("stub1", creds["password"])
3133
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
3134
3135
class TestPlainTextCredentialStore(tests.TestCase):
3136
3137
    def test_decode_password(self):
3138
        r = config.credential_store_registry
3139
        plain_text = r.get_credential_store()
3140
        decoded = plain_text.decode_password(dict(password='secret'))
3141
        self.assertEquals('secret', decoded)
3142
3143
2900.2.14 by Vincent Ladeuil
More tests.
3144
# 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.
3145
# can implement generic tests.
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
3146
# test_user_password_in_url
3147
# test_user_in_url_password_from_config
3148
# test_user_in_url_password_prompted
3149
# test_user_in_config
3150
# test_user_getpass.getuser
3151
# test_user_prompted ?
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
3152
class TestAuthenticationRing(tests.TestCaseWithTransport):
3153
    pass
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
3154
3155
3156
class TestAutoUserId(tests.TestCase):
3157
    """Test inferring an automatic user name."""
3158
3159
    def test_auto_user_id(self):
3160
        """Automatic inference of user name.
3161
        
3162
        This is a bit hard to test in an isolated way, because it depends on
3163
        system functions that go direct to /etc or perhaps somewhere else.
3164
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
3165
        to be able to choose a user name with no configuration.
3166
        """
3167
        if sys.platform == 'win32':
3168
            raise TestSkipped("User name inference not implemented on win32")
3169
        realname, address = config._auto_user_id()
3170
        if os.path.exists('/etc/mailname'):
5813.1.1 by Jelmer Vernooij
Allow realname to be empty in tests.
3171
            self.assertIsNot(None, realname)
3172
            self.assertIsNot(None, address)
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
3173
        else:
3174
            self.assertEquals((None, None), (realname, address))
3175