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