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