/brz/remove-bazaar

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