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