/brz/remove-bazaar

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