/brz/remove-bazaar

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