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