~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Michael Ellerman
  • Date: 2006-02-28 14:45:51 UTC
  • mto: (1558.1.18 Aaron's integration)
  • mto: This revision was merged to the branch mainline in revision 1586.
  • Revision ID: michael@ellerman.id.au-20060228144551-3d9941ecde4a0b0a
Update contrib/pwk for -p1 diffs from bzr

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005 by Canonical Ltd
 
2
#   Authors: Robert Collins <robert.collins@canonical.com>
2
3
#
3
4
# This program is free software; you can redistribute it and/or modify
4
5
# it under the terms of the GNU General Public License as published by
12
13
#
13
14
# You should have received a copy of the GNU General Public License
14
15
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
 
17
18
"""Tests for finding and reading the bzr config file[s]."""
18
19
# import system imports here
 
20
from bzrlib.util.configobj.configobj import ConfigObj, ConfigObjError
19
21
from cStringIO import StringIO
20
22
import os
21
23
import sys
22
 
import threading
23
 
 
24
 
 
25
 
from testtools import matchers
26
24
 
27
25
#import bzrlib specific imports here
28
 
from bzrlib import (
29
 
    branch,
30
 
    bzrdir,
31
 
    config,
32
 
    diff,
33
 
    errors,
34
 
    osutils,
35
 
    mail_client,
36
 
    ui,
37
 
    urlutils,
38
 
    remote,
39
 
    tests,
40
 
    trace,
41
 
    )
42
 
from bzrlib.symbol_versioning import (
43
 
    deprecated_in,
44
 
    )
45
 
from bzrlib.transport import remote as transport_remote
46
 
from bzrlib.tests import (
47
 
    features,
48
 
    scenarios,
49
 
    test_server,
50
 
    )
51
 
from bzrlib.util.configobj import configobj
52
 
 
53
 
 
54
 
def lockable_config_scenarios():
55
 
    return [
56
 
        ('global',
57
 
         {'config_class': config.GlobalConfig,
58
 
          'config_args': [],
59
 
          'config_section': 'DEFAULT'}),
60
 
        ('locations',
61
 
         {'config_class': config.LocationConfig,
62
 
          'config_args': ['.'],
63
 
          'config_section': '.'}),]
64
 
 
65
 
 
66
 
load_tests = scenarios.load_tests_apply_scenarios
67
 
 
68
 
# Register helpers to build stores
69
 
config.test_store_builder_registry.register(
70
 
    'configobj', lambda test: config.IniFileStore(test.get_transport(),
71
 
                                                  'configobj.conf'))
72
 
config.test_store_builder_registry.register(
73
 
    'bazaar', lambda test: config.GlobalStore())
74
 
config.test_store_builder_registry.register(
75
 
    'location', lambda test: config.LocationStore())
76
 
 
77
 
 
78
 
def build_backing_branch(test, relpath,
79
 
                         transport_class=None, server_class=None):
80
 
    """Test helper to create a backing branch only once.
81
 
 
82
 
    Some tests needs multiple stores/stacks to check concurrent update
83
 
    behaviours. As such, they need to build different branch *objects* even if
84
 
    they share the branch on disk.
85
 
 
86
 
    :param relpath: The relative path to the branch. (Note that the helper
87
 
        should always specify the same relpath).
88
 
 
89
 
    :param transport_class: The Transport class the test needs to use.
90
 
 
91
 
    :param server_class: The server associated with the ``transport_class``
92
 
        above.
93
 
 
94
 
    Either both or neither of ``transport_class`` and ``server_class`` should
95
 
    be specified.
96
 
    """
97
 
    if transport_class is not None and server_class is not None:
98
 
        test.transport_class = transport_class
99
 
        test.transport_server = server_class
100
 
    elif not (transport_class is None and server_class is None):
101
 
        raise AssertionError('Specify both ``transport_class`` and '
102
 
                             '``server_class`` or neither of them')
103
 
    if getattr(test, 'backing_branch', None) is None:
104
 
        # First call, let's build the branch on disk
105
 
        test.backing_branch = test.make_branch(relpath)
106
 
 
107
 
 
108
 
def build_branch_store(test):
109
 
    build_backing_branch(test, 'branch')
110
 
    b = branch.Branch.open('branch')
111
 
    return config.BranchStore(b)
112
 
config.test_store_builder_registry.register('branch', build_branch_store)
113
 
 
114
 
 
115
 
def build_control_store(test):
116
 
    build_backing_branch(test, 'branch')
117
 
    b = bzrdir.BzrDir.open('branch')
118
 
    return config.ControlStore(b)
119
 
config.test_store_builder_registry.register('control', build_control_store)
120
 
 
121
 
 
122
 
def build_remote_branch_store(test):
123
 
    # There is only one permutation (but we won't be able to handle more with
124
 
    # this design anyway)
125
 
    (transport_class,
126
 
     server_class) = transport_remote.get_test_permutations()[0]
127
 
    build_backing_branch(test, 'branch', transport_class, server_class)
128
 
    b = branch.Branch.open(test.get_url('branch'))
129
 
    return config.BranchStore(b)
130
 
config.test_store_builder_registry.register('remote_branch',
131
 
                                            build_remote_branch_store)
132
 
 
133
 
 
134
 
config.test_stack_builder_registry.register(
135
 
    'bazaar', lambda test: config.GlobalStack())
136
 
config.test_stack_builder_registry.register(
137
 
    'location', lambda test: config.LocationStack('.'))
138
 
 
139
 
 
140
 
def build_branch_stack(test):
141
 
    build_backing_branch(test, 'branch')
142
 
    b = branch.Branch.open('branch')
143
 
    return config.BranchStack(b)
144
 
config.test_stack_builder_registry.register('branch', build_branch_stack)
145
 
 
146
 
 
147
 
def build_remote_branch_stack(test):
148
 
    # There is only one permutation (but we won't be able to handle more with
149
 
    # this design anyway)
150
 
    (transport_class,
151
 
     server_class) = transport_remote.get_test_permutations()[0]
152
 
    build_backing_branch(test, 'branch', transport_class, server_class)
153
 
    b = branch.Branch.open(test.get_url('branch'))
154
 
    return config.RemoteBranchStack(b)
155
 
config.test_stack_builder_registry.register('remote_branch',
156
 
                                            build_remote_branch_stack)
157
 
 
158
 
def build_remote_control_stack(test):
159
 
    # There is only one permutation (but we won't be able to handle more with
160
 
    # this design anyway)
161
 
    (transport_class,
162
 
     server_class) = transport_remote.get_test_permutations()[0]
163
 
    # We need only a bzrdir for this, not a full branch, but it's not worth
164
 
    # creating a dedicated helper to create only the bzrdir
165
 
    build_backing_branch(test, 'branch', transport_class, server_class)
166
 
    b = branch.Branch.open(test.get_url('branch'))
167
 
    return config.RemoteControlStack(b.bzrdir)
168
 
config.test_stack_builder_registry.register('remote_control',
169
 
                                            build_remote_control_stack)
 
26
import bzrlib.config as config
 
27
import bzrlib.errors as errors
 
28
from bzrlib.tests import TestCase, TestCaseInTempDir
170
29
 
171
30
 
172
31
sample_long_alias="log -r-15..-1 --line"
173
 
sample_config_text = u"""
174
 
[DEFAULT]
175
 
email=Erik B\u00e5gfors <erik@bagfors.nu>
176
 
editor=vim
177
 
change_editor=vimdiff -of @new_path @old_path
178
 
gpg_signing_command=gnome-gpg
179
 
gpg_signing_key=DD4D5088
180
 
log_format=short
181
 
validate_signatures_in_log=true
182
 
acceptable_keys=amy
183
 
user_global_option=something
184
 
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
185
 
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
186
 
bzr.mergetool.newtool='"newtool with spaces" {this_temp}'
187
 
bzr.default_mergetool=sometool
188
 
[ALIASES]
189
 
h=help
190
 
ll=""" + sample_long_alias + "\n"
191
 
 
192
 
 
193
 
sample_always_signatures = """
194
 
[DEFAULT]
195
 
check_signatures=ignore
196
 
create_signatures=always
197
 
"""
198
 
 
199
 
sample_ignore_signatures = """
200
 
[DEFAULT]
201
 
check_signatures=require
202
 
create_signatures=never
203
 
"""
204
 
 
205
 
sample_maybe_signatures = """
206
 
[DEFAULT]
207
 
check_signatures=ignore
208
 
create_signatures=when-required
209
 
"""
210
 
 
211
 
sample_branches_text = """
212
 
[http://www.example.com]
213
 
# Top level policy
214
 
email=Robert Collins <robertc@example.org>
215
 
normal_option = normal
216
 
appendpath_option = append
217
 
appendpath_option:policy = appendpath
218
 
norecurse_option = norecurse
219
 
norecurse_option:policy = norecurse
220
 
[http://www.example.com/ignoreparent]
221
 
# different project: ignore parent dir config
222
 
ignore_parents=true
223
 
[http://www.example.com/norecurse]
224
 
# configuration items that only apply to this dir
225
 
recurse=false
226
 
normal_option = norecurse
227
 
[http://www.example.com/dir]
228
 
appendpath_option = normal
229
 
[/b/]
230
 
check_signatures=require
231
 
# test trailing / matching with no children
232
 
[/a/]
233
 
check_signatures=check-available
234
 
gpg_signing_command=false
235
 
gpg_signing_key=default
236
 
user_local_option=local
237
 
# test trailing / matching
238
 
[/a/*]
239
 
#subdirs will match but not the parent
240
 
[/a/c]
241
 
check_signatures=ignore
242
 
post_commit=bzrlib.tests.test_config.post_commit
243
 
#testing explicit beats globs
244
 
"""
245
 
 
246
 
 
247
 
def create_configs(test):
248
 
    """Create configuration files for a given test.
249
 
 
250
 
    This requires creating a tree (and populate the ``test.tree`` attribute)
251
 
    and its associated branch and will populate the following attributes:
252
 
 
253
 
    - branch_config: A BranchConfig for the associated branch.
254
 
 
255
 
    - locations_config : A LocationConfig for the associated branch
256
 
 
257
 
    - bazaar_config: A GlobalConfig.
258
 
 
259
 
    The tree and branch are created in a 'tree' subdirectory so the tests can
260
 
    still use the test directory to stay outside of the branch.
261
 
    """
262
 
    tree = test.make_branch_and_tree('tree')
263
 
    test.tree = tree
264
 
    test.branch_config = config.BranchConfig(tree.branch)
265
 
    test.locations_config = config.LocationConfig(tree.basedir)
266
 
    test.bazaar_config = config.GlobalConfig()
267
 
 
268
 
 
269
 
def create_configs_with_file_option(test):
270
 
    """Create configuration files with a ``file`` option set in each.
271
 
 
272
 
    This builds on ``create_configs`` and add one ``file`` option in each
273
 
    configuration with a value which allows identifying the configuration file.
274
 
    """
275
 
    create_configs(test)
276
 
    test.bazaar_config.set_user_option('file', 'bazaar')
277
 
    test.locations_config.set_user_option('file', 'locations')
278
 
    test.branch_config.set_user_option('file', 'branch')
279
 
 
280
 
 
281
 
class TestOptionsMixin:
282
 
 
283
 
    def assertOptions(self, expected, conf):
284
 
        # We don't care about the parser (as it will make tests hard to write
285
 
        # and error-prone anyway)
286
 
        self.assertThat([opt[:4] for opt in conf._get_options()],
287
 
                        matchers.Equals(expected))
 
32
sample_config_text = ("[DEFAULT]\n"
 
33
                      "email=Robert Collins <robertc@example.com>\n"
 
34
                      "editor=vim\n"
 
35
                      "gpg_signing_command=gnome-gpg\n"
 
36
                      "log_format=short\n"
 
37
                      "user_global_option=something\n"
 
38
                      "[ALIASES]\n"
 
39
                      "h=help\n"
 
40
                      "ll=" + sample_long_alias + "\n")
 
41
 
 
42
 
 
43
sample_always_signatures = ("[DEFAULT]\n"
 
44
                            "check_signatures=require\n")
 
45
 
 
46
 
 
47
sample_ignore_signatures = ("[DEFAULT]\n"
 
48
                            "check_signatures=ignore\n")
 
49
 
 
50
 
 
51
sample_maybe_signatures = ("[DEFAULT]\n"
 
52
                            "check_signatures=check-available\n")
 
53
 
 
54
 
 
55
sample_branches_text = ("[http://www.example.com]\n"
 
56
                        "# Top level policy\n"
 
57
                        "email=Robert Collins <robertc@example.org>\n"
 
58
                        "[http://www.example.com/useglobal]\n"
 
59
                        "# different project, forces global lookup\n"
 
60
                        "recurse=false\n"
 
61
                        "[/b/]\n"
 
62
                        "check_signatures=require\n"
 
63
                        "# test trailing / matching with no children\n"
 
64
                        "[/a/]\n"
 
65
                        "check_signatures=check-available\n"
 
66
                        "gpg_signing_command=false\n"
 
67
                        "user_local_option=local\n"
 
68
                        "# test trailing / matching\n"
 
69
                        "[/a/*]\n"
 
70
                        "#subdirs will match but not the parent\n"
 
71
                        "recurse=False\n"
 
72
                        "[/a/c]\n"
 
73
                        "check_signatures=ignore\n"
 
74
                        "post_commit=bzrlib.tests.test_config.post_commit\n"
 
75
                        "#testing explicit beats globs\n")
 
76
 
288
77
 
289
78
 
290
79
class InstrumentedConfigObj(object):
298
87
        self._calls.append(('__getitem__', key))
299
88
        return self
300
89
 
301
 
    def __init__(self, input, encoding=None):
302
 
        self._calls = [('__init__', input, encoding)]
 
90
    def __init__(self, input):
 
91
        self._calls = [('__init__', input)]
303
92
 
304
93
    def __setitem__(self, key, value):
305
94
        self._calls.append(('__setitem__', key, value))
306
95
 
307
 
    def __delitem__(self, key):
308
 
        self._calls.append(('__delitem__', key))
309
 
 
310
 
    def keys(self):
311
 
        self._calls.append(('keys',))
312
 
        return []
313
 
 
314
 
    def reload(self):
315
 
        self._calls.append(('reload',))
316
 
 
317
 
    def write(self, arg):
 
96
    def write(self):
318
97
        self._calls.append(('write',))
319
98
 
320
 
    def as_bool(self, value):
321
 
        self._calls.append(('as_bool', value))
322
 
        return False
323
 
 
324
 
    def get_value(self, section, name):
325
 
        self._calls.append(('get_value', section, name))
326
 
        return None
327
 
 
328
99
 
329
100
class FakeBranch(object):
330
101
 
331
 
    def __init__(self, base=None, user_id=None):
332
 
        if base is None:
333
 
            self.base = "http://example.com/branches/demo"
334
 
        else:
335
 
            self.base = base
336
 
        self._transport = self.control_files = \
337
 
            FakeControlFilesAndTransport(user_id=user_id)
338
 
 
339
 
    def _get_config(self):
340
 
        return config.TransportConfig(self._transport, 'branch.conf')
341
 
 
342
 
    def lock_write(self):
343
 
        pass
344
 
 
345
 
    def unlock(self):
346
 
        pass
347
 
 
348
 
 
349
 
class FakeControlFilesAndTransport(object):
350
 
 
351
 
    def __init__(self, user_id=None):
352
 
        self.files = {}
353
 
        if user_id:
354
 
            self.files['email'] = user_id
355
 
        self._transport = self
 
102
    def __init__(self):
 
103
        self.base = "http://example.com/branches/demo"
 
104
        self.control_files = FakeControlFiles()
 
105
 
 
106
 
 
107
class FakeControlFiles(object):
 
108
 
 
109
    def __init__(self):
 
110
        self.email = 'Robert Collins <robertc@example.net>\n'
356
111
 
357
112
    def get_utf8(self, filename):
358
 
        # from LockableFiles
359
 
        raise AssertionError("get_utf8 should no longer be used")
360
 
 
361
 
    def get(self, filename):
362
 
        # from Transport
363
 
        try:
364
 
            return StringIO(self.files[filename])
365
 
        except KeyError:
366
 
            raise errors.NoSuchFile(filename)
367
 
 
368
 
    def get_bytes(self, filename):
369
 
        # from Transport
370
 
        try:
371
 
            return self.files[filename]
372
 
        except KeyError:
373
 
            raise errors.NoSuchFile(filename)
374
 
 
375
 
    def put(self, filename, fileobj):
376
 
        self.files[filename] = fileobj.read()
377
 
 
378
 
    def put_file(self, filename, fileobj):
379
 
        return self.put(filename, fileobj)
 
113
        if filename != 'email':
 
114
            raise NotImplementedError
 
115
        if self.email is not None:
 
116
            return StringIO(self.email)
 
117
        raise errors.NoSuchFile(filename)
380
118
 
381
119
 
382
120
class InstrumentedConfig(config.Config):
383
121
    """An instrumented config that supplies stubs for template methods."""
384
 
 
 
122
    
385
123
    def __init__(self):
386
124
        super(InstrumentedConfig, self).__init__()
387
125
        self._calls = []
395
133
        self._calls.append('_get_signature_checking')
396
134
        return self._signatures
397
135
 
398
 
    def _get_change_editor(self):
399
 
        self._calls.append('_get_change_editor')
400
 
        return 'vimdiff -fo @new_path @old_path'
401
 
 
402
136
 
403
137
bool_config = """[DEFAULT]
404
138
active = true
407
141
active = True
408
142
nonactive = False
409
143
"""
410
 
 
411
 
 
412
 
class TestConfigObj(tests.TestCase):
413
 
 
 
144
class TestConfigObj(TestCase):
414
145
    def test_get_bool(self):
415
 
        co = config.ConfigObj(StringIO(bool_config))
 
146
        from bzrlib.config import ConfigObj
 
147
        co = ConfigObj(StringIO(bool_config))
416
148
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
417
149
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
418
150
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
419
151
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
420
152
 
421
 
    def test_hash_sign_in_value(self):
422
 
        """
423
 
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
424
 
        treated as comments when read in again. (#86838)
425
 
        """
426
 
        co = config.ConfigObj()
427
 
        co['test'] = 'foo#bar'
428
 
        outfile = StringIO()
429
 
        co.write(outfile=outfile)
430
 
        lines = outfile.getvalue().splitlines()
431
 
        self.assertEqual(lines, ['test = "foo#bar"'])
432
 
        co2 = config.ConfigObj(lines)
433
 
        self.assertEqual(co2['test'], 'foo#bar')
434
 
 
435
 
    def test_triple_quotes(self):
436
 
        # Bug #710410: if the value string has triple quotes
437
 
        # then ConfigObj versions up to 4.7.2 will quote them wrong
438
 
        # and won't able to read them back
439
 
        triple_quotes_value = '''spam
440
 
""" that's my spam """
441
 
eggs'''
442
 
        co = config.ConfigObj()
443
 
        co['test'] = triple_quotes_value
444
 
        # While writing this test another bug in ConfigObj has been found:
445
 
        # method co.write() without arguments produces list of lines
446
 
        # one option per line, and multiline values are not split
447
 
        # across multiple lines,
448
 
        # and that breaks the parsing these lines back by ConfigObj.
449
 
        # This issue only affects test, but it's better to avoid
450
 
        # `co.write()` construct at all.
451
 
        # [bialix 20110222] bug report sent to ConfigObj's author
452
 
        outfile = StringIO()
453
 
        co.write(outfile=outfile)
454
 
        output = outfile.getvalue()
455
 
        # now we're trying to read it back
456
 
        co2 = config.ConfigObj(StringIO(output))
457
 
        self.assertEquals(triple_quotes_value, co2['test'])
458
 
 
459
 
 
460
 
erroneous_config = """[section] # line 1
461
 
good=good # line 2
462
 
[section] # line 3
463
 
whocares=notme # line 4
464
 
"""
465
 
 
466
 
 
467
 
class TestConfigObjErrors(tests.TestCase):
468
 
 
469
 
    def test_duplicate_section_name_error_line(self):
470
 
        try:
471
 
            co = configobj.ConfigObj(StringIO(erroneous_config),
472
 
                                     raise_errors=True)
473
 
        except config.configobj.DuplicateError, e:
474
 
            self.assertEqual(3, e.line_number)
475
 
        else:
476
 
            self.fail('Error in config file not detected')
477
 
 
478
 
 
479
 
class TestConfig(tests.TestCase):
 
153
 
 
154
class TestConfig(TestCase):
480
155
 
481
156
    def test_constructs(self):
482
157
        config.Config()
483
 
 
 
158
 
484
159
    def test_no_default_editor(self):
485
 
        self.assertRaises(
486
 
            NotImplementedError,
487
 
            self.applyDeprecated, deprecated_in((2, 4, 0)),
488
 
            config.Config().get_editor)
 
160
        self.assertRaises(NotImplementedError, config.Config().get_editor)
489
161
 
490
162
    def test_user_email(self):
491
163
        my_config = InstrumentedConfig()
500
172
 
501
173
    def test_signatures_default(self):
502
174
        my_config = config.Config()
503
 
        self.assertFalse(my_config.signature_needed())
504
175
        self.assertEqual(config.CHECK_IF_POSSIBLE,
505
176
                         my_config.signature_checking())
506
 
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
507
 
                         my_config.signing_policy())
508
177
 
509
178
    def test_signatures_template_method(self):
510
179
        my_config = InstrumentedConfig()
534
203
        my_config = config.Config()
535
204
        self.assertEqual('long', my_config.log_format())
536
205
 
537
 
    def test_acceptable_keys_default(self):
538
 
        my_config = config.Config()
539
 
        self.assertEqual(None, my_config.acceptable_keys())
540
 
 
541
 
    def test_validate_signatures_in_log_default(self):
542
 
        my_config = config.Config()
543
 
        self.assertEqual(False, my_config.validate_signatures_in_log())
544
 
 
545
 
    def test_get_change_editor(self):
546
 
        my_config = InstrumentedConfig()
547
 
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
548
 
        self.assertEqual(['_get_change_editor'], my_config._calls)
549
 
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
550
 
        self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
551
 
                         change_editor.command_template)
552
 
 
553
 
 
554
 
class TestConfigPath(tests.TestCase):
 
206
 
 
207
class TestConfigPath(TestCase):
555
208
 
556
209
    def setUp(self):
557
210
        super(TestConfigPath, self).setUp()
558
 
        self.overrideEnv('HOME', '/home/bogus')
559
 
        self.overrideEnv('XDG_CACHE_DIR', '')
560
 
        if sys.platform == 'win32':
561
 
            self.overrideEnv(
562
 
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
563
 
            self.bzr_home = \
564
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
565
 
        else:
566
 
            self.bzr_home = '/home/bogus/.bazaar'
 
211
        self.old_home = os.environ.get('HOME', None)
 
212
        self.old_appdata = os.environ.get('APPDATA', None)
 
213
        os.environ['HOME'] = '/home/bogus'
 
214
        os.environ['APPDATA'] = \
 
215
            r'C:\Documents and Settings\bogus\Application Data'
567
216
 
 
217
    def tearDown(self):
 
218
        if self.old_home is None:
 
219
            del os.environ['HOME']
 
220
        else:
 
221
            os.environ['HOME'] = self.old_home
 
222
        if self.old_appdata is None:
 
223
            del os.environ['APPDATA']
 
224
        else:
 
225
            os.environ['APPDATA'] = self.old_appdata
 
226
        super(TestConfigPath, self).tearDown()
 
227
    
568
228
    def test_config_dir(self):
569
 
        self.assertEqual(config.config_dir(), self.bzr_home)
 
229
        if sys.platform == 'win32':
 
230
            self.assertEqual(config.config_dir(), 
 
231
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0')
 
232
        else:
 
233
            self.assertEqual(config.config_dir(), '/home/bogus/.bazaar')
570
234
 
571
235
    def test_config_filename(self):
572
 
        self.assertEqual(config.config_filename(),
573
 
                         self.bzr_home + '/bazaar.conf')
574
 
 
575
 
    def test_locations_config_filename(self):
576
 
        self.assertEqual(config.locations_config_filename(),
577
 
                         self.bzr_home + '/locations.conf')
578
 
 
579
 
    def test_authentication_config_filename(self):
580
 
        self.assertEqual(config.authentication_config_filename(),
581
 
                         self.bzr_home + '/authentication.conf')
582
 
 
583
 
    def test_xdg_cache_dir(self):
584
 
        self.assertEqual(config.xdg_cache_dir(),
585
 
            '/home/bogus/.cache')
586
 
 
587
 
 
588
 
class TestXDGConfigDir(tests.TestCaseInTempDir):
589
 
    # must be in temp dir because config tests for the existence of the bazaar
590
 
    # subdirectory of $XDG_CONFIG_HOME
591
 
 
592
 
    def setUp(self):
593
 
        if sys.platform in ('darwin', 'win32'):
594
 
            raise tests.TestNotApplicable(
595
 
                'XDG config dir not used on this platform')
596
 
        super(TestXDGConfigDir, self).setUp()
597
 
        self.overrideEnv('HOME', self.test_home_dir)
598
 
        # BZR_HOME overrides everything we want to test so unset it.
599
 
        self.overrideEnv('BZR_HOME', None)
600
 
 
601
 
    def test_xdg_config_dir_exists(self):
602
 
        """When ~/.config/bazaar exists, use it as the config dir."""
603
 
        newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
604
 
        os.makedirs(newdir)
605
 
        self.assertEqual(config.config_dir(), newdir)
606
 
 
607
 
    def test_xdg_config_home(self):
608
 
        """When XDG_CONFIG_HOME is set, use it."""
609
 
        xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
610
 
        self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
611
 
        newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
612
 
        os.makedirs(newdir)
613
 
        self.assertEqual(config.config_dir(), newdir)
614
 
 
615
 
 
616
 
class TestIniConfig(tests.TestCaseInTempDir):
617
 
 
618
 
    def make_config_parser(self, s):
619
 
        conf = config.IniBasedConfig.from_string(s)
620
 
        return conf, conf._get_parser()
621
 
 
622
 
 
623
 
class TestIniConfigBuilding(TestIniConfig):
 
236
        if sys.platform == 'win32':
 
237
            self.assertEqual(config.config_filename(), 
 
238
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/bazaar.conf')
 
239
        else:
 
240
            self.assertEqual(config.config_filename(),
 
241
                             '/home/bogus/.bazaar/bazaar.conf')
 
242
 
 
243
    def test_branches_config_filename(self):
 
244
        if sys.platform == 'win32':
 
245
            self.assertEqual(config.branches_config_filename(), 
 
246
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/branches.conf')
 
247
        else:
 
248
            self.assertEqual(config.branches_config_filename(),
 
249
                             '/home/bogus/.bazaar/branches.conf')
 
250
 
 
251
class TestIniConfig(TestCase):
624
252
 
625
253
    def test_contructs(self):
626
 
        my_config = config.IniBasedConfig()
 
254
        my_config = config.IniBasedConfig("nothing")
627
255
 
628
256
    def test_from_fp(self):
629
 
        my_config = config.IniBasedConfig.from_string(sample_config_text)
630
 
        self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
 
257
        config_file = StringIO(sample_config_text)
 
258
        my_config = config.IniBasedConfig(None)
 
259
        self.failUnless(
 
260
            isinstance(my_config._get_parser(file=config_file),
 
261
                        ConfigObj))
631
262
 
632
263
    def test_cached(self):
633
 
        my_config = config.IniBasedConfig.from_string(sample_config_text)
634
 
        parser = my_config._get_parser()
635
 
        self.assertTrue(my_config._get_parser() is parser)
636
 
 
637
 
    def _dummy_chown(self, path, uid, gid):
638
 
        self.path, self.uid, self.gid = path, uid, gid
639
 
 
640
 
    def test_ini_config_ownership(self):
641
 
        """Ensure that chown is happening during _write_config_file"""
642
 
        self.requireFeature(features.chown_feature)
643
 
        self.overrideAttr(os, 'chown', self._dummy_chown)
644
 
        self.path = self.uid = self.gid = None
645
 
        conf = config.IniBasedConfig(file_name='./foo.conf')
646
 
        conf._write_config_file()
647
 
        self.assertEquals(self.path, './foo.conf')
648
 
        self.assertTrue(isinstance(self.uid, int))
649
 
        self.assertTrue(isinstance(self.gid, int))
650
 
 
651
 
    def test_get_filename_parameter_is_deprecated_(self):
652
 
        conf = self.callDeprecated([
653
 
            'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
654
 
            ' Use file_name instead.'],
655
 
            config.IniBasedConfig, lambda: 'ini.conf')
656
 
        self.assertEqual('ini.conf', conf.file_name)
657
 
 
658
 
    def test_get_parser_file_parameter_is_deprecated_(self):
659
 
        config_file = StringIO(sample_config_text.encode('utf-8'))
660
 
        conf = config.IniBasedConfig.from_string(sample_config_text)
661
 
        conf = self.callDeprecated([
662
 
            'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
663
 
            ' Use IniBasedConfig(_content=xxx) instead.'],
664
 
            conf._get_parser, file=config_file)
665
 
 
666
 
 
667
 
class TestIniConfigSaving(tests.TestCaseInTempDir):
668
 
 
669
 
    def test_cant_save_without_a_file_name(self):
670
 
        conf = config.IniBasedConfig()
671
 
        self.assertRaises(AssertionError, conf._write_config_file)
672
 
 
673
 
    def test_saved_with_content(self):
674
 
        content = 'foo = bar\n'
675
 
        conf = config.IniBasedConfig.from_string(
676
 
            content, file_name='./test.conf', save=True)
677
 
        self.assertFileEqual(content, 'test.conf')
678
 
 
679
 
 
680
 
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
681
 
    """What is the default value of expand for config options.
682
 
 
683
 
    This is an opt-in beta feature used to evaluate whether or not option
684
 
    references can appear in dangerous place raising exceptions, disapearing
685
 
    (and as such corrupting data) or if it's safe to activate the option by
686
 
    default.
687
 
 
688
 
    Note that these tests relies on config._expand_default_value being already
689
 
    overwritten in the parent class setUp.
690
 
    """
691
 
 
692
 
    def setUp(self):
693
 
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
694
 
        self.config = None
695
 
        self.warnings = []
696
 
        def warning(*args):
697
 
            self.warnings.append(args[0] % args[1:])
698
 
        self.overrideAttr(trace, 'warning', warning)
699
 
 
700
 
    def get_config(self, expand):
701
 
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
702
 
                                            save=True)
703
 
        return c
704
 
 
705
 
    def assertExpandIs(self, expected):
706
 
        actual = config._get_expand_default_value()
707
 
        #self.config.get_user_option_as_bool('bzr.config.expand')
708
 
        self.assertEquals(expected, actual)
709
 
 
710
 
    def test_default_is_None(self):
711
 
        self.assertEquals(None, config._expand_default_value)
712
 
 
713
 
    def test_default_is_False_even_if_None(self):
714
 
        self.config = self.get_config(None)
715
 
        self.assertExpandIs(False)
716
 
 
717
 
    def test_default_is_False_even_if_invalid(self):
718
 
        self.config = self.get_config('<your choice>')
719
 
        self.assertExpandIs(False)
720
 
        # ...
721
 
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
722
 
        # Wait, you've been warned !
723
 
        self.assertLength(1, self.warnings)
724
 
        self.assertEquals(
725
 
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
726
 
            self.warnings[0])
727
 
 
728
 
    def test_default_is_True(self):
729
 
        self.config = self.get_config(True)
730
 
        self.assertExpandIs(True)
731
 
 
732
 
    def test_default_is_False(self):
733
 
        self.config = self.get_config(False)
734
 
        self.assertExpandIs(False)
735
 
 
736
 
 
737
 
class TestIniConfigOptionExpansion(tests.TestCase):
738
 
    """Test option expansion from the IniConfig level.
739
 
 
740
 
    What we really want here is to test the Config level, but the class being
741
 
    abstract as far as storing values is concerned, this can't be done
742
 
    properly (yet).
743
 
    """
744
 
    # FIXME: This should be rewritten when all configs share a storage
745
 
    # implementation -- vila 2011-02-18
746
 
 
747
 
    def get_config(self, string=None):
748
 
        if string is None:
749
 
            string = ''
750
 
        c = config.IniBasedConfig.from_string(string)
751
 
        return c
752
 
 
753
 
    def assertExpansion(self, expected, conf, string, env=None):
754
 
        self.assertEquals(expected, conf.expand_options(string, env))
755
 
 
756
 
    def test_no_expansion(self):
757
 
        c = self.get_config('')
758
 
        self.assertExpansion('foo', c, 'foo')
759
 
 
760
 
    def test_env_adding_options(self):
761
 
        c = self.get_config('')
762
 
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
763
 
 
764
 
    def test_env_overriding_options(self):
765
 
        c = self.get_config('foo=baz')
766
 
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
767
 
 
768
 
    def test_simple_ref(self):
769
 
        c = self.get_config('foo=xxx')
770
 
        self.assertExpansion('xxx', c, '{foo}')
771
 
 
772
 
    def test_unknown_ref(self):
773
 
        c = self.get_config('')
774
 
        self.assertRaises(errors.ExpandingUnknownOption,
775
 
                          c.expand_options, '{foo}')
776
 
 
777
 
    def test_indirect_ref(self):
778
 
        c = self.get_config('''
779
 
foo=xxx
780
 
bar={foo}
781
 
''')
782
 
        self.assertExpansion('xxx', c, '{bar}')
783
 
 
784
 
    def test_embedded_ref(self):
785
 
        c = self.get_config('''
786
 
foo=xxx
787
 
bar=foo
788
 
''')
789
 
        self.assertExpansion('xxx', c, '{{bar}}')
790
 
 
791
 
    def test_simple_loop(self):
792
 
        c = self.get_config('foo={foo}')
793
 
        self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
794
 
 
795
 
    def test_indirect_loop(self):
796
 
        c = self.get_config('''
797
 
foo={bar}
798
 
bar={baz}
799
 
baz={foo}''')
800
 
        e = self.assertRaises(errors.OptionExpansionLoop,
801
 
                              c.expand_options, '{foo}')
802
 
        self.assertEquals('foo->bar->baz', e.refs)
803
 
        self.assertEquals('{foo}', e.string)
804
 
 
805
 
    def test_list(self):
806
 
        conf = self.get_config('''
807
 
foo=start
808
 
bar=middle
809
 
baz=end
810
 
list={foo},{bar},{baz}
811
 
''')
812
 
        self.assertEquals(['start', 'middle', 'end'],
813
 
                           conf.get_user_option('list', expand=True))
814
 
 
815
 
    def test_cascading_list(self):
816
 
        conf = self.get_config('''
817
 
foo=start,{bar}
818
 
bar=middle,{baz}
819
 
baz=end
820
 
list={foo}
821
 
''')
822
 
        self.assertEquals(['start', 'middle', 'end'],
823
 
                           conf.get_user_option('list', expand=True))
824
 
 
825
 
    def test_pathological_hidden_list(self):
826
 
        conf = self.get_config('''
827
 
foo=bin
828
 
bar=go
829
 
start={foo
830
 
middle=},{
831
 
end=bar}
832
 
hidden={start}{middle}{end}
833
 
''')
834
 
        # Nope, it's either a string or a list, and the list wins as soon as a
835
 
        # ',' appears, so the string concatenation never occur.
836
 
        self.assertEquals(['{foo', '}', '{', 'bar}'],
837
 
                          conf.get_user_option('hidden', expand=True))
838
 
 
839
 
 
840
 
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
841
 
 
842
 
    def get_config(self, location, string=None):
843
 
        if string is None:
844
 
            string = ''
845
 
        # Since we don't save the config we won't strictly require to inherit
846
 
        # from TestCaseInTempDir, but an error occurs so quickly...
847
 
        c = config.LocationConfig.from_string(string, location)
848
 
        return c
849
 
 
850
 
    def test_dont_cross_unrelated_section(self):
851
 
        c = self.get_config('/another/branch/path','''
852
 
[/one/branch/path]
853
 
foo = hello
854
 
bar = {foo}/2
855
 
 
856
 
[/another/branch/path]
857
 
bar = {foo}/2
858
 
''')
859
 
        self.assertRaises(errors.ExpandingUnknownOption,
860
 
                          c.get_user_option, 'bar', expand=True)
861
 
 
862
 
    def test_cross_related_sections(self):
863
 
        c = self.get_config('/project/branch/path','''
864
 
[/project]
865
 
foo = qu
866
 
 
867
 
[/project/branch/path]
868
 
bar = {foo}ux
869
 
''')
870
 
        self.assertEquals('quux', c.get_user_option('bar', expand=True))
871
 
 
872
 
 
873
 
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
874
 
 
875
 
    def test_cannot_reload_without_name(self):
876
 
        conf = config.IniBasedConfig.from_string(sample_config_text)
877
 
        self.assertRaises(AssertionError, conf.reload)
878
 
 
879
 
    def test_reload_see_new_value(self):
880
 
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
881
 
                                               file_name='./test/conf')
882
 
        c1._write_config_file()
883
 
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
884
 
                                               file_name='./test/conf')
885
 
        c2._write_config_file()
886
 
        self.assertEqual('vim', c1.get_user_option('editor'))
887
 
        self.assertEqual('emacs', c2.get_user_option('editor'))
888
 
        # Make sure we get the Right value
889
 
        c1.reload()
890
 
        self.assertEqual('emacs', c1.get_user_option('editor'))
891
 
 
892
 
 
893
 
class TestLockableConfig(tests.TestCaseInTempDir):
894
 
 
895
 
    scenarios = lockable_config_scenarios()
896
 
 
897
 
    # Set by load_tests
898
 
    config_class = None
899
 
    config_args = None
900
 
    config_section = None
901
 
 
902
 
    def setUp(self):
903
 
        super(TestLockableConfig, self).setUp()
904
 
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
905
 
        self.config = self.create_config(self._content)
906
 
 
907
 
    def get_existing_config(self):
908
 
        return self.config_class(*self.config_args)
909
 
 
910
 
    def create_config(self, content):
911
 
        kwargs = dict(save=True)
912
 
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
913
 
        return c
914
 
 
915
 
    def test_simple_read_access(self):
916
 
        self.assertEquals('1', self.config.get_user_option('one'))
917
 
 
918
 
    def test_simple_write_access(self):
919
 
        self.config.set_user_option('one', 'one')
920
 
        self.assertEquals('one', self.config.get_user_option('one'))
921
 
 
922
 
    def test_listen_to_the_last_speaker(self):
923
 
        c1 = self.config
924
 
        c2 = self.get_existing_config()
925
 
        c1.set_user_option('one', 'ONE')
926
 
        c2.set_user_option('two', 'TWO')
927
 
        self.assertEquals('ONE', c1.get_user_option('one'))
928
 
        self.assertEquals('TWO', c2.get_user_option('two'))
929
 
        # The second update respect the first one
930
 
        self.assertEquals('ONE', c2.get_user_option('one'))
931
 
 
932
 
    def test_last_speaker_wins(self):
933
 
        # If the same config is not shared, the same variable modified twice
934
 
        # can only see a single result.
935
 
        c1 = self.config
936
 
        c2 = self.get_existing_config()
937
 
        c1.set_user_option('one', 'c1')
938
 
        c2.set_user_option('one', 'c2')
939
 
        self.assertEquals('c2', c2._get_user_option('one'))
940
 
        # The first modification is still available until another refresh
941
 
        # occur
942
 
        self.assertEquals('c1', c1._get_user_option('one'))
943
 
        c1.set_user_option('two', 'done')
944
 
        self.assertEquals('c2', c1._get_user_option('one'))
945
 
 
946
 
    def test_writes_are_serialized(self):
947
 
        c1 = self.config
948
 
        c2 = self.get_existing_config()
949
 
 
950
 
        # We spawn a thread that will pause *during* the write
951
 
        before_writing = threading.Event()
952
 
        after_writing = threading.Event()
953
 
        writing_done = threading.Event()
954
 
        c1_orig = c1._write_config_file
955
 
        def c1_write_config_file():
956
 
            before_writing.set()
957
 
            c1_orig()
958
 
            # The lock is held. We wait for the main thread to decide when to
959
 
            # continue
960
 
            after_writing.wait()
961
 
        c1._write_config_file = c1_write_config_file
962
 
        def c1_set_option():
963
 
            c1.set_user_option('one', 'c1')
964
 
            writing_done.set()
965
 
        t1 = threading.Thread(target=c1_set_option)
966
 
        # Collect the thread after the test
967
 
        self.addCleanup(t1.join)
968
 
        # Be ready to unblock the thread if the test goes wrong
969
 
        self.addCleanup(after_writing.set)
970
 
        t1.start()
971
 
        before_writing.wait()
972
 
        self.assertTrue(c1._lock.is_held)
973
 
        self.assertRaises(errors.LockContention,
974
 
                          c2.set_user_option, 'one', 'c2')
975
 
        self.assertEquals('c1', c1.get_user_option('one'))
976
 
        # Let the lock be released
977
 
        after_writing.set()
978
 
        writing_done.wait()
979
 
        c2.set_user_option('one', 'c2')
980
 
        self.assertEquals('c2', c2.get_user_option('one'))
981
 
 
982
 
    def test_read_while_writing(self):
983
 
       c1 = self.config
984
 
       # We spawn a thread that will pause *during* the write
985
 
       ready_to_write = threading.Event()
986
 
       do_writing = threading.Event()
987
 
       writing_done = threading.Event()
988
 
       c1_orig = c1._write_config_file
989
 
       def c1_write_config_file():
990
 
           ready_to_write.set()
991
 
           # The lock is held. We wait for the main thread to decide when to
992
 
           # continue
993
 
           do_writing.wait()
994
 
           c1_orig()
995
 
           writing_done.set()
996
 
       c1._write_config_file = c1_write_config_file
997
 
       def c1_set_option():
998
 
           c1.set_user_option('one', 'c1')
999
 
       t1 = threading.Thread(target=c1_set_option)
1000
 
       # Collect the thread after the test
1001
 
       self.addCleanup(t1.join)
1002
 
       # Be ready to unblock the thread if the test goes wrong
1003
 
       self.addCleanup(do_writing.set)
1004
 
       t1.start()
1005
 
       # Ensure the thread is ready to write
1006
 
       ready_to_write.wait()
1007
 
       self.assertTrue(c1._lock.is_held)
1008
 
       self.assertEquals('c1', c1.get_user_option('one'))
1009
 
       # If we read during the write, we get the old value
1010
 
       c2 = self.get_existing_config()
1011
 
       self.assertEquals('1', c2.get_user_option('one'))
1012
 
       # Let the writing occur and ensure it occurred
1013
 
       do_writing.set()
1014
 
       writing_done.wait()
1015
 
       # Now we get the updated value
1016
 
       c3 = self.get_existing_config()
1017
 
       self.assertEquals('c1', c3.get_user_option('one'))
1018
 
 
1019
 
 
1020
 
class TestGetUserOptionAs(TestIniConfig):
1021
 
 
1022
 
    def test_get_user_option_as_bool(self):
1023
 
        conf, parser = self.make_config_parser("""
1024
 
a_true_bool = true
1025
 
a_false_bool = 0
1026
 
an_invalid_bool = maybe
1027
 
a_list = hmm, who knows ? # This is interpreted as a list !
1028
 
""")
1029
 
        get_bool = conf.get_user_option_as_bool
1030
 
        self.assertEqual(True, get_bool('a_true_bool'))
1031
 
        self.assertEqual(False, get_bool('a_false_bool'))
1032
 
        warnings = []
1033
 
        def warning(*args):
1034
 
            warnings.append(args[0] % args[1:])
1035
 
        self.overrideAttr(trace, 'warning', warning)
1036
 
        msg = 'Value "%s" is not a boolean for "%s"'
1037
 
        self.assertIs(None, get_bool('an_invalid_bool'))
1038
 
        self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
1039
 
        warnings = []
1040
 
        self.assertIs(None, get_bool('not_defined_in_this_config'))
1041
 
        self.assertEquals([], warnings)
1042
 
 
1043
 
    def test_get_user_option_as_list(self):
1044
 
        conf, parser = self.make_config_parser("""
1045
 
a_list = a,b,c
1046
 
length_1 = 1,
1047
 
one_item = x
1048
 
""")
1049
 
        get_list = conf.get_user_option_as_list
1050
 
        self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
1051
 
        self.assertEqual(['1'], get_list('length_1'))
1052
 
        self.assertEqual('x', conf.get_user_option('one_item'))
1053
 
        # automatically cast to list
1054
 
        self.assertEqual(['x'], get_list('one_item'))
1055
 
 
1056
 
    def test_get_user_option_as_int_from_SI(self):
1057
 
        conf, parser = self.make_config_parser("""
1058
 
plain = 100
1059
 
si_k = 5k,
1060
 
si_kb = 5kb,
1061
 
si_m = 5M,
1062
 
si_mb = 5MB,
1063
 
si_g = 5g,
1064
 
si_gb = 5gB,
1065
 
""")
1066
 
        get_si = conf.get_user_option_as_int_from_SI
1067
 
        self.assertEqual(100, get_si('plain'))
1068
 
        self.assertEqual(5000, get_si('si_k'))
1069
 
        self.assertEqual(5000, get_si('si_kb'))
1070
 
        self.assertEqual(5000000, get_si('si_m'))
1071
 
        self.assertEqual(5000000, get_si('si_mb'))
1072
 
        self.assertEqual(5000000000, get_si('si_g'))
1073
 
        self.assertEqual(5000000000, get_si('si_gb'))
1074
 
        self.assertEqual(None, get_si('non-exist'))
1075
 
        self.assertEqual(42, get_si('non-exist-with-default',  42))
1076
 
 
1077
 
class TestSupressWarning(TestIniConfig):
1078
 
 
1079
 
    def make_warnings_config(self, s):
1080
 
        conf, parser = self.make_config_parser(s)
1081
 
        return conf.suppress_warning
1082
 
 
1083
 
    def test_suppress_warning_unknown(self):
1084
 
        suppress_warning = self.make_warnings_config('')
1085
 
        self.assertEqual(False, suppress_warning('unknown_warning'))
1086
 
 
1087
 
    def test_suppress_warning_known(self):
1088
 
        suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
1089
 
        self.assertEqual(False, suppress_warning('c'))
1090
 
        self.assertEqual(True, suppress_warning('a'))
1091
 
        self.assertEqual(True, suppress_warning('b'))
1092
 
 
1093
 
 
1094
 
class TestGetConfig(tests.TestCase):
 
264
        config_file = StringIO(sample_config_text)
 
265
        my_config = config.IniBasedConfig(None)
 
266
        parser = my_config._get_parser(file=config_file)
 
267
        self.failUnless(my_config._get_parser() is parser)
 
268
 
 
269
 
 
270
class TestGetConfig(TestCase):
1095
271
 
1096
272
    def test_constructs(self):
1097
273
        my_config = config.GlobalConfig()
1098
274
 
1099
275
    def test_calls_read_filenames(self):
1100
 
        # replace the class that is constructed, to check its parameters
 
276
        # replace the class that is constructured, to check its parameters
1101
277
        oldparserclass = config.ConfigObj
1102
278
        config.ConfigObj = InstrumentedConfigObj
1103
279
        my_config = config.GlobalConfig()
1105
281
            parser = my_config._get_parser()
1106
282
        finally:
1107
283
            config.ConfigObj = oldparserclass
1108
 
        self.assertIsInstance(parser, InstrumentedConfigObj)
1109
 
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
1110
 
                                          'utf-8')])
1111
 
 
1112
 
 
1113
 
class TestBranchConfig(tests.TestCaseWithTransport):
 
284
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
285
        self.assertEqual(parser._calls, [('__init__', config.config_filename())])
 
286
 
 
287
 
 
288
class TestBranchConfig(TestCaseInTempDir):
1114
289
 
1115
290
    def test_constructs(self):
1116
291
        branch = FakeBranch()
1122
297
        my_config = config.BranchConfig(branch)
1123
298
        location_config = my_config._get_location_config()
1124
299
        self.assertEqual(branch.base, location_config.location)
1125
 
        self.assertIs(location_config, my_config._get_location_config())
1126
 
 
1127
 
    def test_get_config(self):
1128
 
        """The Branch.get_config method works properly"""
1129
 
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
1130
 
        my_config = b.get_config()
1131
 
        self.assertIs(my_config.get_user_option('wacky'), None)
1132
 
        my_config.set_user_option('wacky', 'unlikely')
1133
 
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
1134
 
 
1135
 
        # Ensure we get the same thing if we start again
1136
 
        b2 = branch.Branch.open('.')
1137
 
        my_config2 = b2.get_config()
1138
 
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
1139
 
 
1140
 
    def test_has_explicit_nickname(self):
1141
 
        b = self.make_branch('.')
1142
 
        self.assertFalse(b.get_config().has_explicit_nickname())
1143
 
        b.nick = 'foo'
1144
 
        self.assertTrue(b.get_config().has_explicit_nickname())
1145
 
 
1146
 
    def test_config_url(self):
1147
 
        """The Branch.get_config will use section that uses a local url"""
1148
 
        branch = self.make_branch('branch')
1149
 
        self.assertEqual('branch', branch.nick)
1150
 
 
1151
 
        local_url = urlutils.local_path_to_url('branch')
1152
 
        conf = config.LocationConfig.from_string(
1153
 
            '[%s]\nnickname = foobar' % (local_url,),
1154
 
            local_url, save=True)
1155
 
        self.assertEqual('foobar', branch.nick)
1156
 
 
1157
 
    def test_config_local_path(self):
1158
 
        """The Branch.get_config will use a local system path"""
1159
 
        branch = self.make_branch('branch')
1160
 
        self.assertEqual('branch', branch.nick)
1161
 
 
1162
 
        local_path = osutils.getcwd().encode('utf8')
1163
 
        conf = config.LocationConfig.from_string(
1164
 
            '[%s/branch]\nnickname = barry' % (local_path,),
1165
 
            'branch',  save=True)
1166
 
        self.assertEqual('barry', branch.nick)
1167
 
 
1168
 
    def test_config_creates_local(self):
1169
 
        """Creating a new entry in config uses a local path."""
1170
 
        branch = self.make_branch('branch', format='knit')
1171
 
        branch.set_push_location('http://foobar')
1172
 
        local_path = osutils.getcwd().encode('utf8')
1173
 
        # Surprisingly ConfigObj doesn't create a trailing newline
1174
 
        self.check_file_contents(config.locations_config_filename(),
1175
 
                                 '[%s/branch]\n'
1176
 
                                 'push_location = http://foobar\n'
1177
 
                                 'push_location:policy = norecurse\n'
1178
 
                                 % (local_path,))
1179
 
 
1180
 
    def test_autonick_urlencoded(self):
1181
 
        b = self.make_branch('!repo')
1182
 
        self.assertEqual('!repo', b.get_config().get_nickname())
1183
 
 
1184
 
    def test_warn_if_masked(self):
1185
 
        warnings = []
1186
 
        def warning(*args):
1187
 
            warnings.append(args[0] % args[1:])
1188
 
        self.overrideAttr(trace, 'warning', warning)
1189
 
 
1190
 
        def set_option(store, warn_masked=True):
1191
 
            warnings[:] = []
1192
 
            conf.set_user_option('example_option', repr(store), store=store,
1193
 
                                 warn_masked=warn_masked)
1194
 
        def assertWarning(warning):
1195
 
            if warning is None:
1196
 
                self.assertEqual(0, len(warnings))
1197
 
            else:
1198
 
                self.assertEqual(1, len(warnings))
1199
 
                self.assertEqual(warning, warnings[0])
1200
 
        branch = self.make_branch('.')
1201
 
        conf = branch.get_config()
1202
 
        set_option(config.STORE_GLOBAL)
1203
 
        assertWarning(None)
1204
 
        set_option(config.STORE_BRANCH)
1205
 
        assertWarning(None)
1206
 
        set_option(config.STORE_GLOBAL)
1207
 
        assertWarning('Value "4" is masked by "3" from branch.conf')
1208
 
        set_option(config.STORE_GLOBAL, warn_masked=False)
1209
 
        assertWarning(None)
1210
 
        set_option(config.STORE_LOCATION)
1211
 
        assertWarning(None)
1212
 
        set_option(config.STORE_BRANCH)
1213
 
        assertWarning('Value "3" is masked by "0" from locations.conf')
1214
 
        set_option(config.STORE_BRANCH, warn_masked=False)
1215
 
        assertWarning(None)
1216
 
 
1217
 
 
1218
 
class TestGlobalConfigItems(tests.TestCaseInTempDir):
 
300
        self.failUnless(location_config is my_config._get_location_config())
 
301
 
 
302
 
 
303
class TestGlobalConfigItems(TestCase):
1219
304
 
1220
305
    def test_user_id(self):
1221
 
        my_config = config.GlobalConfig.from_string(sample_config_text)
1222
 
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
 
306
        config_file = StringIO(sample_config_text)
 
307
        my_config = config.GlobalConfig()
 
308
        my_config._parser = my_config._get_parser(file=config_file)
 
309
        self.assertEqual("Robert Collins <robertc@example.com>",
1223
310
                         my_config._get_user_id())
1224
311
 
1225
312
    def test_absent_user_id(self):
 
313
        config_file = StringIO("")
1226
314
        my_config = config.GlobalConfig()
 
315
        my_config._parser = my_config._get_parser(file=config_file)
1227
316
        self.assertEqual(None, my_config._get_user_id())
1228
317
 
1229
318
    def test_configured_editor(self):
1230
 
        my_config = config.GlobalConfig.from_string(sample_config_text)
1231
 
        editor = self.applyDeprecated(
1232
 
            deprecated_in((2, 4, 0)), my_config.get_editor)
1233
 
        self.assertEqual('vim', editor)
 
319
        config_file = StringIO(sample_config_text)
 
320
        my_config = config.GlobalConfig()
 
321
        my_config._parser = my_config._get_parser(file=config_file)
 
322
        self.assertEqual("vim", my_config.get_editor())
1234
323
 
1235
324
    def test_signatures_always(self):
1236
 
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
1237
 
        self.assertEqual(config.CHECK_NEVER,
 
325
        config_file = StringIO(sample_always_signatures)
 
326
        my_config = config.GlobalConfig()
 
327
        my_config._parser = my_config._get_parser(file=config_file)
 
328
        self.assertEqual(config.CHECK_ALWAYS,
1238
329
                         my_config.signature_checking())
1239
 
        self.assertEqual(config.SIGN_ALWAYS,
1240
 
                         my_config.signing_policy())
1241
330
        self.assertEqual(True, my_config.signature_needed())
1242
331
 
1243
332
    def test_signatures_if_possible(self):
1244
 
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
1245
 
        self.assertEqual(config.CHECK_NEVER,
 
333
        config_file = StringIO(sample_maybe_signatures)
 
334
        my_config = config.GlobalConfig()
 
335
        my_config._parser = my_config._get_parser(file=config_file)
 
336
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1246
337
                         my_config.signature_checking())
1247
 
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
1248
 
                         my_config.signing_policy())
1249
338
        self.assertEqual(False, my_config.signature_needed())
1250
339
 
1251
340
    def test_signatures_ignore(self):
1252
 
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
1253
 
        self.assertEqual(config.CHECK_ALWAYS,
 
341
        config_file = StringIO(sample_ignore_signatures)
 
342
        my_config = config.GlobalConfig()
 
343
        my_config._parser = my_config._get_parser(file=config_file)
 
344
        self.assertEqual(config.CHECK_NEVER,
1254
345
                         my_config.signature_checking())
1255
 
        self.assertEqual(config.SIGN_NEVER,
1256
 
                         my_config.signing_policy())
1257
346
        self.assertEqual(False, my_config.signature_needed())
1258
347
 
1259
348
    def _get_sample_config(self):
1260
 
        my_config = config.GlobalConfig.from_string(sample_config_text)
 
349
        config_file = StringIO(sample_config_text)
 
350
        my_config = config.GlobalConfig()
 
351
        my_config._parser = my_config._get_parser(file=config_file)
1261
352
        return my_config
1262
353
 
1263
354
    def test_gpg_signing_command(self):
1265
356
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
1266
357
        self.assertEqual(False, my_config.signature_needed())
1267
358
 
1268
 
    def test_gpg_signing_key(self):
1269
 
        my_config = self._get_sample_config()
1270
 
        self.assertEqual("DD4D5088", my_config.gpg_signing_key())
1271
 
 
1272
359
    def _get_empty_config(self):
 
360
        config_file = StringIO("")
1273
361
        my_config = config.GlobalConfig()
 
362
        my_config._parser = my_config._get_parser(file=config_file)
1274
363
        return my_config
1275
364
 
1276
365
    def test_gpg_signing_command_unset(self):
1285
374
        my_config = self._get_sample_config()
1286
375
        self.assertEqual("something",
1287
376
                         my_config.get_user_option('user_global_option'))
1288
 
 
 
377
        
1289
378
    def test_post_commit_default(self):
1290
379
        my_config = self._get_sample_config()
1291
380
        self.assertEqual(None, my_config.post_commit())
1294
383
        my_config = self._get_sample_config()
1295
384
        self.assertEqual("short", my_config.log_format())
1296
385
 
1297
 
    def test_configured_acceptable_keys(self):
1298
 
        my_config = self._get_sample_config()
1299
 
        self.assertEqual("amy", my_config.acceptable_keys())
1300
 
 
1301
 
    def test_configured_validate_signatures_in_log(self):
1302
 
        my_config = self._get_sample_config()
1303
 
        self.assertEqual(True, my_config.validate_signatures_in_log())
1304
 
 
1305
386
    def test_get_alias(self):
1306
387
        my_config = self._get_sample_config()
1307
388
        self.assertEqual('help', my_config.get_alias('h'))
1308
389
 
1309
 
    def test_get_aliases(self):
1310
 
        my_config = self._get_sample_config()
1311
 
        aliases = my_config.get_aliases()
1312
 
        self.assertEqual(2, len(aliases))
1313
 
        sorted_keys = sorted(aliases)
1314
 
        self.assertEqual('help', aliases[sorted_keys[0]])
1315
 
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
1316
 
 
1317
390
    def test_get_no_alias(self):
1318
391
        my_config = self._get_sample_config()
1319
392
        self.assertEqual(None, my_config.get_alias('foo'))
1322
395
        my_config = self._get_sample_config()
1323
396
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
1324
397
 
1325
 
    def test_get_change_editor(self):
1326
 
        my_config = self._get_sample_config()
1327
 
        change_editor = my_config.get_change_editor('old', 'new')
1328
 
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
1329
 
        self.assertEqual('vimdiff -of @new_path @old_path',
1330
 
                         ' '.join(change_editor.command_template))
1331
 
 
1332
 
    def test_get_no_change_editor(self):
1333
 
        my_config = self._get_empty_config()
1334
 
        change_editor = my_config.get_change_editor('old', 'new')
1335
 
        self.assertIs(None, change_editor)
1336
 
 
1337
 
    def test_get_merge_tools(self):
1338
 
        conf = self._get_sample_config()
1339
 
        tools = conf.get_merge_tools()
1340
 
        self.log(repr(tools))
1341
 
        self.assertEqual(
1342
 
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
1343
 
            u'sometool' : u'sometool {base} {this} {other} -o {result}',
1344
 
            u'newtool' : u'"newtool with spaces" {this_temp}'},
1345
 
            tools)
1346
 
 
1347
 
    def test_get_merge_tools_empty(self):
1348
 
        conf = self._get_empty_config()
1349
 
        tools = conf.get_merge_tools()
1350
 
        self.assertEqual({}, tools)
1351
 
 
1352
 
    def test_find_merge_tool(self):
1353
 
        conf = self._get_sample_config()
1354
 
        cmdline = conf.find_merge_tool('sometool')
1355
 
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
1356
 
 
1357
 
    def test_find_merge_tool_not_found(self):
1358
 
        conf = self._get_sample_config()
1359
 
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
1360
 
        self.assertIs(cmdline, None)
1361
 
 
1362
 
    def test_find_merge_tool_known(self):
1363
 
        conf = self._get_empty_config()
1364
 
        cmdline = conf.find_merge_tool('kdiff3')
1365
 
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
1366
 
 
1367
 
    def test_find_merge_tool_override_known(self):
1368
 
        conf = self._get_empty_config()
1369
 
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
1370
 
        cmdline = conf.find_merge_tool('kdiff3')
1371
 
        self.assertEqual('kdiff3 blah', cmdline)
1372
 
 
1373
 
 
1374
 
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
1375
 
 
1376
 
    def test_empty(self):
1377
 
        my_config = config.GlobalConfig()
1378
 
        self.assertEqual(0, len(my_config.get_aliases()))
1379
 
 
1380
 
    def test_set_alias(self):
1381
 
        my_config = config.GlobalConfig()
1382
 
        alias_value = 'commit --strict'
1383
 
        my_config.set_alias('commit', alias_value)
1384
 
        new_config = config.GlobalConfig()
1385
 
        self.assertEqual(alias_value, new_config.get_alias('commit'))
1386
 
 
1387
 
    def test_remove_alias(self):
1388
 
        my_config = config.GlobalConfig()
1389
 
        my_config.set_alias('commit', 'commit --strict')
1390
 
        # Now remove the alias again.
1391
 
        my_config.unset_alias('commit')
1392
 
        new_config = config.GlobalConfig()
1393
 
        self.assertIs(None, new_config.get_alias('commit'))
1394
 
 
1395
 
 
1396
 
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
 
398
class TestLocationConfig(TestCase):
1397
399
 
1398
400
    def test_constructs(self):
1399
401
        my_config = config.LocationConfig('http://example.com')
1403
405
        # This is testing the correct file names are provided.
1404
406
        # TODO: consolidate with the test for GlobalConfigs filename checks.
1405
407
        #
1406
 
        # replace the class that is constructed, to check its parameters
 
408
        # replace the class that is constructured, to check its parameters
1407
409
        oldparserclass = config.ConfigObj
1408
410
        config.ConfigObj = InstrumentedConfigObj
 
411
        my_config = config.LocationConfig('http://www.example.com')
1409
412
        try:
1410
 
            my_config = config.LocationConfig('http://www.example.com')
1411
413
            parser = my_config._get_parser()
1412
414
        finally:
1413
415
            config.ConfigObj = oldparserclass
1414
 
        self.assertIsInstance(parser, InstrumentedConfigObj)
 
416
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1415
417
        self.assertEqual(parser._calls,
1416
 
                         [('__init__', config.locations_config_filename(),
1417
 
                           'utf-8')])
 
418
                         [('__init__', config.branches_config_filename())])
1418
419
 
1419
420
    def test_get_global_config(self):
1420
 
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
 
421
        my_config = config.LocationConfig('http://example.com')
1421
422
        global_config = my_config._get_global_config()
1422
 
        self.assertIsInstance(global_config, config.GlobalConfig)
1423
 
        self.assertIs(global_config, my_config._get_global_config())
1424
 
 
1425
 
    def assertLocationMatching(self, expected):
1426
 
        self.assertEqual(expected,
1427
 
                         list(self.my_location_config._get_matching_sections()))
1428
 
 
1429
 
    def test__get_matching_sections_no_match(self):
1430
 
        self.get_branch_config('/')
1431
 
        self.assertLocationMatching([])
1432
 
 
1433
 
    def test__get_matching_sections_exact(self):
1434
 
        self.get_branch_config('http://www.example.com')
1435
 
        self.assertLocationMatching([('http://www.example.com', '')])
1436
 
 
1437
 
    def test__get_matching_sections_suffix_does_not(self):
1438
 
        self.get_branch_config('http://www.example.com-com')
1439
 
        self.assertLocationMatching([])
1440
 
 
1441
 
    def test__get_matching_sections_subdir_recursive(self):
1442
 
        self.get_branch_config('http://www.example.com/com')
1443
 
        self.assertLocationMatching([('http://www.example.com', 'com')])
1444
 
 
1445
 
    def test__get_matching_sections_ignoreparent(self):
1446
 
        self.get_branch_config('http://www.example.com/ignoreparent')
1447
 
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1448
 
                                      '')])
1449
 
 
1450
 
    def test__get_matching_sections_ignoreparent_subdir(self):
1451
 
        self.get_branch_config(
1452
 
            'http://www.example.com/ignoreparent/childbranch')
1453
 
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1454
 
                                      'childbranch')])
1455
 
 
1456
 
    def test__get_matching_sections_subdir_trailing_slash(self):
1457
 
        self.get_branch_config('/b')
1458
 
        self.assertLocationMatching([('/b/', '')])
1459
 
 
1460
 
    def test__get_matching_sections_subdir_child(self):
1461
 
        self.get_branch_config('/a/foo')
1462
 
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
1463
 
 
1464
 
    def test__get_matching_sections_subdir_child_child(self):
1465
 
        self.get_branch_config('/a/foo/bar')
1466
 
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
1467
 
 
1468
 
    def test__get_matching_sections_trailing_slash_with_children(self):
1469
 
        self.get_branch_config('/a/')
1470
 
        self.assertLocationMatching([('/a/', '')])
1471
 
 
1472
 
    def test__get_matching_sections_explicit_over_glob(self):
1473
 
        # XXX: 2006-09-08 jamesh
1474
 
        # This test only passes because ord('c') > ord('*').  If there
1475
 
        # was a config section for '/a/?', it would get precedence
1476
 
        # over '/a/c'.
1477
 
        self.get_branch_config('/a/c')
1478
 
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
1479
 
 
1480
 
    def test__get_option_policy_normal(self):
1481
 
        self.get_branch_config('http://www.example.com')
1482
 
        self.assertEqual(
1483
 
            self.my_location_config._get_config_policy(
1484
 
            'http://www.example.com', 'normal_option'),
1485
 
            config.POLICY_NONE)
1486
 
 
1487
 
    def test__get_option_policy_norecurse(self):
1488
 
        self.get_branch_config('http://www.example.com')
1489
 
        self.assertEqual(
1490
 
            self.my_location_config._get_option_policy(
1491
 
            'http://www.example.com', 'norecurse_option'),
1492
 
            config.POLICY_NORECURSE)
1493
 
        # Test old recurse=False setting:
1494
 
        self.assertEqual(
1495
 
            self.my_location_config._get_option_policy(
1496
 
            'http://www.example.com/norecurse', 'normal_option'),
1497
 
            config.POLICY_NORECURSE)
1498
 
 
1499
 
    def test__get_option_policy_normal(self):
1500
 
        self.get_branch_config('http://www.example.com')
1501
 
        self.assertEqual(
1502
 
            self.my_location_config._get_option_policy(
1503
 
            'http://www.example.com', 'appendpath_option'),
1504
 
            config.POLICY_APPENDPATH)
1505
 
 
1506
 
    def test__get_options_with_policy(self):
1507
 
        self.get_branch_config('/dir/subdir',
1508
 
                               location_config="""\
1509
 
[/dir]
1510
 
other_url = /other-dir
1511
 
other_url:policy = appendpath
1512
 
[/dir/subdir]
1513
 
other_url = /other-subdir
1514
 
""")
1515
 
        self.assertOptions(
1516
 
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
1517
 
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
1518
 
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
1519
 
            self.my_location_config)
 
423
        self.failUnless(isinstance(global_config, config.GlobalConfig))
 
424
        self.failUnless(global_config is my_config._get_global_config())
 
425
 
 
426
    def test__get_section_no_match(self):
 
427
        self.get_location_config('/')
 
428
        self.assertEqual(None, self.my_config._get_section())
 
429
        
 
430
    def test__get_section_exact(self):
 
431
        self.get_location_config('http://www.example.com')
 
432
        self.assertEqual('http://www.example.com',
 
433
                         self.my_config._get_section())
 
434
   
 
435
    def test__get_section_suffix_does_not(self):
 
436
        self.get_location_config('http://www.example.com-com')
 
437
        self.assertEqual(None, self.my_config._get_section())
 
438
 
 
439
    def test__get_section_subdir_recursive(self):
 
440
        self.get_location_config('http://www.example.com/com')
 
441
        self.assertEqual('http://www.example.com',
 
442
                         self.my_config._get_section())
 
443
 
 
444
    def test__get_section_subdir_matches(self):
 
445
        self.get_location_config('http://www.example.com/useglobal')
 
446
        self.assertEqual('http://www.example.com/useglobal',
 
447
                         self.my_config._get_section())
 
448
 
 
449
    def test__get_section_subdir_nonrecursive(self):
 
450
        self.get_location_config(
 
451
            'http://www.example.com/useglobal/childbranch')
 
452
        self.assertEqual('http://www.example.com',
 
453
                         self.my_config._get_section())
 
454
 
 
455
    def test__get_section_subdir_trailing_slash(self):
 
456
        self.get_location_config('/b')
 
457
        self.assertEqual('/b/', self.my_config._get_section())
 
458
 
 
459
    def test__get_section_subdir_child(self):
 
460
        self.get_location_config('/a/foo')
 
461
        self.assertEqual('/a/*', self.my_config._get_section())
 
462
 
 
463
    def test__get_section_subdir_child_child(self):
 
464
        self.get_location_config('/a/foo/bar')
 
465
        self.assertEqual('/a/', self.my_config._get_section())
 
466
 
 
467
    def test__get_section_trailing_slash_with_children(self):
 
468
        self.get_location_config('/a/')
 
469
        self.assertEqual('/a/', self.my_config._get_section())
 
470
 
 
471
    def test__get_section_explicit_over_glob(self):
 
472
        self.get_location_config('/a/c')
 
473
        self.assertEqual('/a/c', self.my_config._get_section())
 
474
 
 
475
    def get_location_config(self, location, global_config=None):
 
476
        if global_config is None:
 
477
            global_file = StringIO(sample_config_text)
 
478
        else:
 
479
            global_file = StringIO(global_config)
 
480
        branches_file = StringIO(sample_branches_text)
 
481
        self.my_config = config.LocationConfig(location)
 
482
        self.my_config._get_parser(branches_file)
 
483
        self.my_config._get_global_config()._get_parser(global_file)
1520
484
 
1521
485
    def test_location_without_username(self):
1522
 
        self.get_branch_config('http://www.example.com/ignoreparent')
1523
 
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
 
486
        self.get_location_config('http://www.example.com/useglobal')
 
487
        self.assertEqual('Robert Collins <robertc@example.com>',
1524
488
                         self.my_config.username())
1525
489
 
1526
490
    def test_location_not_listed(self):
1527
 
        """Test that the global username is used when no location matches"""
1528
 
        self.get_branch_config('/home/robertc/sources')
1529
 
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
 
491
        self.get_location_config('/home/robertc/sources')
 
492
        self.assertEqual('Robert Collins <robertc@example.com>',
1530
493
                         self.my_config.username())
1531
494
 
1532
495
    def test_overriding_location(self):
1533
 
        self.get_branch_config('http://www.example.com/foo')
 
496
        self.get_location_config('http://www.example.com/foo')
1534
497
        self.assertEqual('Robert Collins <robertc@example.org>',
1535
498
                         self.my_config.username())
1536
499
 
1537
500
    def test_signatures_not_set(self):
1538
 
        self.get_branch_config('http://www.example.com',
 
501
        self.get_location_config('http://www.example.com',
1539
502
                                 global_config=sample_ignore_signatures)
1540
 
        self.assertEqual(config.CHECK_ALWAYS,
 
503
        self.assertEqual(config.CHECK_NEVER,
1541
504
                         self.my_config.signature_checking())
1542
 
        self.assertEqual(config.SIGN_NEVER,
1543
 
                         self.my_config.signing_policy())
1544
505
 
1545
506
    def test_signatures_never(self):
1546
 
        self.get_branch_config('/a/c')
 
507
        self.get_location_config('/a/c')
1547
508
        self.assertEqual(config.CHECK_NEVER,
1548
509
                         self.my_config.signature_checking())
1549
 
 
 
510
        
1550
511
    def test_signatures_when_available(self):
1551
 
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
 
512
        self.get_location_config('/a/', global_config=sample_ignore_signatures)
1552
513
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1553
514
                         self.my_config.signature_checking())
1554
 
 
 
515
        
1555
516
    def test_signatures_always(self):
1556
 
        self.get_branch_config('/b')
 
517
        self.get_location_config('/b')
1557
518
        self.assertEqual(config.CHECK_ALWAYS,
1558
519
                         self.my_config.signature_checking())
1559
 
 
 
520
        
1560
521
    def test_gpg_signing_command(self):
1561
 
        self.get_branch_config('/b')
 
522
        self.get_location_config('/b')
1562
523
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
1563
524
 
1564
525
    def test_gpg_signing_command_missing(self):
1565
 
        self.get_branch_config('/a')
 
526
        self.get_location_config('/a')
1566
527
        self.assertEqual("false", self.my_config.gpg_signing_command())
1567
528
 
1568
 
    def test_gpg_signing_key(self):
1569
 
        self.get_branch_config('/b')
1570
 
        self.assertEqual("DD4D5088", self.my_config.gpg_signing_key())
1571
 
 
1572
 
    def test_gpg_signing_key_default(self):
1573
 
        self.get_branch_config('/a')
1574
 
        self.assertEqual("erik@bagfors.nu", self.my_config.gpg_signing_key())
1575
 
 
1576
529
    def test_get_user_option_global(self):
1577
 
        self.get_branch_config('/a')
 
530
        self.get_location_config('/a')
1578
531
        self.assertEqual('something',
1579
532
                         self.my_config.get_user_option('user_global_option'))
1580
533
 
1581
534
    def test_get_user_option_local(self):
1582
 
        self.get_branch_config('/a')
 
535
        self.get_location_config('/a')
1583
536
        self.assertEqual('local',
1584
537
                         self.my_config.get_user_option('user_local_option'))
1585
 
 
1586
 
    def test_get_user_option_appendpath(self):
1587
 
        # returned as is for the base path:
1588
 
        self.get_branch_config('http://www.example.com')
1589
 
        self.assertEqual('append',
1590
 
                         self.my_config.get_user_option('appendpath_option'))
1591
 
        # Extra path components get appended:
1592
 
        self.get_branch_config('http://www.example.com/a/b/c')
1593
 
        self.assertEqual('append/a/b/c',
1594
 
                         self.my_config.get_user_option('appendpath_option'))
1595
 
        # Overriden for http://www.example.com/dir, where it is a
1596
 
        # normal option:
1597
 
        self.get_branch_config('http://www.example.com/dir/a/b/c')
1598
 
        self.assertEqual('normal',
1599
 
                         self.my_config.get_user_option('appendpath_option'))
1600
 
 
1601
 
    def test_get_user_option_norecurse(self):
1602
 
        self.get_branch_config('http://www.example.com')
1603
 
        self.assertEqual('norecurse',
1604
 
                         self.my_config.get_user_option('norecurse_option'))
1605
 
        self.get_branch_config('http://www.example.com/dir')
1606
 
        self.assertEqual(None,
1607
 
                         self.my_config.get_user_option('norecurse_option'))
1608
 
        # http://www.example.com/norecurse is a recurse=False section
1609
 
        # that redefines normal_option.  Subdirectories do not pick up
1610
 
        # this redefinition.
1611
 
        self.get_branch_config('http://www.example.com/norecurse')
1612
 
        self.assertEqual('norecurse',
1613
 
                         self.my_config.get_user_option('normal_option'))
1614
 
        self.get_branch_config('http://www.example.com/norecurse/subdir')
1615
 
        self.assertEqual('normal',
1616
 
                         self.my_config.get_user_option('normal_option'))
1617
 
 
1618
 
    def test_set_user_option_norecurse(self):
1619
 
        self.get_branch_config('http://www.example.com')
1620
 
        self.my_config.set_user_option('foo', 'bar',
1621
 
                                       store=config.STORE_LOCATION_NORECURSE)
1622
 
        self.assertEqual(
1623
 
            self.my_location_config._get_option_policy(
1624
 
            'http://www.example.com', 'foo'),
1625
 
            config.POLICY_NORECURSE)
1626
 
 
1627
 
    def test_set_user_option_appendpath(self):
1628
 
        self.get_branch_config('http://www.example.com')
1629
 
        self.my_config.set_user_option('foo', 'bar',
1630
 
                                       store=config.STORE_LOCATION_APPENDPATH)
1631
 
        self.assertEqual(
1632
 
            self.my_location_config._get_option_policy(
1633
 
            'http://www.example.com', 'foo'),
1634
 
            config.POLICY_APPENDPATH)
1635
 
 
1636
 
    def test_set_user_option_change_policy(self):
1637
 
        self.get_branch_config('http://www.example.com')
1638
 
        self.my_config.set_user_option('norecurse_option', 'normal',
1639
 
                                       store=config.STORE_LOCATION)
1640
 
        self.assertEqual(
1641
 
            self.my_location_config._get_option_policy(
1642
 
            'http://www.example.com', 'norecurse_option'),
1643
 
            config.POLICY_NONE)
1644
 
 
1645
 
    def test_set_user_option_recurse_false_section(self):
1646
 
        # The following section has recurse=False set.  The test is to
1647
 
        # make sure that a normal option can be added to the section,
1648
 
        # converting recurse=False to the norecurse policy.
1649
 
        self.get_branch_config('http://www.example.com/norecurse')
1650
 
        self.callDeprecated(['The recurse option is deprecated as of 0.14.  '
1651
 
                             'The section "http://www.example.com/norecurse" '
1652
 
                             'has been converted to use policies.'],
1653
 
                            self.my_config.set_user_option,
1654
 
                            'foo', 'bar', store=config.STORE_LOCATION)
1655
 
        self.assertEqual(
1656
 
            self.my_location_config._get_option_policy(
1657
 
            'http://www.example.com/norecurse', 'foo'),
1658
 
            config.POLICY_NONE)
1659
 
        # The previously existing option is still norecurse:
1660
 
        self.assertEqual(
1661
 
            self.my_location_config._get_option_policy(
1662
 
            'http://www.example.com/norecurse', 'normal_option'),
1663
 
            config.POLICY_NORECURSE)
1664
 
 
 
538
        
1665
539
    def test_post_commit_default(self):
1666
 
        self.get_branch_config('/a/c')
 
540
        self.get_location_config('/a/c')
1667
541
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1668
542
                         self.my_config.post_commit())
1669
543
 
1670
 
    def get_branch_config(self, location, global_config=None,
1671
 
                          location_config=None):
1672
 
        my_branch = FakeBranch(location)
 
544
 
 
545
class TestLocationConfig(TestCaseInTempDir):
 
546
 
 
547
    def get_location_config(self, location, global_config=None):
1673
548
        if global_config is None:
1674
 
            global_config = sample_config_text
1675
 
        if location_config is None:
1676
 
            location_config = sample_branches_text
1677
 
 
1678
 
        my_global_config = config.GlobalConfig.from_string(global_config,
1679
 
                                                           save=True)
1680
 
        my_location_config = config.LocationConfig.from_string(
1681
 
            location_config, my_branch.base, save=True)
1682
 
        my_config = config.BranchConfig(my_branch)
1683
 
        self.my_config = my_config
1684
 
        self.my_location_config = my_config._get_location_config()
 
549
            global_file = StringIO(sample_config_text)
 
550
        else:
 
551
            global_file = StringIO(global_config)
 
552
        branches_file = StringIO(sample_branches_text)
 
553
        self.my_config = config.LocationConfig(location)
 
554
        self.my_config._get_parser(branches_file)
 
555
        self.my_config._get_global_config()._get_parser(global_file)
1685
556
 
1686
557
    def test_set_user_setting_sets_and_saves(self):
1687
 
        self.get_branch_config('/a/c')
 
558
        self.get_location_config('/a/c')
1688
559
        record = InstrumentedConfigObj("foo")
1689
 
        self.my_location_config._parser = record
1690
 
 
1691
 
        self.callDeprecated(['The recurse option is deprecated as of '
1692
 
                             '0.14.  The section "/a/c" has been '
1693
 
                             'converted to use policies.'],
1694
 
                            self.my_config.set_user_option,
1695
 
                            'foo', 'bar', store=config.STORE_LOCATION)
1696
 
        self.assertEqual([('reload',),
1697
 
                          ('__contains__', '/a/c'),
 
560
        self.my_config._parser = record
 
561
 
 
562
        real_mkdir = os.mkdir
 
563
        self.created = False
 
564
        def checked_mkdir(path, mode=0777):
 
565
            self.log('making directory: %s', path)
 
566
            real_mkdir(path, mode)
 
567
            self.created = True
 
568
 
 
569
        os.mkdir = checked_mkdir
 
570
        try:
 
571
            self.my_config.set_user_option('foo', 'bar')
 
572
        finally:
 
573
            os.mkdir = real_mkdir
 
574
 
 
575
        self.failUnless(self.created, 'Failed to create ~/.bazaar')
 
576
        self.assertEqual([('__contains__', '/a/c'),
1698
577
                          ('__contains__', '/a/c/'),
1699
578
                          ('__setitem__', '/a/c', {}),
1700
579
                          ('__getitem__', '/a/c'),
1701
580
                          ('__setitem__', 'foo', 'bar'),
1702
 
                          ('__getitem__', '/a/c'),
1703
 
                          ('as_bool', 'recurse'),
1704
 
                          ('__getitem__', '/a/c'),
1705
 
                          ('__delitem__', 'recurse'),
1706
 
                          ('__getitem__', '/a/c'),
1707
 
                          ('keys',),
1708
 
                          ('__getitem__', '/a/c'),
1709
 
                          ('__contains__', 'foo:policy'),
1710
581
                          ('write',)],
1711
582
                         record._calls[1:])
1712
583
 
1713
 
    def test_set_user_setting_sets_and_saves2(self):
1714
 
        self.get_branch_config('/a/c')
1715
 
        self.assertIs(self.my_config.get_user_option('foo'), None)
1716
 
        self.my_config.set_user_option('foo', 'bar')
1717
 
        self.assertEqual(
1718
 
            self.my_config.branch.control_files.files['branch.conf'].strip(),
1719
 
            'foo = bar')
1720
 
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
1721
 
        self.my_config.set_user_option('foo', 'baz',
1722
 
                                       store=config.STORE_LOCATION)
1723
 
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1724
 
        self.my_config.set_user_option('foo', 'qux')
1725
 
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1726
 
 
1727
 
    def test_get_bzr_remote_path(self):
1728
 
        my_config = config.LocationConfig('/a/c')
1729
 
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1730
 
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1731
 
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1732
 
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1733
 
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1734
 
 
1735
 
 
1736
 
precedence_global = 'option = global'
1737
 
precedence_branch = 'option = branch'
1738
 
precedence_location = """
1739
 
[http://]
1740
 
recurse = true
1741
 
option = recurse
1742
 
[http://example.com/specific]
1743
 
option = exact
1744
 
"""
1745
 
 
1746
 
class TestBranchConfigItems(tests.TestCaseInTempDir):
1747
 
 
1748
 
    def get_branch_config(self, global_config=None, location=None,
1749
 
                          location_config=None, branch_data_config=None):
1750
 
        my_branch = FakeBranch(location)
1751
 
        if global_config is not None:
1752
 
            my_global_config = config.GlobalConfig.from_string(global_config,
1753
 
                                                               save=True)
1754
 
        if location_config is not None:
1755
 
            my_location_config = config.LocationConfig.from_string(
1756
 
                location_config, my_branch.base, save=True)
1757
 
        my_config = config.BranchConfig(my_branch)
1758
 
        if branch_data_config is not None:
1759
 
            my_config.branch.control_files.files['branch.conf'] = \
1760
 
                branch_data_config
1761
 
        return my_config
 
584
 
 
585
class TestBranchConfigItems(TestCase):
1762
586
 
1763
587
    def test_user_id(self):
1764
 
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
 
588
        branch = FakeBranch()
1765
589
        my_config = config.BranchConfig(branch)
1766
590
        self.assertEqual("Robert Collins <robertc@example.net>",
1767
 
                         my_config.username())
1768
 
        my_config.branch.control_files.files['email'] = "John"
1769
 
        my_config.set_user_option('email',
1770
 
                                  "Robert Collins <robertc@example.org>")
1771
 
        self.assertEqual("John", my_config.username())
1772
 
        del my_config.branch.control_files.files['email']
1773
 
        self.assertEqual("Robert Collins <robertc@example.org>",
1774
 
                         my_config.username())
 
591
                         my_config._get_user_id())
 
592
        branch.control_files.email = "John"
 
593
        self.assertEqual("John", my_config._get_user_id())
1775
594
 
1776
595
    def test_not_set_in_branch(self):
1777
 
        my_config = self.get_branch_config(global_config=sample_config_text)
1778
 
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
 
596
        branch = FakeBranch()
 
597
        my_config = config.BranchConfig(branch)
 
598
        branch.control_files.email = None
 
599
        config_file = StringIO(sample_config_text)
 
600
        (my_config._get_location_config().
 
601
            _get_global_config()._get_parser(config_file))
 
602
        self.assertEqual("Robert Collins <robertc@example.com>",
1779
603
                         my_config._get_user_id())
1780
 
        my_config.branch.control_files.files['email'] = "John"
 
604
        branch.control_files.email = "John"
1781
605
        self.assertEqual("John", my_config._get_user_id())
1782
606
 
1783
 
    def test_BZR_EMAIL_OVERRIDES(self):
1784
 
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
 
607
    def test_BZREMAIL_OVERRIDES(self):
 
608
        os.environ['BZREMAIL'] = "Robert Collins <robertc@example.org>"
1785
609
        branch = FakeBranch()
1786
610
        my_config = config.BranchConfig(branch)
1787
611
        self.assertEqual("Robert Collins <robertc@example.org>",
1788
612
                         my_config.username())
1789
 
 
 
613
    
1790
614
    def test_signatures_forced(self):
1791
 
        my_config = self.get_branch_config(
1792
 
            global_config=sample_always_signatures)
1793
 
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1794
 
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1795
 
        self.assertTrue(my_config.signature_needed())
1796
 
 
1797
 
    def test_signatures_forced_branch(self):
1798
 
        my_config = self.get_branch_config(
1799
 
            global_config=sample_ignore_signatures,
1800
 
            branch_data_config=sample_always_signatures)
1801
 
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1802
 
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1803
 
        self.assertTrue(my_config.signature_needed())
 
615
        branch = FakeBranch()
 
616
        my_config = config.BranchConfig(branch)
 
617
        config_file = StringIO(sample_always_signatures)
 
618
        (my_config._get_location_config().
 
619
            _get_global_config()._get_parser(config_file))
 
620
        self.assertEqual(config.CHECK_ALWAYS, my_config.signature_checking())
1804
621
 
1805
622
    def test_gpg_signing_command(self):
1806
 
        my_config = self.get_branch_config(
1807
 
            global_config=sample_config_text,
1808
 
            # branch data cannot set gpg_signing_command
1809
 
            branch_data_config="gpg_signing_command=pgp")
 
623
        branch = FakeBranch()
 
624
        my_config = config.BranchConfig(branch)
 
625
        config_file = StringIO(sample_config_text)
 
626
        (my_config._get_location_config().
 
627
            _get_global_config()._get_parser(config_file))
1810
628
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1811
629
 
1812
630
    def test_get_user_option_global(self):
1813
 
        my_config = self.get_branch_config(global_config=sample_config_text)
 
631
        branch = FakeBranch()
 
632
        my_config = config.BranchConfig(branch)
 
633
        config_file = StringIO(sample_config_text)
 
634
        (my_config._get_location_config().
 
635
            _get_global_config()._get_parser(config_file))
1814
636
        self.assertEqual('something',
1815
637
                         my_config.get_user_option('user_global_option'))
1816
638
 
1817
639
    def test_post_commit_default(self):
1818
 
        my_config = self.get_branch_config(global_config=sample_config_text,
1819
 
                                      location='/a/c',
1820
 
                                      location_config=sample_branches_text)
1821
 
        self.assertEqual(my_config.branch.base, '/a/c')
1822
 
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1823
 
                         my_config.post_commit())
1824
 
        my_config.set_user_option('post_commit', 'rmtree_root')
1825
 
        # post-commit is ignored when present in branch data
1826
 
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1827
 
                         my_config.post_commit())
1828
 
        my_config.set_user_option('post_commit', 'rmtree_root',
1829
 
                                  store=config.STORE_LOCATION)
1830
 
        self.assertEqual('rmtree_root', my_config.post_commit())
1831
 
 
1832
 
    def test_config_precedence(self):
1833
 
        # FIXME: eager test, luckily no persitent config file makes it fail
1834
 
        # -- vila 20100716
1835
 
        my_config = self.get_branch_config(global_config=precedence_global)
1836
 
        self.assertEqual(my_config.get_user_option('option'), 'global')
1837
 
        my_config = self.get_branch_config(global_config=precedence_global,
1838
 
                                           branch_data_config=precedence_branch)
1839
 
        self.assertEqual(my_config.get_user_option('option'), 'branch')
1840
 
        my_config = self.get_branch_config(
1841
 
            global_config=precedence_global,
1842
 
            branch_data_config=precedence_branch,
1843
 
            location_config=precedence_location)
1844
 
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
1845
 
        my_config = self.get_branch_config(
1846
 
            global_config=precedence_global,
1847
 
            branch_data_config=precedence_branch,
1848
 
            location_config=precedence_location,
1849
 
            location='http://example.com/specific')
1850
 
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1851
 
 
1852
 
    def test_get_mail_client(self):
1853
 
        config = self.get_branch_config()
1854
 
        client = config.get_mail_client()
1855
 
        self.assertIsInstance(client, mail_client.DefaultMail)
1856
 
 
1857
 
        # Specific clients
1858
 
        config.set_user_option('mail_client', 'evolution')
1859
 
        client = config.get_mail_client()
1860
 
        self.assertIsInstance(client, mail_client.Evolution)
1861
 
 
1862
 
        config.set_user_option('mail_client', 'kmail')
1863
 
        client = config.get_mail_client()
1864
 
        self.assertIsInstance(client, mail_client.KMail)
1865
 
 
1866
 
        config.set_user_option('mail_client', 'mutt')
1867
 
        client = config.get_mail_client()
1868
 
        self.assertIsInstance(client, mail_client.Mutt)
1869
 
 
1870
 
        config.set_user_option('mail_client', 'thunderbird')
1871
 
        client = config.get_mail_client()
1872
 
        self.assertIsInstance(client, mail_client.Thunderbird)
1873
 
 
1874
 
        # Generic options
1875
 
        config.set_user_option('mail_client', 'default')
1876
 
        client = config.get_mail_client()
1877
 
        self.assertIsInstance(client, mail_client.DefaultMail)
1878
 
 
1879
 
        config.set_user_option('mail_client', 'editor')
1880
 
        client = config.get_mail_client()
1881
 
        self.assertIsInstance(client, mail_client.Editor)
1882
 
 
1883
 
        config.set_user_option('mail_client', 'mapi')
1884
 
        client = config.get_mail_client()
1885
 
        self.assertIsInstance(client, mail_client.MAPIClient)
1886
 
 
1887
 
        config.set_user_option('mail_client', 'xdg-email')
1888
 
        client = config.get_mail_client()
1889
 
        self.assertIsInstance(client, mail_client.XDGEmail)
1890
 
 
1891
 
        config.set_user_option('mail_client', 'firebird')
1892
 
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1893
 
 
1894
 
 
1895
 
class TestMailAddressExtraction(tests.TestCase):
 
640
        branch = FakeBranch()
 
641
        branch.base='/a/c'
 
642
        my_config = config.BranchConfig(branch)
 
643
        config_file = StringIO(sample_config_text)
 
644
        (my_config._get_location_config().
 
645
            _get_global_config()._get_parser(config_file))
 
646
        branch_file = StringIO(sample_branches_text)
 
647
        my_config._get_location_config()._get_parser(branch_file)
 
648
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
649
                         my_config.post_commit())
 
650
 
 
651
 
 
652
class TestMailAddressExtraction(TestCase):
1896
653
 
1897
654
    def test_extract_email_address(self):
1898
655
        self.assertEqual('jane@test.com',
1899
656
                         config.extract_email_address('Jane <jane@test.com>'))
1900
 
        self.assertRaises(errors.NoEmailInUsername,
 
657
        self.assertRaises(errors.BzrError,
1901
658
                          config.extract_email_address, 'Jane Tester')
1902
 
 
1903
 
    def test_parse_username(self):
1904
 
        self.assertEqual(('', 'jdoe@example.com'),
1905
 
                         config.parse_username('jdoe@example.com'))
1906
 
        self.assertEqual(('', 'jdoe@example.com'),
1907
 
                         config.parse_username('<jdoe@example.com>'))
1908
 
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1909
 
                         config.parse_username('John Doe <jdoe@example.com>'))
1910
 
        self.assertEqual(('John Doe', ''),
1911
 
                         config.parse_username('John Doe'))
1912
 
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1913
 
                         config.parse_username('John Doe jdoe@example.com'))
1914
 
 
1915
 
class TestTreeConfig(tests.TestCaseWithTransport):
1916
 
 
1917
 
    def test_get_value(self):
1918
 
        """Test that retreiving a value from a section is possible"""
1919
 
        branch = self.make_branch('.')
1920
 
        tree_config = config.TreeConfig(branch)
1921
 
        tree_config.set_option('value', 'key', 'SECTION')
1922
 
        tree_config.set_option('value2', 'key2')
1923
 
        tree_config.set_option('value3-top', 'key3')
1924
 
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1925
 
        value = tree_config.get_option('key', 'SECTION')
1926
 
        self.assertEqual(value, 'value')
1927
 
        value = tree_config.get_option('key2')
1928
 
        self.assertEqual(value, 'value2')
1929
 
        self.assertEqual(tree_config.get_option('non-existant'), None)
1930
 
        value = tree_config.get_option('non-existant', 'SECTION')
1931
 
        self.assertEqual(value, None)
1932
 
        value = tree_config.get_option('non-existant', default='default')
1933
 
        self.assertEqual(value, 'default')
1934
 
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1935
 
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1936
 
        self.assertEqual(value, 'default')
1937
 
        value = tree_config.get_option('key3')
1938
 
        self.assertEqual(value, 'value3-top')
1939
 
        value = tree_config.get_option('key3', 'SECTION')
1940
 
        self.assertEqual(value, 'value3-section')
1941
 
 
1942
 
 
1943
 
class TestTransportConfig(tests.TestCaseWithTransport):
1944
 
 
1945
 
    def test_load_utf8(self):
1946
 
        """Ensure we can load an utf8-encoded file."""
1947
 
        t = self.get_transport()
1948
 
        unicode_user = u'b\N{Euro Sign}ar'
1949
 
        unicode_content = u'user=%s' % (unicode_user,)
1950
 
        utf8_content = unicode_content.encode('utf8')
1951
 
        # Store the raw content in the config file
1952
 
        t.put_bytes('foo.conf', utf8_content)
1953
 
        conf = config.TransportConfig(t, 'foo.conf')
1954
 
        self.assertEquals(unicode_user, conf.get_option('user'))
1955
 
 
1956
 
    def test_load_non_ascii(self):
1957
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
1958
 
        t = self.get_transport()
1959
 
        t.put_bytes('foo.conf', 'user=foo\n#\xff\n')
1960
 
        conf = config.TransportConfig(t, 'foo.conf')
1961
 
        self.assertRaises(errors.ConfigContentError, conf._get_configobj)
1962
 
 
1963
 
    def test_load_erroneous_content(self):
1964
 
        """Ensure we display a proper error on content that can't be parsed."""
1965
 
        t = self.get_transport()
1966
 
        t.put_bytes('foo.conf', '[open_section\n')
1967
 
        conf = config.TransportConfig(t, 'foo.conf')
1968
 
        self.assertRaises(errors.ParseConfigError, conf._get_configobj)
1969
 
 
1970
 
    def test_load_permission_denied(self):
1971
 
        """Ensure we get an empty config file if the file is inaccessible."""
1972
 
        warnings = []
1973
 
        def warning(*args):
1974
 
            warnings.append(args[0] % args[1:])
1975
 
        self.overrideAttr(trace, 'warning', warning)
1976
 
 
1977
 
        class DenyingTransport(object):
1978
 
 
1979
 
            def __init__(self, base):
1980
 
                self.base = base
1981
 
 
1982
 
            def get_bytes(self, relpath):
1983
 
                raise errors.PermissionDenied(relpath, "")
1984
 
 
1985
 
        cfg = config.TransportConfig(
1986
 
            DenyingTransport("nonexisting://"), 'control.conf')
1987
 
        self.assertIs(None, cfg.get_option('non-existant', 'SECTION'))
1988
 
        self.assertEquals(
1989
 
            warnings,
1990
 
            [u'Permission denied while trying to open configuration file '
1991
 
             u'nonexisting:///control.conf.'])
1992
 
 
1993
 
    def test_get_value(self):
1994
 
        """Test that retreiving a value from a section is possible"""
1995
 
        bzrdir_config = config.TransportConfig(self.get_transport('.'),
1996
 
                                               'control.conf')
1997
 
        bzrdir_config.set_option('value', 'key', 'SECTION')
1998
 
        bzrdir_config.set_option('value2', 'key2')
1999
 
        bzrdir_config.set_option('value3-top', 'key3')
2000
 
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
2001
 
        value = bzrdir_config.get_option('key', 'SECTION')
2002
 
        self.assertEqual(value, 'value')
2003
 
        value = bzrdir_config.get_option('key2')
2004
 
        self.assertEqual(value, 'value2')
2005
 
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
2006
 
        value = bzrdir_config.get_option('non-existant', 'SECTION')
2007
 
        self.assertEqual(value, None)
2008
 
        value = bzrdir_config.get_option('non-existant', default='default')
2009
 
        self.assertEqual(value, 'default')
2010
 
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
2011
 
        value = bzrdir_config.get_option('key2', 'NOSECTION',
2012
 
                                         default='default')
2013
 
        self.assertEqual(value, 'default')
2014
 
        value = bzrdir_config.get_option('key3')
2015
 
        self.assertEqual(value, 'value3-top')
2016
 
        value = bzrdir_config.get_option('key3', 'SECTION')
2017
 
        self.assertEqual(value, 'value3-section')
2018
 
 
2019
 
    def test_set_unset_default_stack_on(self):
2020
 
        my_dir = self.make_bzrdir('.')
2021
 
        bzrdir_config = config.BzrDirConfig(my_dir)
2022
 
        self.assertIs(None, bzrdir_config.get_default_stack_on())
2023
 
        bzrdir_config.set_default_stack_on('Foo')
2024
 
        self.assertEqual('Foo', bzrdir_config._config.get_option(
2025
 
                         'default_stack_on'))
2026
 
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
2027
 
        bzrdir_config.set_default_stack_on(None)
2028
 
        self.assertIs(None, bzrdir_config.get_default_stack_on())
2029
 
 
2030
 
 
2031
 
class TestOldConfigHooks(tests.TestCaseWithTransport):
2032
 
 
2033
 
    def setUp(self):
2034
 
        super(TestOldConfigHooks, self).setUp()
2035
 
        create_configs_with_file_option(self)
2036
 
 
2037
 
    def assertGetHook(self, conf, name, value):
2038
 
        calls = []
2039
 
        def hook(*args):
2040
 
            calls.append(args)
2041
 
        config.OldConfigHooks.install_named_hook('get', hook, None)
2042
 
        self.addCleanup(
2043
 
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
2044
 
        self.assertLength(0, calls)
2045
 
        actual_value = conf.get_user_option(name)
2046
 
        self.assertEquals(value, actual_value)
2047
 
        self.assertLength(1, calls)
2048
 
        self.assertEquals((conf, name, value), calls[0])
2049
 
 
2050
 
    def test_get_hook_bazaar(self):
2051
 
        self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
2052
 
 
2053
 
    def test_get_hook_locations(self):
2054
 
        self.assertGetHook(self.locations_config, 'file', 'locations')
2055
 
 
2056
 
    def test_get_hook_branch(self):
2057
 
        # Since locations masks branch, we define a different option
2058
 
        self.branch_config.set_user_option('file2', 'branch')
2059
 
        self.assertGetHook(self.branch_config, 'file2', 'branch')
2060
 
 
2061
 
    def assertSetHook(self, conf, name, value):
2062
 
        calls = []
2063
 
        def hook(*args):
2064
 
            calls.append(args)
2065
 
        config.OldConfigHooks.install_named_hook('set', hook, None)
2066
 
        self.addCleanup(
2067
 
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
2068
 
        self.assertLength(0, calls)
2069
 
        conf.set_user_option(name, value)
2070
 
        self.assertLength(1, calls)
2071
 
        # We can't assert the conf object below as different configs use
2072
 
        # different means to implement set_user_option and we care only about
2073
 
        # coverage here.
2074
 
        self.assertEquals((name, value), calls[0][1:])
2075
 
 
2076
 
    def test_set_hook_bazaar(self):
2077
 
        self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
2078
 
 
2079
 
    def test_set_hook_locations(self):
2080
 
        self.assertSetHook(self.locations_config, 'foo', 'locations')
2081
 
 
2082
 
    def test_set_hook_branch(self):
2083
 
        self.assertSetHook(self.branch_config, 'foo', 'branch')
2084
 
 
2085
 
    def assertRemoveHook(self, conf, name, section_name=None):
2086
 
        calls = []
2087
 
        def hook(*args):
2088
 
            calls.append(args)
2089
 
        config.OldConfigHooks.install_named_hook('remove', hook, None)
2090
 
        self.addCleanup(
2091
 
            config.OldConfigHooks.uninstall_named_hook, 'remove', None)
2092
 
        self.assertLength(0, calls)
2093
 
        conf.remove_user_option(name, section_name)
2094
 
        self.assertLength(1, calls)
2095
 
        # We can't assert the conf object below as different configs use
2096
 
        # different means to implement remove_user_option and we care only about
2097
 
        # coverage here.
2098
 
        self.assertEquals((name,), calls[0][1:])
2099
 
 
2100
 
    def test_remove_hook_bazaar(self):
2101
 
        self.assertRemoveHook(self.bazaar_config, 'file')
2102
 
 
2103
 
    def test_remove_hook_locations(self):
2104
 
        self.assertRemoveHook(self.locations_config, 'file',
2105
 
                              self.locations_config.location)
2106
 
 
2107
 
    def test_remove_hook_branch(self):
2108
 
        self.assertRemoveHook(self.branch_config, 'file')
2109
 
 
2110
 
    def assertLoadHook(self, name, conf_class, *conf_args):
2111
 
        calls = []
2112
 
        def hook(*args):
2113
 
            calls.append(args)
2114
 
        config.OldConfigHooks.install_named_hook('load', hook, None)
2115
 
        self.addCleanup(
2116
 
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
2117
 
        self.assertLength(0, calls)
2118
 
        # Build a config
2119
 
        conf = conf_class(*conf_args)
2120
 
        # Access an option to trigger a load
2121
 
        conf.get_user_option(name)
2122
 
        self.assertLength(1, calls)
2123
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2124
 
 
2125
 
    def test_load_hook_bazaar(self):
2126
 
        self.assertLoadHook('file', config.GlobalConfig)
2127
 
 
2128
 
    def test_load_hook_locations(self):
2129
 
        self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
2130
 
 
2131
 
    def test_load_hook_branch(self):
2132
 
        self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
2133
 
 
2134
 
    def assertSaveHook(self, conf):
2135
 
        calls = []
2136
 
        def hook(*args):
2137
 
            calls.append(args)
2138
 
        config.OldConfigHooks.install_named_hook('save', hook, None)
2139
 
        self.addCleanup(
2140
 
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
2141
 
        self.assertLength(0, calls)
2142
 
        # Setting an option triggers a save
2143
 
        conf.set_user_option('foo', 'bar')
2144
 
        self.assertLength(1, calls)
2145
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2146
 
 
2147
 
    def test_save_hook_bazaar(self):
2148
 
        self.assertSaveHook(self.bazaar_config)
2149
 
 
2150
 
    def test_save_hook_locations(self):
2151
 
        self.assertSaveHook(self.locations_config)
2152
 
 
2153
 
    def test_save_hook_branch(self):
2154
 
        self.assertSaveHook(self.branch_config)
2155
 
 
2156
 
 
2157
 
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
2158
 
    """Tests config hooks for remote configs.
2159
 
 
2160
 
    No tests for the remove hook as this is not implemented there.
2161
 
    """
2162
 
 
2163
 
    def setUp(self):
2164
 
        super(TestOldConfigHooksForRemote, self).setUp()
2165
 
        self.transport_server = test_server.SmartTCPServer_for_testing
2166
 
        create_configs_with_file_option(self)
2167
 
 
2168
 
    def assertGetHook(self, conf, name, value):
2169
 
        calls = []
2170
 
        def hook(*args):
2171
 
            calls.append(args)
2172
 
        config.OldConfigHooks.install_named_hook('get', hook, None)
2173
 
        self.addCleanup(
2174
 
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
2175
 
        self.assertLength(0, calls)
2176
 
        actual_value = conf.get_option(name)
2177
 
        self.assertEquals(value, actual_value)
2178
 
        self.assertLength(1, calls)
2179
 
        self.assertEquals((conf, name, value), calls[0])
2180
 
 
2181
 
    def test_get_hook_remote_branch(self):
2182
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2183
 
        self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2184
 
 
2185
 
    def test_get_hook_remote_bzrdir(self):
2186
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2187
 
        conf = remote_bzrdir._get_config()
2188
 
        conf.set_option('remotedir', 'file')
2189
 
        self.assertGetHook(conf, 'file', 'remotedir')
2190
 
 
2191
 
    def assertSetHook(self, conf, name, value):
2192
 
        calls = []
2193
 
        def hook(*args):
2194
 
            calls.append(args)
2195
 
        config.OldConfigHooks.install_named_hook('set', hook, None)
2196
 
        self.addCleanup(
2197
 
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
2198
 
        self.assertLength(0, calls)
2199
 
        conf.set_option(value, name)
2200
 
        self.assertLength(1, calls)
2201
 
        # We can't assert the conf object below as different configs use
2202
 
        # different means to implement set_user_option and we care only about
2203
 
        # coverage here.
2204
 
        self.assertEquals((name, value), calls[0][1:])
2205
 
 
2206
 
    def test_set_hook_remote_branch(self):
2207
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2208
 
        self.addCleanup(remote_branch.lock_write().unlock)
2209
 
        self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
2210
 
 
2211
 
    def test_set_hook_remote_bzrdir(self):
2212
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2213
 
        self.addCleanup(remote_branch.lock_write().unlock)
2214
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2215
 
        self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2216
 
 
2217
 
    def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2218
 
        calls = []
2219
 
        def hook(*args):
2220
 
            calls.append(args)
2221
 
        config.OldConfigHooks.install_named_hook('load', hook, None)
2222
 
        self.addCleanup(
2223
 
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
2224
 
        self.assertLength(0, calls)
2225
 
        # Build a config
2226
 
        conf = conf_class(*conf_args)
2227
 
        # Access an option to trigger a load
2228
 
        conf.get_option(name)
2229
 
        self.assertLength(expected_nb_calls, calls)
2230
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2231
 
 
2232
 
    def test_load_hook_remote_branch(self):
2233
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2234
 
        self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2235
 
 
2236
 
    def test_load_hook_remote_bzrdir(self):
2237
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2238
 
        # The config file doesn't exist, set an option to force its creation
2239
 
        conf = remote_bzrdir._get_config()
2240
 
        conf.set_option('remotedir', 'file')
2241
 
        # We get one call for the server and one call for the client, this is
2242
 
        # caused by the differences in implementations betwen
2243
 
        # SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
2244
 
        # SmartServerBranchGetConfigFile (in smart/branch.py)
2245
 
        self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
2246
 
 
2247
 
    def assertSaveHook(self, conf):
2248
 
        calls = []
2249
 
        def hook(*args):
2250
 
            calls.append(args)
2251
 
        config.OldConfigHooks.install_named_hook('save', hook, None)
2252
 
        self.addCleanup(
2253
 
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
2254
 
        self.assertLength(0, calls)
2255
 
        # Setting an option triggers a save
2256
 
        conf.set_option('foo', 'bar')
2257
 
        self.assertLength(1, calls)
2258
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2259
 
 
2260
 
    def test_save_hook_remote_branch(self):
2261
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2262
 
        self.addCleanup(remote_branch.lock_write().unlock)
2263
 
        self.assertSaveHook(remote_branch._get_config())
2264
 
 
2265
 
    def test_save_hook_remote_bzrdir(self):
2266
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2267
 
        self.addCleanup(remote_branch.lock_write().unlock)
2268
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2269
 
        self.assertSaveHook(remote_bzrdir._get_config())
2270
 
 
2271
 
 
2272
 
class TestOption(tests.TestCase):
2273
 
 
2274
 
    def test_default_value(self):
2275
 
        opt = config.Option('foo', default='bar')
2276
 
        self.assertEquals('bar', opt.get_default())
2277
 
 
2278
 
    def test_default_value_from_env(self):
2279
 
        opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2280
 
        self.overrideEnv('FOO', 'quux')
2281
 
        # Env variable provides a default taking over the option one
2282
 
        self.assertEquals('quux', opt.get_default())
2283
 
 
2284
 
    def test_first_default_value_from_env_wins(self):
2285
 
        opt = config.Option('foo', default='bar',
2286
 
                            default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2287
 
        self.overrideEnv('FOO', 'foo')
2288
 
        self.overrideEnv('BAZ', 'baz')
2289
 
        # The first env var set wins
2290
 
        self.assertEquals('foo', opt.get_default())
2291
 
 
2292
 
    def test_not_supported_list_default_value(self):
2293
 
        self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2294
 
 
2295
 
    def test_not_supported_object_default_value(self):
2296
 
        self.assertRaises(AssertionError, config.Option, 'foo',
2297
 
                          default=object())
2298
 
 
2299
 
 
2300
 
class TestOptionConverterMixin(object):
2301
 
 
2302
 
    def assertConverted(self, expected, opt, value):
2303
 
        self.assertEquals(expected, opt.convert_from_unicode(value))
2304
 
 
2305
 
    def assertWarns(self, opt, value):
2306
 
        warnings = []
2307
 
        def warning(*args):
2308
 
            warnings.append(args[0] % args[1:])
2309
 
        self.overrideAttr(trace, 'warning', warning)
2310
 
        self.assertEquals(None, opt.convert_from_unicode(value))
2311
 
        self.assertLength(1, warnings)
2312
 
        self.assertEquals(
2313
 
            'Value "%s" is not valid for "%s"' % (value, opt.name),
2314
 
            warnings[0])
2315
 
 
2316
 
    def assertErrors(self, opt, value):
2317
 
        self.assertRaises(errors.ConfigOptionValueError,
2318
 
                          opt.convert_from_unicode, value)
2319
 
 
2320
 
    def assertConvertInvalid(self, opt, invalid_value):
2321
 
        opt.invalid = None
2322
 
        self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2323
 
        opt.invalid = 'warning'
2324
 
        self.assertWarns(opt, invalid_value)
2325
 
        opt.invalid = 'error'
2326
 
        self.assertErrors(opt, invalid_value)
2327
 
 
2328
 
 
2329
 
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2330
 
 
2331
 
    def get_option(self):
2332
 
        return config.Option('foo', help='A boolean.',
2333
 
                             from_unicode=config.bool_from_store)
2334
 
 
2335
 
    def test_convert_invalid(self):
2336
 
        opt = self.get_option()
2337
 
        # A string that is not recognized as a boolean
2338
 
        self.assertConvertInvalid(opt, u'invalid-boolean')
2339
 
        # A list of strings is never recognized as a boolean
2340
 
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2341
 
 
2342
 
    def test_convert_valid(self):
2343
 
        opt = self.get_option()
2344
 
        self.assertConverted(True, opt, u'True')
2345
 
        self.assertConverted(True, opt, u'1')
2346
 
        self.assertConverted(False, opt, u'False')
2347
 
 
2348
 
 
2349
 
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2350
 
 
2351
 
    def get_option(self):
2352
 
        return config.Option('foo', help='An integer.',
2353
 
                             from_unicode=config.int_from_store)
2354
 
 
2355
 
    def test_convert_invalid(self):
2356
 
        opt = self.get_option()
2357
 
        # A string that is not recognized as an integer
2358
 
        self.assertConvertInvalid(opt, u'forty-two')
2359
 
        # A list of strings is never recognized as an integer
2360
 
        self.assertConvertInvalid(opt, [u'a', u'list'])
2361
 
 
2362
 
    def test_convert_valid(self):
2363
 
        opt = self.get_option()
2364
 
        self.assertConverted(16, opt, u'16')
2365
 
 
2366
 
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2367
 
 
2368
 
    def get_option(self):
2369
 
        return config.Option('foo', help='A list.',
2370
 
                             from_unicode=config.list_from_store)
2371
 
 
2372
 
    def test_convert_invalid(self):
2373
 
        # No string is invalid as all forms can be converted to a list
2374
 
        pass
2375
 
 
2376
 
    def test_convert_valid(self):
2377
 
        opt = self.get_option()
2378
 
        # An empty string is an empty list
2379
 
        self.assertConverted([], opt, '') # Using a bare str() just in case
2380
 
        self.assertConverted([], opt, u'')
2381
 
        # A boolean
2382
 
        self.assertConverted([u'True'], opt, u'True')
2383
 
        # An integer
2384
 
        self.assertConverted([u'42'], opt, u'42')
2385
 
        # A single string
2386
 
        self.assertConverted([u'bar'], opt, u'bar')
2387
 
        # A list remains a list (configObj will turn a string containing commas
2388
 
        # into a list, but that's not what we're testing here)
2389
 
        self.assertConverted([u'foo', u'1', u'True'],
2390
 
                             opt, [u'foo', u'1', u'True'])
2391
 
 
2392
 
 
2393
 
class TestOptionConverterMixin(object):
2394
 
 
2395
 
    def assertConverted(self, expected, opt, value):
2396
 
        self.assertEquals(expected, opt.convert_from_unicode(value))
2397
 
 
2398
 
    def assertWarns(self, opt, value):
2399
 
        warnings = []
2400
 
        def warning(*args):
2401
 
            warnings.append(args[0] % args[1:])
2402
 
        self.overrideAttr(trace, 'warning', warning)
2403
 
        self.assertEquals(None, opt.convert_from_unicode(value))
2404
 
        self.assertLength(1, warnings)
2405
 
        self.assertEquals(
2406
 
            'Value "%s" is not valid for "%s"' % (value, opt.name),
2407
 
            warnings[0])
2408
 
 
2409
 
    def assertErrors(self, opt, value):
2410
 
        self.assertRaises(errors.ConfigOptionValueError,
2411
 
                          opt.convert_from_unicode, value)
2412
 
 
2413
 
    def assertConvertInvalid(self, opt, invalid_value):
2414
 
        opt.invalid = None
2415
 
        self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2416
 
        opt.invalid = 'warning'
2417
 
        self.assertWarns(opt, invalid_value)
2418
 
        opt.invalid = 'error'
2419
 
        self.assertErrors(opt, invalid_value)
2420
 
 
2421
 
 
2422
 
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2423
 
 
2424
 
    def get_option(self):
2425
 
        return config.Option('foo', help='A boolean.',
2426
 
                             from_unicode=config.bool_from_store)
2427
 
 
2428
 
    def test_convert_invalid(self):
2429
 
        opt = self.get_option()
2430
 
        # A string that is not recognized as a boolean
2431
 
        self.assertConvertInvalid(opt, u'invalid-boolean')
2432
 
        # A list of strings is never recognized as a boolean
2433
 
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2434
 
 
2435
 
    def test_convert_valid(self):
2436
 
        opt = self.get_option()
2437
 
        self.assertConverted(True, opt, u'True')
2438
 
        self.assertConverted(True, opt, u'1')
2439
 
        self.assertConverted(False, opt, u'False')
2440
 
 
2441
 
 
2442
 
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2443
 
 
2444
 
    def get_option(self):
2445
 
        return config.Option('foo', help='An integer.',
2446
 
                             from_unicode=config.int_from_store)
2447
 
 
2448
 
    def test_convert_invalid(self):
2449
 
        opt = self.get_option()
2450
 
        # A string that is not recognized as an integer
2451
 
        self.assertConvertInvalid(opt, u'forty-two')
2452
 
        # A list of strings is never recognized as an integer
2453
 
        self.assertConvertInvalid(opt, [u'a', u'list'])
2454
 
 
2455
 
    def test_convert_valid(self):
2456
 
        opt = self.get_option()
2457
 
        self.assertConverted(16, opt, u'16')
2458
 
 
2459
 
 
2460
 
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2461
 
 
2462
 
    def get_option(self):
2463
 
        return config.Option('foo', help='A list.',
2464
 
                             from_unicode=config.list_from_store)
2465
 
 
2466
 
    def test_convert_invalid(self):
2467
 
        opt = self.get_option()
2468
 
        # We don't even try to convert a list into a list, we only expect
2469
 
        # strings
2470
 
        self.assertConvertInvalid(opt, [1])
2471
 
        # No string is invalid as all forms can be converted to a list
2472
 
 
2473
 
    def test_convert_valid(self):
2474
 
        opt = self.get_option()
2475
 
        # An empty string is an empty list
2476
 
        self.assertConverted([], opt, '') # Using a bare str() just in case
2477
 
        self.assertConverted([], opt, u'')
2478
 
        # A boolean
2479
 
        self.assertConverted([u'True'], opt, u'True')
2480
 
        # An integer
2481
 
        self.assertConverted([u'42'], opt, u'42')
2482
 
        # A single string
2483
 
        self.assertConverted([u'bar'], opt, u'bar')
2484
 
 
2485
 
 
2486
 
class TestOptionRegistry(tests.TestCase):
2487
 
 
2488
 
    def setUp(self):
2489
 
        super(TestOptionRegistry, self).setUp()
2490
 
        # Always start with an empty registry
2491
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2492
 
        self.registry = config.option_registry
2493
 
 
2494
 
    def test_register(self):
2495
 
        opt = config.Option('foo')
2496
 
        self.registry.register(opt)
2497
 
        self.assertIs(opt, self.registry.get('foo'))
2498
 
 
2499
 
    def test_registered_help(self):
2500
 
        opt = config.Option('foo', help='A simple option')
2501
 
        self.registry.register(opt)
2502
 
        self.assertEquals('A simple option', self.registry.get_help('foo'))
2503
 
 
2504
 
    lazy_option = config.Option('lazy_foo', help='Lazy help')
2505
 
 
2506
 
    def test_register_lazy(self):
2507
 
        self.registry.register_lazy('lazy_foo', self.__module__,
2508
 
                                    'TestOptionRegistry.lazy_option')
2509
 
        self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2510
 
 
2511
 
    def test_registered_lazy_help(self):
2512
 
        self.registry.register_lazy('lazy_foo', self.__module__,
2513
 
                                    'TestOptionRegistry.lazy_option')
2514
 
        self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2515
 
 
2516
 
 
2517
 
class TestRegisteredOptions(tests.TestCase):
2518
 
    """All registered options should verify some constraints."""
2519
 
 
2520
 
    scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2521
 
                 in config.option_registry.iteritems()]
2522
 
 
2523
 
    def setUp(self):
2524
 
        super(TestRegisteredOptions, self).setUp()
2525
 
        self.registry = config.option_registry
2526
 
 
2527
 
    def test_proper_name(self):
2528
 
        # An option should be registered under its own name, this can't be
2529
 
        # checked at registration time for the lazy ones.
2530
 
        self.assertEquals(self.option_name, self.option.name)
2531
 
 
2532
 
    def test_help_is_set(self):
2533
 
        option_help = self.registry.get_help(self.option_name)
2534
 
        self.assertNotEquals(None, option_help)
2535
 
        # Come on, think about the user, he really wants to know what the
2536
 
        # option is about
2537
 
        self.assertIsNot(None, option_help)
2538
 
        self.assertNotEquals('', option_help)
2539
 
 
2540
 
 
2541
 
class TestSection(tests.TestCase):
2542
 
 
2543
 
    # FIXME: Parametrize so that all sections produced by Stores run these
2544
 
    # tests -- vila 2011-04-01
2545
 
 
2546
 
    def test_get_a_value(self):
2547
 
        a_dict = dict(foo='bar')
2548
 
        section = config.Section('myID', a_dict)
2549
 
        self.assertEquals('bar', section.get('foo'))
2550
 
 
2551
 
    def test_get_unknown_option(self):
2552
 
        a_dict = dict()
2553
 
        section = config.Section(None, a_dict)
2554
 
        self.assertEquals('out of thin air',
2555
 
                          section.get('foo', 'out of thin air'))
2556
 
 
2557
 
    def test_options_is_shared(self):
2558
 
        a_dict = dict()
2559
 
        section = config.Section(None, a_dict)
2560
 
        self.assertIs(a_dict, section.options)
2561
 
 
2562
 
 
2563
 
class TestMutableSection(tests.TestCase):
2564
 
 
2565
 
    scenarios = [('mutable',
2566
 
                  {'get_section':
2567
 
                       lambda opts: config.MutableSection('myID', opts)},),
2568
 
                 ('cmdline',
2569
 
                  {'get_section':
2570
 
                       lambda opts: config.CommandLineSection(opts)},),
2571
 
        ]
2572
 
 
2573
 
    def test_set(self):
2574
 
        a_dict = dict(foo='bar')
2575
 
        section = self.get_section(a_dict)
2576
 
        section.set('foo', 'new_value')
2577
 
        self.assertEquals('new_value', section.get('foo'))
2578
 
        # The change appears in the shared section
2579
 
        self.assertEquals('new_value', a_dict.get('foo'))
2580
 
        # We keep track of the change
2581
 
        self.assertTrue('foo' in section.orig)
2582
 
        self.assertEquals('bar', section.orig.get('foo'))
2583
 
 
2584
 
    def test_set_preserve_original_once(self):
2585
 
        a_dict = dict(foo='bar')
2586
 
        section = self.get_section(a_dict)
2587
 
        section.set('foo', 'first_value')
2588
 
        section.set('foo', 'second_value')
2589
 
        # We keep track of the original value
2590
 
        self.assertTrue('foo' in section.orig)
2591
 
        self.assertEquals('bar', section.orig.get('foo'))
2592
 
 
2593
 
    def test_remove(self):
2594
 
        a_dict = dict(foo='bar')
2595
 
        section = self.get_section(a_dict)
2596
 
        section.remove('foo')
2597
 
        # We get None for unknown options via the default value
2598
 
        self.assertEquals(None, section.get('foo'))
2599
 
        # Or we just get the default value
2600
 
        self.assertEquals('unknown', section.get('foo', 'unknown'))
2601
 
        self.assertFalse('foo' in section.options)
2602
 
        # We keep track of the deletion
2603
 
        self.assertTrue('foo' in section.orig)
2604
 
        self.assertEquals('bar', section.orig.get('foo'))
2605
 
 
2606
 
    def test_remove_new_option(self):
2607
 
        a_dict = dict()
2608
 
        section = self.get_section(a_dict)
2609
 
        section.set('foo', 'bar')
2610
 
        section.remove('foo')
2611
 
        self.assertFalse('foo' in section.options)
2612
 
        # The option didn't exist initially so it we need to keep track of it
2613
 
        # with a special value
2614
 
        self.assertTrue('foo' in section.orig)
2615
 
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2616
 
 
2617
 
 
2618
 
class TestCommandLineSection(tests.TestCase):
2619
 
 
2620
 
    def setUp(self):
2621
 
        super(TestCommandLineSection, self).setUp()
2622
 
        self.section = config.CommandLineSection()
2623
 
 
2624
 
    def test_no_override(self):
2625
 
        self.section._from_cmdline([])
2626
 
        # FIXME: we want some iterator over all options, failing that, we peek
2627
 
        # under the cover -- vila 2011-09026
2628
 
        self.assertLength(0, self.section.options)
2629
 
 
2630
 
    def test_simple_override(self):
2631
 
        self.section._from_cmdline(['a=b'])
2632
 
        self.assertEqual('b', self.section.get('a'))
2633
 
 
2634
 
    def test_list_override(self):
2635
 
        self.section._from_cmdline(['l=1,2,3'])
2636
 
        val = self.section.get('l')
2637
 
        self.assertEqual('1,2,3', val)
2638
 
        # Reminder: lists should registered as such explicitely, otherwise the
2639
 
        # conversion needs to be done afterwards.
2640
 
        self.assertEqual(['1', '2', '3'], config.list_from_store(val))
2641
 
 
2642
 
    def test_multiple_overrides(self):
2643
 
        self.section._from_cmdline(['a=b', 'x=y'])
2644
 
        self.assertEquals('b', self.section.get('a'))
2645
 
        self.assertEquals('y', self.section.get('x'))
2646
 
 
2647
 
    def test_wrong_syntax(self):
2648
 
        self.assertRaises(errors.BzrCommandError,
2649
 
                          self.section._from_cmdline, ['a=b', 'c'])
2650
 
 
2651
 
 
2652
 
class TestStore(tests.TestCaseWithTransport):
2653
 
 
2654
 
    def assertSectionContent(self, expected, section):
2655
 
        """Assert that some options have the proper values in a section."""
2656
 
        expected_name, expected_options = expected
2657
 
        self.assertEquals(expected_name, section.id)
2658
 
        self.assertEquals(
2659
 
            expected_options,
2660
 
            dict([(k, section.get(k)) for k in expected_options.keys()]))
2661
 
 
2662
 
 
2663
 
class TestReadonlyStore(TestStore):
2664
 
 
2665
 
    scenarios = [(key, {'get_store': builder}) for key, builder
2666
 
                 in config.test_store_builder_registry.iteritems()]
2667
 
 
2668
 
    def test_building_delays_load(self):
2669
 
        store = self.get_store(self)
2670
 
        self.assertEquals(False, store.is_loaded())
2671
 
        store._load_from_string('')
2672
 
        self.assertEquals(True, store.is_loaded())
2673
 
 
2674
 
    def test_get_no_sections_for_empty(self):
2675
 
        store = self.get_store(self)
2676
 
        store._load_from_string('')
2677
 
        self.assertEquals([], list(store.get_sections()))
2678
 
 
2679
 
    def test_get_default_section(self):
2680
 
        store = self.get_store(self)
2681
 
        store._load_from_string('foo=bar')
2682
 
        sections = list(store.get_sections())
2683
 
        self.assertLength(1, sections)
2684
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2685
 
 
2686
 
    def test_get_named_section(self):
2687
 
        store = self.get_store(self)
2688
 
        store._load_from_string('[baz]\nfoo=bar')
2689
 
        sections = list(store.get_sections())
2690
 
        self.assertLength(1, sections)
2691
 
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2692
 
 
2693
 
    def test_load_from_string_fails_for_non_empty_store(self):
2694
 
        store = self.get_store(self)
2695
 
        store._load_from_string('foo=bar')
2696
 
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2697
 
 
2698
 
 
2699
 
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2700
 
    """Simulate loading a config store with content of various encodings.
2701
 
 
2702
 
    All files produced by bzr are in utf8 content.
2703
 
 
2704
 
    Users may modify them manually and end up with a file that can't be
2705
 
    loaded. We need to issue proper error messages in this case.
2706
 
    """
2707
 
 
2708
 
    invalid_utf8_char = '\xff'
2709
 
 
2710
 
    def test_load_utf8(self):
2711
 
        """Ensure we can load an utf8-encoded file."""
2712
 
        t = self.get_transport()
2713
 
        # From http://pad.lv/799212
2714
 
        unicode_user = u'b\N{Euro Sign}ar'
2715
 
        unicode_content = u'user=%s' % (unicode_user,)
2716
 
        utf8_content = unicode_content.encode('utf8')
2717
 
        # Store the raw content in the config file
2718
 
        t.put_bytes('foo.conf', utf8_content)
2719
 
        store = config.IniFileStore(t, 'foo.conf')
2720
 
        store.load()
2721
 
        stack = config.Stack([store.get_sections], store)
2722
 
        self.assertEquals(unicode_user, stack.get('user'))
2723
 
 
2724
 
    def test_load_non_ascii(self):
2725
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2726
 
        t = self.get_transport()
2727
 
        t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2728
 
        store = config.IniFileStore(t, 'foo.conf')
2729
 
        self.assertRaises(errors.ConfigContentError, store.load)
2730
 
 
2731
 
    def test_load_erroneous_content(self):
2732
 
        """Ensure we display a proper error on content that can't be parsed."""
2733
 
        t = self.get_transport()
2734
 
        t.put_bytes('foo.conf', '[open_section\n')
2735
 
        store = config.IniFileStore(t, 'foo.conf')
2736
 
        self.assertRaises(errors.ParseConfigError, store.load)
2737
 
 
2738
 
    def test_load_permission_denied(self):
2739
 
        """Ensure we get warned when trying to load an inaccessible file."""
2740
 
        warnings = []
2741
 
        def warning(*args):
2742
 
            warnings.append(args[0] % args[1:])
2743
 
        self.overrideAttr(trace, 'warning', warning)
2744
 
 
2745
 
        t = self.get_transport()
2746
 
 
2747
 
        def get_bytes(relpath):
2748
 
            raise errors.PermissionDenied(relpath, "")
2749
 
        t.get_bytes = get_bytes
2750
 
        store = config.IniFileStore(t, 'foo.conf')
2751
 
        self.assertRaises(errors.PermissionDenied, store.load)
2752
 
        self.assertEquals(
2753
 
            warnings,
2754
 
            [u'Permission denied while trying to load configuration store %s.'
2755
 
             % store.external_url()])
2756
 
 
2757
 
 
2758
 
class TestIniConfigContent(tests.TestCaseWithTransport):
2759
 
    """Simulate loading a IniBasedConfig with content of various encodings.
2760
 
 
2761
 
    All files produced by bzr are in utf8 content.
2762
 
 
2763
 
    Users may modify them manually and end up with a file that can't be
2764
 
    loaded. We need to issue proper error messages in this case.
2765
 
    """
2766
 
 
2767
 
    invalid_utf8_char = '\xff'
2768
 
 
2769
 
    def test_load_utf8(self):
2770
 
        """Ensure we can load an utf8-encoded file."""
2771
 
        # From http://pad.lv/799212
2772
 
        unicode_user = u'b\N{Euro Sign}ar'
2773
 
        unicode_content = u'user=%s' % (unicode_user,)
2774
 
        utf8_content = unicode_content.encode('utf8')
2775
 
        # Store the raw content in the config file
2776
 
        with open('foo.conf', 'wb') as f:
2777
 
            f.write(utf8_content)
2778
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2779
 
        self.assertEquals(unicode_user, conf.get_user_option('user'))
2780
 
 
2781
 
    def test_load_badly_encoded_content(self):
2782
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2783
 
        with open('foo.conf', 'wb') as f:
2784
 
            f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2785
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2786
 
        self.assertRaises(errors.ConfigContentError, conf._get_parser)
2787
 
 
2788
 
    def test_load_erroneous_content(self):
2789
 
        """Ensure we display a proper error on content that can't be parsed."""
2790
 
        with open('foo.conf', 'wb') as f:
2791
 
            f.write('[open_section\n')
2792
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2793
 
        self.assertRaises(errors.ParseConfigError, conf._get_parser)
2794
 
 
2795
 
 
2796
 
class TestMutableStore(TestStore):
2797
 
 
2798
 
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2799
 
                 in config.test_store_builder_registry.iteritems()]
2800
 
 
2801
 
    def setUp(self):
2802
 
        super(TestMutableStore, self).setUp()
2803
 
        self.transport = self.get_transport()
2804
 
 
2805
 
    def has_store(self, store):
2806
 
        store_basename = urlutils.relative_url(self.transport.external_url(),
2807
 
                                               store.external_url())
2808
 
        return self.transport.has(store_basename)
2809
 
 
2810
 
    def test_save_empty_creates_no_file(self):
2811
 
        # FIXME: There should be a better way than relying on the test
2812
 
        # parametrization to identify branch.conf -- vila 2011-0526
2813
 
        if self.store_id in ('branch', 'remote_branch'):
2814
 
            raise tests.TestNotApplicable(
2815
 
                'branch.conf is *always* created when a branch is initialized')
2816
 
        store = self.get_store(self)
2817
 
        store.save()
2818
 
        self.assertEquals(False, self.has_store(store))
2819
 
 
2820
 
    def test_save_emptied_succeeds(self):
2821
 
        store = self.get_store(self)
2822
 
        store._load_from_string('foo=bar\n')
2823
 
        section = store.get_mutable_section(None)
2824
 
        section.remove('foo')
2825
 
        store.save()
2826
 
        self.assertEquals(True, self.has_store(store))
2827
 
        modified_store = self.get_store(self)
2828
 
        sections = list(modified_store.get_sections())
2829
 
        self.assertLength(0, sections)
2830
 
 
2831
 
    def test_save_with_content_succeeds(self):
2832
 
        # FIXME: There should be a better way than relying on the test
2833
 
        # parametrization to identify branch.conf -- vila 2011-0526
2834
 
        if self.store_id in ('branch', 'remote_branch'):
2835
 
            raise tests.TestNotApplicable(
2836
 
                'branch.conf is *always* created when a branch is initialized')
2837
 
        store = self.get_store(self)
2838
 
        store._load_from_string('foo=bar\n')
2839
 
        self.assertEquals(False, self.has_store(store))
2840
 
        store.save()
2841
 
        self.assertEquals(True, self.has_store(store))
2842
 
        modified_store = self.get_store(self)
2843
 
        sections = list(modified_store.get_sections())
2844
 
        self.assertLength(1, sections)
2845
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2846
 
 
2847
 
    def test_set_option_in_empty_store(self):
2848
 
        store = self.get_store(self)
2849
 
        section = store.get_mutable_section(None)
2850
 
        section.set('foo', 'bar')
2851
 
        store.save()
2852
 
        modified_store = self.get_store(self)
2853
 
        sections = list(modified_store.get_sections())
2854
 
        self.assertLength(1, sections)
2855
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2856
 
 
2857
 
    def test_set_option_in_default_section(self):
2858
 
        store = self.get_store(self)
2859
 
        store._load_from_string('')
2860
 
        section = store.get_mutable_section(None)
2861
 
        section.set('foo', 'bar')
2862
 
        store.save()
2863
 
        modified_store = self.get_store(self)
2864
 
        sections = list(modified_store.get_sections())
2865
 
        self.assertLength(1, sections)
2866
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2867
 
 
2868
 
    def test_set_option_in_named_section(self):
2869
 
        store = self.get_store(self)
2870
 
        store._load_from_string('')
2871
 
        section = store.get_mutable_section('baz')
2872
 
        section.set('foo', 'bar')
2873
 
        store.save()
2874
 
        modified_store = self.get_store(self)
2875
 
        sections = list(modified_store.get_sections())
2876
 
        self.assertLength(1, sections)
2877
 
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2878
 
 
2879
 
    def test_load_hook(self):
2880
 
        # We first needs to ensure that the store exists
2881
 
        store = self.get_store(self)
2882
 
        section = store.get_mutable_section('baz')
2883
 
        section.set('foo', 'bar')
2884
 
        store.save()
2885
 
        # Now we can try to load it
2886
 
        store = self.get_store(self)
2887
 
        calls = []
2888
 
        def hook(*args):
2889
 
            calls.append(args)
2890
 
        config.ConfigHooks.install_named_hook('load', hook, None)
2891
 
        self.assertLength(0, calls)
2892
 
        store.load()
2893
 
        self.assertLength(1, calls)
2894
 
        self.assertEquals((store,), calls[0])
2895
 
 
2896
 
    def test_save_hook(self):
2897
 
        calls = []
2898
 
        def hook(*args):
2899
 
            calls.append(args)
2900
 
        config.ConfigHooks.install_named_hook('save', hook, None)
2901
 
        self.assertLength(0, calls)
2902
 
        store = self.get_store(self)
2903
 
        section = store.get_mutable_section('baz')
2904
 
        section.set('foo', 'bar')
2905
 
        store.save()
2906
 
        self.assertLength(1, calls)
2907
 
        self.assertEquals((store,), calls[0])
2908
 
 
2909
 
 
2910
 
class TestIniFileStore(TestStore):
2911
 
 
2912
 
    def test_loading_unknown_file_fails(self):
2913
 
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
2914
 
        self.assertRaises(errors.NoSuchFile, store.load)
2915
 
 
2916
 
    def test_invalid_content(self):
2917
 
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2918
 
        self.assertEquals(False, store.is_loaded())
2919
 
        exc = self.assertRaises(
2920
 
            errors.ParseConfigError, store._load_from_string,
2921
 
            'this is invalid !')
2922
 
        self.assertEndsWith(exc.filename, 'foo.conf')
2923
 
        # And the load failed
2924
 
        self.assertEquals(False, store.is_loaded())
2925
 
 
2926
 
    def test_get_embedded_sections(self):
2927
 
        # A more complicated example (which also shows that section names and
2928
 
        # option names share the same name space...)
2929
 
        # FIXME: This should be fixed by forbidding dicts as values ?
2930
 
        # -- vila 2011-04-05
2931
 
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2932
 
        store._load_from_string('''
2933
 
foo=bar
2934
 
l=1,2
2935
 
[DEFAULT]
2936
 
foo_in_DEFAULT=foo_DEFAULT
2937
 
[bar]
2938
 
foo_in_bar=barbar
2939
 
[baz]
2940
 
foo_in_baz=barbaz
2941
 
[[qux]]
2942
 
foo_in_qux=quux
2943
 
''')
2944
 
        sections = list(store.get_sections())
2945
 
        self.assertLength(4, sections)
2946
 
        # The default section has no name.
2947
 
        # List values are provided as strings and need to be explicitly
2948
 
        # converted by specifying from_unicode=list_from_store at option
2949
 
        # registration
2950
 
        self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
2951
 
                                  sections[0])
2952
 
        self.assertSectionContent(
2953
 
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2954
 
        self.assertSectionContent(
2955
 
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
2956
 
        # sub sections are provided as embedded dicts.
2957
 
        self.assertSectionContent(
2958
 
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2959
 
            sections[3])
2960
 
 
2961
 
 
2962
 
class TestLockableIniFileStore(TestStore):
2963
 
 
2964
 
    def test_create_store_in_created_dir(self):
2965
 
        self.assertPathDoesNotExist('dir')
2966
 
        t = self.get_transport('dir/subdir')
2967
 
        store = config.LockableIniFileStore(t, 'foo.conf')
2968
 
        store.get_mutable_section(None).set('foo', 'bar')
2969
 
        store.save()
2970
 
        self.assertPathExists('dir/subdir')
2971
 
 
2972
 
 
2973
 
class TestConcurrentStoreUpdates(TestStore):
2974
 
    """Test that Stores properly handle conccurent updates.
2975
 
 
2976
 
    New Store implementation may fail some of these tests but until such
2977
 
    implementations exist it's hard to properly filter them from the scenarios
2978
 
    applied here. If you encounter such a case, contact the bzr devs.
2979
 
    """
2980
 
 
2981
 
    scenarios = [(key, {'get_stack': builder}) for key, builder
2982
 
                 in config.test_stack_builder_registry.iteritems()]
2983
 
 
2984
 
    def setUp(self):
2985
 
        super(TestConcurrentStoreUpdates, self).setUp()
2986
 
        self._content = 'one=1\ntwo=2\n'
2987
 
        self.stack = self.get_stack(self)
2988
 
        if not isinstance(self.stack, config._CompatibleStack):
2989
 
            raise tests.TestNotApplicable(
2990
 
                '%s is not meant to be compatible with the old config design'
2991
 
                % (self.stack,))
2992
 
        self.stack.store._load_from_string(self._content)
2993
 
        # Flush the store
2994
 
        self.stack.store.save()
2995
 
 
2996
 
    def test_simple_read_access(self):
2997
 
        self.assertEquals('1', self.stack.get('one'))
2998
 
 
2999
 
    def test_simple_write_access(self):
3000
 
        self.stack.set('one', 'one')
3001
 
        self.assertEquals('one', self.stack.get('one'))
3002
 
 
3003
 
    def test_listen_to_the_last_speaker(self):
3004
 
        c1 = self.stack
3005
 
        c2 = self.get_stack(self)
3006
 
        c1.set('one', 'ONE')
3007
 
        c2.set('two', 'TWO')
3008
 
        self.assertEquals('ONE', c1.get('one'))
3009
 
        self.assertEquals('TWO', c2.get('two'))
3010
 
        # The second update respect the first one
3011
 
        self.assertEquals('ONE', c2.get('one'))
3012
 
 
3013
 
    def test_last_speaker_wins(self):
3014
 
        # If the same config is not shared, the same variable modified twice
3015
 
        # can only see a single result.
3016
 
        c1 = self.stack
3017
 
        c2 = self.get_stack(self)
3018
 
        c1.set('one', 'c1')
3019
 
        c2.set('one', 'c2')
3020
 
        self.assertEquals('c2', c2.get('one'))
3021
 
        # The first modification is still available until another refresh
3022
 
        # occur
3023
 
        self.assertEquals('c1', c1.get('one'))
3024
 
        c1.set('two', 'done')
3025
 
        self.assertEquals('c2', c1.get('one'))
3026
 
 
3027
 
    def test_writes_are_serialized(self):
3028
 
        c1 = self.stack
3029
 
        c2 = self.get_stack(self)
3030
 
 
3031
 
        # We spawn a thread that will pause *during* the config saving.
3032
 
        before_writing = threading.Event()
3033
 
        after_writing = threading.Event()
3034
 
        writing_done = threading.Event()
3035
 
        c1_save_without_locking_orig = c1.store.save_without_locking
3036
 
        def c1_save_without_locking():
3037
 
            before_writing.set()
3038
 
            c1_save_without_locking_orig()
3039
 
            # The lock is held. We wait for the main thread to decide when to
3040
 
            # continue
3041
 
            after_writing.wait()
3042
 
        c1.store.save_without_locking = c1_save_without_locking
3043
 
        def c1_set():
3044
 
            c1.set('one', 'c1')
3045
 
            writing_done.set()
3046
 
        t1 = threading.Thread(target=c1_set)
3047
 
        # Collect the thread after the test
3048
 
        self.addCleanup(t1.join)
3049
 
        # Be ready to unblock the thread if the test goes wrong
3050
 
        self.addCleanup(after_writing.set)
3051
 
        t1.start()
3052
 
        before_writing.wait()
3053
 
        self.assertRaises(errors.LockContention,
3054
 
                          c2.set, 'one', 'c2')
3055
 
        self.assertEquals('c1', c1.get('one'))
3056
 
        # Let the lock be released
3057
 
        after_writing.set()
3058
 
        writing_done.wait()
3059
 
        c2.set('one', 'c2')
3060
 
        self.assertEquals('c2', c2.get('one'))
3061
 
 
3062
 
    def test_read_while_writing(self):
3063
 
       c1 = self.stack
3064
 
       # We spawn a thread that will pause *during* the write
3065
 
       ready_to_write = threading.Event()
3066
 
       do_writing = threading.Event()
3067
 
       writing_done = threading.Event()
3068
 
       # We override the _save implementation so we know the store is locked
3069
 
       c1_save_without_locking_orig = c1.store.save_without_locking
3070
 
       def c1_save_without_locking():
3071
 
           ready_to_write.set()
3072
 
           # The lock is held. We wait for the main thread to decide when to
3073
 
           # continue
3074
 
           do_writing.wait()
3075
 
           c1_save_without_locking_orig()
3076
 
           writing_done.set()
3077
 
       c1.store.save_without_locking = c1_save_without_locking
3078
 
       def c1_set():
3079
 
           c1.set('one', 'c1')
3080
 
       t1 = threading.Thread(target=c1_set)
3081
 
       # Collect the thread after the test
3082
 
       self.addCleanup(t1.join)
3083
 
       # Be ready to unblock the thread if the test goes wrong
3084
 
       self.addCleanup(do_writing.set)
3085
 
       t1.start()
3086
 
       # Ensure the thread is ready to write
3087
 
       ready_to_write.wait()
3088
 
       self.assertEquals('c1', c1.get('one'))
3089
 
       # If we read during the write, we get the old value
3090
 
       c2 = self.get_stack(self)
3091
 
       self.assertEquals('1', c2.get('one'))
3092
 
       # Let the writing occur and ensure it occurred
3093
 
       do_writing.set()
3094
 
       writing_done.wait()
3095
 
       # Now we get the updated value
3096
 
       c3 = self.get_stack(self)
3097
 
       self.assertEquals('c1', c3.get('one'))
3098
 
 
3099
 
    # FIXME: It may be worth looking into removing the lock dir when it's not
3100
 
    # needed anymore and look at possible fallouts for concurrent lockers. This
3101
 
    # will matter if/when we use config files outside of bazaar directories
3102
 
    # (.bazaar or .bzr) -- vila 20110-04-111
3103
 
 
3104
 
 
3105
 
class TestSectionMatcher(TestStore):
3106
 
 
3107
 
    scenarios = [('location', {'matcher': config.LocationMatcher}),
3108
 
                 ('id', {'matcher': config.NameMatcher}),]
3109
 
 
3110
 
    def setUp(self):
3111
 
        super(TestSectionMatcher, self).setUp()
3112
 
        # Any simple store is good enough
3113
 
        self.get_store = config.test_store_builder_registry.get('configobj')
3114
 
 
3115
 
    def test_no_matches_for_empty_stores(self):
3116
 
        store = self.get_store(self)
3117
 
        store._load_from_string('')
3118
 
        matcher = self.matcher(store, '/bar')
3119
 
        self.assertEquals([], list(matcher.get_sections()))
3120
 
 
3121
 
    def test_build_doesnt_load_store(self):
3122
 
        store = self.get_store(self)
3123
 
        matcher = self.matcher(store, '/bar')
3124
 
        self.assertFalse(store.is_loaded())
3125
 
 
3126
 
 
3127
 
class TestLocationSection(tests.TestCase):
3128
 
 
3129
 
    def get_section(self, options, extra_path):
3130
 
        section = config.Section('foo', options)
3131
 
        # We don't care about the length so we use '0'
3132
 
        return config.LocationSection(section, 0, extra_path)
3133
 
 
3134
 
    def test_simple_option(self):
3135
 
        section = self.get_section({'foo': 'bar'}, '')
3136
 
        self.assertEquals('bar', section.get('foo'))
3137
 
 
3138
 
    def test_option_with_extra_path(self):
3139
 
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
3140
 
                                   'baz')
3141
 
        self.assertEquals('bar/baz', section.get('foo'))
3142
 
 
3143
 
    def test_invalid_policy(self):
3144
 
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
3145
 
                                   'baz')
3146
 
        # invalid policies are ignored
3147
 
        self.assertEquals('bar', section.get('foo'))
3148
 
 
3149
 
 
3150
 
class TestLocationMatcher(TestStore):
3151
 
 
3152
 
    def setUp(self):
3153
 
        super(TestLocationMatcher, self).setUp()
3154
 
        # Any simple store is good enough
3155
 
        self.get_store = config.test_store_builder_registry.get('configobj')
3156
 
 
3157
 
    def test_unrelated_section_excluded(self):
3158
 
        store = self.get_store(self)
3159
 
        store._load_from_string('''
3160
 
[/foo]
3161
 
section=/foo
3162
 
[/foo/baz]
3163
 
section=/foo/baz
3164
 
[/foo/bar]
3165
 
section=/foo/bar
3166
 
[/foo/bar/baz]
3167
 
section=/foo/bar/baz
3168
 
[/quux/quux]
3169
 
section=/quux/quux
3170
 
''')
3171
 
        self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3172
 
                           '/quux/quux'],
3173
 
                          [section.id for section in store.get_sections()])
3174
 
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
3175
 
        sections = list(matcher.get_sections())
3176
 
        self.assertEquals([3, 2],
3177
 
                          [section.length for section in sections])
3178
 
        self.assertEquals(['/foo/bar', '/foo'],
3179
 
                          [section.id for section in sections])
3180
 
        self.assertEquals(['quux', 'bar/quux'],
3181
 
                          [section.extra_path for section in sections])
3182
 
 
3183
 
    def test_more_specific_sections_first(self):
3184
 
        store = self.get_store(self)
3185
 
        store._load_from_string('''
3186
 
[/foo]
3187
 
section=/foo
3188
 
[/foo/bar]
3189
 
section=/foo/bar
3190
 
''')
3191
 
        self.assertEquals(['/foo', '/foo/bar'],
3192
 
                          [section.id for section in store.get_sections()])
3193
 
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
3194
 
        sections = list(matcher.get_sections())
3195
 
        self.assertEquals([3, 2],
3196
 
                          [section.length for section in sections])
3197
 
        self.assertEquals(['/foo/bar', '/foo'],
3198
 
                          [section.id for section in sections])
3199
 
        self.assertEquals(['baz', 'bar/baz'],
3200
 
                          [section.extra_path for section in sections])
3201
 
 
3202
 
    def test_appendpath_in_no_name_section(self):
3203
 
        # It's a bit weird to allow appendpath in a no-name section, but
3204
 
        # someone may found a use for it
3205
 
        store = self.get_store(self)
3206
 
        store._load_from_string('''
3207
 
foo=bar
3208
 
foo:policy = appendpath
3209
 
''')
3210
 
        matcher = config.LocationMatcher(store, 'dir/subdir')
3211
 
        sections = list(matcher.get_sections())
3212
 
        self.assertLength(1, sections)
3213
 
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
3214
 
 
3215
 
    def test_file_urls_are_normalized(self):
3216
 
        store = self.get_store(self)
3217
 
        if sys.platform == 'win32':
3218
 
            expected_url = 'file:///C:/dir/subdir'
3219
 
            expected_location = 'C:/dir/subdir'
3220
 
        else:
3221
 
            expected_url = 'file:///dir/subdir'
3222
 
            expected_location = '/dir/subdir'
3223
 
        matcher = config.LocationMatcher(store, expected_url)
3224
 
        self.assertEquals(expected_location, matcher.location)
3225
 
 
3226
 
 
3227
 
class TestNameMatcher(TestStore):
3228
 
 
3229
 
    def setUp(self):
3230
 
        super(TestNameMatcher, self).setUp()
3231
 
        self.matcher = config.NameMatcher
3232
 
        # Any simple store is good enough
3233
 
        self.get_store = config.test_store_builder_registry.get('configobj')
3234
 
 
3235
 
    def get_matching_sections(self, name):
3236
 
        store = self.get_store(self)
3237
 
        store._load_from_string('''
3238
 
[foo]
3239
 
option=foo
3240
 
[foo/baz]
3241
 
option=foo/baz
3242
 
[bar]
3243
 
option=bar
3244
 
''')
3245
 
        matcher = self.matcher(store, name)
3246
 
        return list(matcher.get_sections())
3247
 
 
3248
 
    def test_matching(self):
3249
 
        sections = self.get_matching_sections('foo')
3250
 
        self.assertLength(1, sections)
3251
 
        self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3252
 
 
3253
 
    def test_not_matching(self):
3254
 
        sections = self.get_matching_sections('baz')
3255
 
        self.assertLength(0, sections)
3256
 
 
3257
 
 
3258
 
class TestStackGet(tests.TestCase):
3259
 
 
3260
 
    # FIXME: This should be parametrized for all known Stack or dedicated
3261
 
    # paramerized tests created to avoid bloating -- vila 2011-03-31
3262
 
 
3263
 
    def overrideOptionRegistry(self):
3264
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3265
 
 
3266
 
    def test_single_config_get(self):
3267
 
        conf = dict(foo='bar')
3268
 
        conf_stack = config.Stack([conf])
3269
 
        self.assertEquals('bar', conf_stack.get('foo'))
3270
 
 
3271
 
    def test_get_with_registered_default_value(self):
3272
 
        conf_stack = config.Stack([dict()])
3273
 
        opt = config.Option('foo', default='bar')
3274
 
        self.overrideOptionRegistry()
3275
 
        config.option_registry.register('foo', opt)
3276
 
        self.assertEquals('bar', conf_stack.get('foo'))
3277
 
 
3278
 
    def test_get_without_registered_default_value(self):
3279
 
        conf_stack = config.Stack([dict()])
3280
 
        opt = config.Option('foo')
3281
 
        self.overrideOptionRegistry()
3282
 
        config.option_registry.register('foo', opt)
3283
 
        self.assertEquals(None, conf_stack.get('foo'))
3284
 
 
3285
 
    def test_get_without_default_value_for_not_registered(self):
3286
 
        conf_stack = config.Stack([dict()])
3287
 
        opt = config.Option('foo')
3288
 
        self.overrideOptionRegistry()
3289
 
        self.assertEquals(None, conf_stack.get('foo'))
3290
 
 
3291
 
    def test_get_first_definition(self):
3292
 
        conf1 = dict(foo='bar')
3293
 
        conf2 = dict(foo='baz')
3294
 
        conf_stack = config.Stack([conf1, conf2])
3295
 
        self.assertEquals('bar', conf_stack.get('foo'))
3296
 
 
3297
 
    def test_get_embedded_definition(self):
3298
 
        conf1 = dict(yy='12')
3299
 
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
3300
 
        conf_stack = config.Stack([conf1, conf2])
3301
 
        self.assertEquals('baz', conf_stack.get('foo'))
3302
 
 
3303
 
    def test_get_for_empty_section_callable(self):
3304
 
        conf_stack = config.Stack([lambda : []])
3305
 
        self.assertEquals(None, conf_stack.get('foo'))
3306
 
 
3307
 
    def test_get_for_broken_callable(self):
3308
 
        # Trying to use and invalid callable raises an exception on first use
3309
 
        conf_stack = config.Stack([lambda : object()])
3310
 
        self.assertRaises(TypeError, conf_stack.get, 'foo')
3311
 
 
3312
 
 
3313
 
class TestStackWithTransport(tests.TestCaseWithTransport):
3314
 
 
3315
 
    scenarios = [(key, {'get_stack': builder}) for key, builder
3316
 
                 in config.test_stack_builder_registry.iteritems()]
3317
 
 
3318
 
 
3319
 
class TestConcreteStacks(TestStackWithTransport):
3320
 
 
3321
 
    def test_build_stack(self):
3322
 
        # Just a smoke test to help debug builders
3323
 
        stack = self.get_stack(self)
3324
 
 
3325
 
 
3326
 
class TestStackGet(TestStackWithTransport):
3327
 
 
3328
 
    def setUp(self):
3329
 
        super(TestStackGet, self).setUp()
3330
 
        self.conf = self.get_stack(self)
3331
 
 
3332
 
    def test_get_for_empty_stack(self):
3333
 
        self.assertEquals(None, self.conf.get('foo'))
3334
 
 
3335
 
    def test_get_hook(self):
3336
 
        self.conf.store._load_from_string('foo=bar')
3337
 
        calls = []
3338
 
        def hook(*args):
3339
 
            calls.append(args)
3340
 
        config.ConfigHooks.install_named_hook('get', hook, None)
3341
 
        self.assertLength(0, calls)
3342
 
        value = self.conf.get('foo')
3343
 
        self.assertEquals('bar', value)
3344
 
        self.assertLength(1, calls)
3345
 
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3346
 
 
3347
 
 
3348
 
class TestStackGetWithConverter(TestStackGet):
3349
 
 
3350
 
    def setUp(self):
3351
 
        super(TestStackGetWithConverter, self).setUp()
3352
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3353
 
        self.registry = config.option_registry
3354
 
 
3355
 
    def register_bool_option(self, name, default=None, default_from_env=None):
3356
 
        b = config.Option(name, help='A boolean.',
3357
 
                          default=default, default_from_env=default_from_env,
3358
 
                          from_unicode=config.bool_from_store)
3359
 
        self.registry.register(b)
3360
 
 
3361
 
    def test_get_default_bool_None(self):
3362
 
        self.register_bool_option('foo')
3363
 
        self.assertEquals(None, self.conf.get('foo'))
3364
 
 
3365
 
    def test_get_default_bool_True(self):
3366
 
        self.register_bool_option('foo', u'True')
3367
 
        self.assertEquals(True, self.conf.get('foo'))
3368
 
 
3369
 
    def test_get_default_bool_False(self):
3370
 
        self.register_bool_option('foo', False)
3371
 
        self.assertEquals(False, self.conf.get('foo'))
3372
 
 
3373
 
    def test_get_default_bool_False_as_string(self):
3374
 
        self.register_bool_option('foo', u'False')
3375
 
        self.assertEquals(False, self.conf.get('foo'))
3376
 
 
3377
 
    def test_get_default_bool_from_env_converted(self):
3378
 
        self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3379
 
        self.overrideEnv('FOO', 'False')
3380
 
        self.assertEquals(False, self.conf.get('foo'))
3381
 
 
3382
 
    def test_get_default_bool_when_conversion_fails(self):
3383
 
        self.register_bool_option('foo', default='True')
3384
 
        self.conf.store._load_from_string('foo=invalid boolean')
3385
 
        self.assertEquals(True, self.conf.get('foo'))
3386
 
 
3387
 
    def register_integer_option(self, name,
3388
 
                                default=None, default_from_env=None):
3389
 
        i = config.Option(name, help='An integer.',
3390
 
                          default=default, default_from_env=default_from_env,
3391
 
                          from_unicode=config.int_from_store)
3392
 
        self.registry.register(i)
3393
 
 
3394
 
    def test_get_default_integer_None(self):
3395
 
        self.register_integer_option('foo')
3396
 
        self.assertEquals(None, self.conf.get('foo'))
3397
 
 
3398
 
    def test_get_default_integer(self):
3399
 
        self.register_integer_option('foo', 42)
3400
 
        self.assertEquals(42, self.conf.get('foo'))
3401
 
 
3402
 
    def test_get_default_integer_as_string(self):
3403
 
        self.register_integer_option('foo', u'42')
3404
 
        self.assertEquals(42, self.conf.get('foo'))
3405
 
 
3406
 
    def test_get_default_integer_from_env(self):
3407
 
        self.register_integer_option('foo', default_from_env=['FOO'])
3408
 
        self.overrideEnv('FOO', '18')
3409
 
        self.assertEquals(18, self.conf.get('foo'))
3410
 
 
3411
 
    def test_get_default_integer_when_conversion_fails(self):
3412
 
        self.register_integer_option('foo', default='12')
3413
 
        self.conf.store._load_from_string('foo=invalid integer')
3414
 
        self.assertEquals(12, self.conf.get('foo'))
3415
 
 
3416
 
    def register_list_option(self, name, default=None, default_from_env=None):
3417
 
        l = config.Option(name, help='A list.',
3418
 
                          default=default, default_from_env=default_from_env,
3419
 
                          from_unicode=config.list_from_store)
3420
 
        self.registry.register(l)
3421
 
 
3422
 
    def test_get_default_list_None(self):
3423
 
        self.register_list_option('foo')
3424
 
        self.assertEquals(None, self.conf.get('foo'))
3425
 
 
3426
 
    def test_get_default_list_empty(self):
3427
 
        self.register_list_option('foo', '')
3428
 
        self.assertEquals([], self.conf.get('foo'))
3429
 
 
3430
 
    def test_get_default_list_from_env(self):
3431
 
        self.register_list_option('foo', default_from_env=['FOO'])
3432
 
        self.overrideEnv('FOO', '')
3433
 
        self.assertEquals([], self.conf.get('foo'))
3434
 
 
3435
 
    def test_get_with_list_converter_no_item(self):
3436
 
        self.register_list_option('foo', None)
3437
 
        self.conf.store._load_from_string('foo=,')
3438
 
        self.assertEquals([], self.conf.get('foo'))
3439
 
 
3440
 
    def test_get_with_list_converter_many_items(self):
3441
 
        self.register_list_option('foo', None)
3442
 
        self.conf.store._load_from_string('foo=m,o,r,e')
3443
 
        self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
3444
 
 
3445
 
    def test_get_with_list_converter_embedded_spaces_many_items(self):
3446
 
        self.register_list_option('foo', None)
3447
 
        self.conf.store._load_from_string('foo=" bar", "baz "')
3448
 
        self.assertEquals([' bar', 'baz '], self.conf.get('foo'))
3449
 
 
3450
 
    def test_get_with_list_converter_stripped_spaces_many_items(self):
3451
 
        self.register_list_option('foo', None)
3452
 
        self.conf.store._load_from_string('foo= bar ,  baz ')
3453
 
        self.assertEquals(['bar', 'baz'], self.conf.get('foo'))
3454
 
 
3455
 
 
3456
 
class TestStackExpandOptions(tests.TestCaseWithTransport):
3457
 
 
3458
 
    def setUp(self):
3459
 
        super(TestStackExpandOptions, self).setUp()
3460
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3461
 
        self.registry = config.option_registry
3462
 
        self.conf = build_branch_stack(self)
3463
 
 
3464
 
    def assertExpansion(self, expected, string, env=None):
3465
 
        self.assertEquals(expected, self.conf.expand_options(string, env))
3466
 
 
3467
 
    def test_no_expansion(self):
3468
 
        self.assertExpansion('foo', 'foo')
3469
 
 
3470
 
    def test_expand_default_value(self):
3471
 
        self.conf.store._load_from_string('bar=baz')
3472
 
        self.registry.register(config.Option('foo', default=u'{bar}'))
3473
 
        self.assertEquals('baz', self.conf.get('foo', expand=True))
3474
 
 
3475
 
    def test_expand_default_from_env(self):
3476
 
        self.conf.store._load_from_string('bar=baz')
3477
 
        self.registry.register(config.Option('foo', default_from_env=['FOO']))
3478
 
        self.overrideEnv('FOO', '{bar}')
3479
 
        self.assertEquals('baz', self.conf.get('foo', expand=True))
3480
 
 
3481
 
    def test_expand_default_on_failed_conversion(self):
3482
 
        self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
3483
 
        self.registry.register(
3484
 
            config.Option('foo', default=u'{bar}',
3485
 
                          from_unicode=config.int_from_store))
3486
 
        self.assertEquals(42, self.conf.get('foo', expand=True))
3487
 
 
3488
 
    def test_env_adding_options(self):
3489
 
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3490
 
 
3491
 
    def test_env_overriding_options(self):
3492
 
        self.conf.store._load_from_string('foo=baz')
3493
 
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3494
 
 
3495
 
    def test_simple_ref(self):
3496
 
        self.conf.store._load_from_string('foo=xxx')
3497
 
        self.assertExpansion('xxx', '{foo}')
3498
 
 
3499
 
    def test_unknown_ref(self):
3500
 
        self.assertRaises(errors.ExpandingUnknownOption,
3501
 
                          self.conf.expand_options, '{foo}')
3502
 
 
3503
 
    def test_indirect_ref(self):
3504
 
        self.conf.store._load_from_string('''
3505
 
foo=xxx
3506
 
bar={foo}
3507
 
''')
3508
 
        self.assertExpansion('xxx', '{bar}')
3509
 
 
3510
 
    def test_embedded_ref(self):
3511
 
        self.conf.store._load_from_string('''
3512
 
foo=xxx
3513
 
bar=foo
3514
 
''')
3515
 
        self.assertExpansion('xxx', '{{bar}}')
3516
 
 
3517
 
    def test_simple_loop(self):
3518
 
        self.conf.store._load_from_string('foo={foo}')
3519
 
        self.assertRaises(errors.OptionExpansionLoop,
3520
 
                          self.conf.expand_options, '{foo}')
3521
 
 
3522
 
    def test_indirect_loop(self):
3523
 
        self.conf.store._load_from_string('''
3524
 
foo={bar}
3525
 
bar={baz}
3526
 
baz={foo}''')
3527
 
        e = self.assertRaises(errors.OptionExpansionLoop,
3528
 
                              self.conf.expand_options, '{foo}')
3529
 
        self.assertEquals('foo->bar->baz', e.refs)
3530
 
        self.assertEquals('{foo}', e.string)
3531
 
 
3532
 
    def test_list(self):
3533
 
        self.conf.store._load_from_string('''
3534
 
foo=start
3535
 
bar=middle
3536
 
baz=end
3537
 
list={foo},{bar},{baz}
3538
 
''')
3539
 
        self.registry.register(
3540
 
            config.Option('list', from_unicode=config.list_from_store))
3541
 
        self.assertEquals(['start', 'middle', 'end'],
3542
 
                           self.conf.get('list', expand=True))
3543
 
 
3544
 
    def test_cascading_list(self):
3545
 
        self.conf.store._load_from_string('''
3546
 
foo=start,{bar}
3547
 
bar=middle,{baz}
3548
 
baz=end
3549
 
list={foo}
3550
 
''')
3551
 
        self.registry.register(
3552
 
            config.Option('list', from_unicode=config.list_from_store))
3553
 
        self.assertEquals(['start', 'middle', 'end'],
3554
 
                           self.conf.get('list', expand=True))
3555
 
 
3556
 
    def test_pathologically_hidden_list(self):
3557
 
        self.conf.store._load_from_string('''
3558
 
foo=bin
3559
 
bar=go
3560
 
start={foo
3561
 
middle=},{
3562
 
end=bar}
3563
 
hidden={start}{middle}{end}
3564
 
''')
3565
 
        # What matters is what the registration says, the conversion happens
3566
 
        # only after all expansions have been performed
3567
 
        self.registry.register(
3568
 
            config.Option('hidden', from_unicode=config.list_from_store))
3569
 
        self.assertEquals(['bin', 'go'],
3570
 
                          self.conf.get('hidden', expand=True))
3571
 
 
3572
 
 
3573
 
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3574
 
 
3575
 
    def setUp(self):
3576
 
        super(TestStackCrossSectionsExpand, self).setUp()
3577
 
 
3578
 
    def get_config(self, location, string):
3579
 
        if string is None:
3580
 
            string = ''
3581
 
        # Since we don't save the config we won't strictly require to inherit
3582
 
        # from TestCaseInTempDir, but an error occurs so quickly...
3583
 
        c = config.LocationStack(location)
3584
 
        c.store._load_from_string(string)
3585
 
        return c
3586
 
 
3587
 
    def test_dont_cross_unrelated_section(self):
3588
 
        c = self.get_config('/another/branch/path','''
3589
 
[/one/branch/path]
3590
 
foo = hello
3591
 
bar = {foo}/2
3592
 
 
3593
 
[/another/branch/path]
3594
 
bar = {foo}/2
3595
 
''')
3596
 
        self.assertRaises(errors.ExpandingUnknownOption,
3597
 
                          c.get, 'bar', expand=True)
3598
 
 
3599
 
    def test_cross_related_sections(self):
3600
 
        c = self.get_config('/project/branch/path','''
3601
 
[/project]
3602
 
foo = qu
3603
 
 
3604
 
[/project/branch/path]
3605
 
bar = {foo}ux
3606
 
''')
3607
 
        self.assertEquals('quux', c.get('bar', expand=True))
3608
 
 
3609
 
 
3610
 
class TestStackSet(TestStackWithTransport):
3611
 
 
3612
 
    def test_simple_set(self):
3613
 
        conf = self.get_stack(self)
3614
 
        conf.store._load_from_string('foo=bar')
3615
 
        self.assertEquals('bar', conf.get('foo'))
3616
 
        conf.set('foo', 'baz')
3617
 
        # Did we get it back ?
3618
 
        self.assertEquals('baz', conf.get('foo'))
3619
 
 
3620
 
    def test_set_creates_a_new_section(self):
3621
 
        conf = self.get_stack(self)
3622
 
        conf.set('foo', 'baz')
3623
 
        self.assertEquals, 'baz', conf.get('foo')
3624
 
 
3625
 
    def test_set_hook(self):
3626
 
        calls = []
3627
 
        def hook(*args):
3628
 
            calls.append(args)
3629
 
        config.ConfigHooks.install_named_hook('set', hook, None)
3630
 
        self.assertLength(0, calls)
3631
 
        conf = self.get_stack(self)
3632
 
        conf.set('foo', 'bar')
3633
 
        self.assertLength(1, calls)
3634
 
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
3635
 
 
3636
 
 
3637
 
class TestStackRemove(TestStackWithTransport):
3638
 
 
3639
 
    def test_remove_existing(self):
3640
 
        conf = self.get_stack(self)
3641
 
        conf.set('foo', 'bar')
3642
 
        self.assertEquals('bar', conf.get('foo'))
3643
 
        conf.remove('foo')
3644
 
        # Did we get it back ?
3645
 
        self.assertEquals(None, conf.get('foo'))
3646
 
 
3647
 
    def test_remove_unknown(self):
3648
 
        conf = self.get_stack(self)
3649
 
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3650
 
 
3651
 
    def test_remove_hook(self):
3652
 
        calls = []
3653
 
        def hook(*args):
3654
 
            calls.append(args)
3655
 
        config.ConfigHooks.install_named_hook('remove', hook, None)
3656
 
        self.assertLength(0, calls)
3657
 
        conf = self.get_stack(self)
3658
 
        conf.set('foo', 'bar')
3659
 
        conf.remove('foo')
3660
 
        self.assertLength(1, calls)
3661
 
        self.assertEquals((conf, 'foo'), calls[0])
3662
 
 
3663
 
 
3664
 
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3665
 
 
3666
 
    def setUp(self):
3667
 
        super(TestConfigGetOptions, self).setUp()
3668
 
        create_configs(self)
3669
 
 
3670
 
    def test_no_variable(self):
3671
 
        # Using branch should query branch, locations and bazaar
3672
 
        self.assertOptions([], self.branch_config)
3673
 
 
3674
 
    def test_option_in_bazaar(self):
3675
 
        self.bazaar_config.set_user_option('file', 'bazaar')
3676
 
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
3677
 
                           self.bazaar_config)
3678
 
 
3679
 
    def test_option_in_locations(self):
3680
 
        self.locations_config.set_user_option('file', 'locations')
3681
 
        self.assertOptions(
3682
 
            [('file', 'locations', self.tree.basedir, 'locations')],
3683
 
            self.locations_config)
3684
 
 
3685
 
    def test_option_in_branch(self):
3686
 
        self.branch_config.set_user_option('file', 'branch')
3687
 
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
3688
 
                           self.branch_config)
3689
 
 
3690
 
    def test_option_in_bazaar_and_branch(self):
3691
 
        self.bazaar_config.set_user_option('file', 'bazaar')
3692
 
        self.branch_config.set_user_option('file', 'branch')
3693
 
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
3694
 
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3695
 
                           self.branch_config)
3696
 
 
3697
 
    def test_option_in_branch_and_locations(self):
3698
 
        # Hmm, locations override branch :-/
3699
 
        self.locations_config.set_user_option('file', 'locations')
3700
 
        self.branch_config.set_user_option('file', 'branch')
3701
 
        self.assertOptions(
3702
 
            [('file', 'locations', self.tree.basedir, 'locations'),
3703
 
             ('file', 'branch', 'DEFAULT', 'branch'),],
3704
 
            self.branch_config)
3705
 
 
3706
 
    def test_option_in_bazaar_locations_and_branch(self):
3707
 
        self.bazaar_config.set_user_option('file', 'bazaar')
3708
 
        self.locations_config.set_user_option('file', 'locations')
3709
 
        self.branch_config.set_user_option('file', 'branch')
3710
 
        self.assertOptions(
3711
 
            [('file', 'locations', self.tree.basedir, 'locations'),
3712
 
             ('file', 'branch', 'DEFAULT', 'branch'),
3713
 
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3714
 
            self.branch_config)
3715
 
 
3716
 
 
3717
 
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
3718
 
 
3719
 
    def setUp(self):
3720
 
        super(TestConfigRemoveOption, self).setUp()
3721
 
        create_configs_with_file_option(self)
3722
 
 
3723
 
    def test_remove_in_locations(self):
3724
 
        self.locations_config.remove_user_option('file', self.tree.basedir)
3725
 
        self.assertOptions(
3726
 
            [('file', 'branch', 'DEFAULT', 'branch'),
3727
 
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3728
 
            self.branch_config)
3729
 
 
3730
 
    def test_remove_in_branch(self):
3731
 
        self.branch_config.remove_user_option('file')
3732
 
        self.assertOptions(
3733
 
            [('file', 'locations', self.tree.basedir, 'locations'),
3734
 
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3735
 
            self.branch_config)
3736
 
 
3737
 
    def test_remove_in_bazaar(self):
3738
 
        self.bazaar_config.remove_user_option('file')
3739
 
        self.assertOptions(
3740
 
            [('file', 'locations', self.tree.basedir, 'locations'),
3741
 
             ('file', 'branch', 'DEFAULT', 'branch'),],
3742
 
            self.branch_config)
3743
 
 
3744
 
 
3745
 
class TestConfigGetSections(tests.TestCaseWithTransport):
3746
 
 
3747
 
    def setUp(self):
3748
 
        super(TestConfigGetSections, self).setUp()
3749
 
        create_configs(self)
3750
 
 
3751
 
    def assertSectionNames(self, expected, conf, name=None):
3752
 
        """Check which sections are returned for a given config.
3753
 
 
3754
 
        If fallback configurations exist their sections can be included.
3755
 
 
3756
 
        :param expected: A list of section names.
3757
 
 
3758
 
        :param conf: The configuration that will be queried.
3759
 
 
3760
 
        :param name: An optional section name that will be passed to
3761
 
            get_sections().
3762
 
        """
3763
 
        sections = list(conf._get_sections(name))
3764
 
        self.assertLength(len(expected), sections)
3765
 
        self.assertEqual(expected, [name for name, _, _ in sections])
3766
 
 
3767
 
    def test_bazaar_default_section(self):
3768
 
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
3769
 
 
3770
 
    def test_locations_default_section(self):
3771
 
        # No sections are defined in an empty file
3772
 
        self.assertSectionNames([], self.locations_config)
3773
 
 
3774
 
    def test_locations_named_section(self):
3775
 
        self.locations_config.set_user_option('file', 'locations')
3776
 
        self.assertSectionNames([self.tree.basedir], self.locations_config)
3777
 
 
3778
 
    def test_locations_matching_sections(self):
3779
 
        loc_config = self.locations_config
3780
 
        loc_config.set_user_option('file', 'locations')
3781
 
        # We need to cheat a bit here to create an option in sections above and
3782
 
        # below the 'location' one.
3783
 
        parser = loc_config._get_parser()
3784
 
        # locations.cong deals with '/' ignoring native os.sep
3785
 
        location_names = self.tree.basedir.split('/')
3786
 
        parent = '/'.join(location_names[:-1])
3787
 
        child = '/'.join(location_names + ['child'])
3788
 
        parser[parent] = {}
3789
 
        parser[parent]['file'] = 'parent'
3790
 
        parser[child] = {}
3791
 
        parser[child]['file'] = 'child'
3792
 
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
3793
 
 
3794
 
    def test_branch_data_default_section(self):
3795
 
        self.assertSectionNames([None],
3796
 
                                self.branch_config._get_branch_data_config())
3797
 
 
3798
 
    def test_branch_default_sections(self):
3799
 
        # No sections are defined in an empty locations file
3800
 
        self.assertSectionNames([None, 'DEFAULT'],
3801
 
                                self.branch_config)
3802
 
        # Unless we define an option
3803
 
        self.branch_config._get_location_config().set_user_option(
3804
 
            'file', 'locations')
3805
 
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
3806
 
                                self.branch_config)
3807
 
 
3808
 
    def test_bazaar_named_section(self):
3809
 
        # We need to cheat as the API doesn't give direct access to sections
3810
 
        # other than DEFAULT.
3811
 
        self.bazaar_config.set_alias('bazaar', 'bzr')
3812
 
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
3813
 
 
3814
 
 
3815
 
class TestAuthenticationConfigFile(tests.TestCase):
3816
 
    """Test the authentication.conf file matching"""
3817
 
 
3818
 
    def _got_user_passwd(self, expected_user, expected_password,
3819
 
                         config, *args, **kwargs):
3820
 
        credentials = config.get_credentials(*args, **kwargs)
3821
 
        if credentials is None:
3822
 
            user = None
3823
 
            password = None
3824
 
        else:
3825
 
            user = credentials['user']
3826
 
            password = credentials['password']
3827
 
        self.assertEquals(expected_user, user)
3828
 
        self.assertEquals(expected_password, password)
3829
 
 
3830
 
    def test_empty_config(self):
3831
 
        conf = config.AuthenticationConfig(_file=StringIO())
3832
 
        self.assertEquals({}, conf._get_config())
3833
 
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
3834
 
 
3835
 
    def test_non_utf8_config(self):
3836
 
        conf = config.AuthenticationConfig(_file=StringIO(
3837
 
                'foo = bar\xff'))
3838
 
        self.assertRaises(errors.ConfigContentError, conf._get_config)
3839
 
 
3840
 
    def test_missing_auth_section_header(self):
3841
 
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
3842
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3843
 
 
3844
 
    def test_auth_section_header_not_closed(self):
3845
 
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
3846
 
        self.assertRaises(errors.ParseConfigError, conf._get_config)
3847
 
 
3848
 
    def test_auth_value_not_boolean(self):
3849
 
        conf = config.AuthenticationConfig(_file=StringIO(
3850
 
                """[broken]
3851
 
scheme=ftp
3852
 
user=joe
3853
 
verify_certificates=askme # Error: Not a boolean
3854
 
"""))
3855
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3856
 
 
3857
 
    def test_auth_value_not_int(self):
3858
 
        conf = config.AuthenticationConfig(_file=StringIO(
3859
 
                """[broken]
3860
 
scheme=ftp
3861
 
user=joe
3862
 
port=port # Error: Not an int
3863
 
"""))
3864
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3865
 
 
3866
 
    def test_unknown_password_encoding(self):
3867
 
        conf = config.AuthenticationConfig(_file=StringIO(
3868
 
                """[broken]
3869
 
scheme=ftp
3870
 
user=joe
3871
 
password_encoding=unknown
3872
 
"""))
3873
 
        self.assertRaises(ValueError, conf.get_password,
3874
 
                          'ftp', 'foo.net', 'joe')
3875
 
 
3876
 
    def test_credentials_for_scheme_host(self):
3877
 
        conf = config.AuthenticationConfig(_file=StringIO(
3878
 
                """# Identity on foo.net
3879
 
[ftp definition]
3880
 
scheme=ftp
3881
 
host=foo.net
3882
 
user=joe
3883
 
password=secret-pass
3884
 
"""))
3885
 
        # Basic matching
3886
 
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
3887
 
        # different scheme
3888
 
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
3889
 
        # different host
3890
 
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
3891
 
 
3892
 
    def test_credentials_for_host_port(self):
3893
 
        conf = config.AuthenticationConfig(_file=StringIO(
3894
 
                """# Identity on foo.net
3895
 
[ftp definition]
3896
 
scheme=ftp
3897
 
port=10021
3898
 
host=foo.net
3899
 
user=joe
3900
 
password=secret-pass
3901
 
"""))
3902
 
        # No port
3903
 
        self._got_user_passwd('joe', 'secret-pass',
3904
 
                              conf, 'ftp', 'foo.net', port=10021)
3905
 
        # different port
3906
 
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
3907
 
 
3908
 
    def test_for_matching_host(self):
3909
 
        conf = config.AuthenticationConfig(_file=StringIO(
3910
 
                """# Identity on foo.net
3911
 
[sourceforge]
3912
 
scheme=bzr
3913
 
host=bzr.sf.net
3914
 
user=joe
3915
 
password=joepass
3916
 
[sourceforge domain]
3917
 
scheme=bzr
3918
 
host=.bzr.sf.net
3919
 
user=georges
3920
 
password=bendover
3921
 
"""))
3922
 
        # matching domain
3923
 
        self._got_user_passwd('georges', 'bendover',
3924
 
                              conf, 'bzr', 'foo.bzr.sf.net')
3925
 
        # phishing attempt
3926
 
        self._got_user_passwd(None, None,
3927
 
                              conf, 'bzr', 'bbzr.sf.net')
3928
 
 
3929
 
    def test_for_matching_host_None(self):
3930
 
        conf = config.AuthenticationConfig(_file=StringIO(
3931
 
                """# Identity on foo.net
3932
 
[catchup bzr]
3933
 
scheme=bzr
3934
 
user=joe
3935
 
password=joepass
3936
 
[DEFAULT]
3937
 
user=georges
3938
 
password=bendover
3939
 
"""))
3940
 
        # match no host
3941
 
        self._got_user_passwd('joe', 'joepass',
3942
 
                              conf, 'bzr', 'quux.net')
3943
 
        # no host but different scheme
3944
 
        self._got_user_passwd('georges', 'bendover',
3945
 
                              conf, 'ftp', 'quux.net')
3946
 
 
3947
 
    def test_credentials_for_path(self):
3948
 
        conf = config.AuthenticationConfig(_file=StringIO(
3949
 
                """
3950
 
[http dir1]
3951
 
scheme=http
3952
 
host=bar.org
3953
 
path=/dir1
3954
 
user=jim
3955
 
password=jimpass
3956
 
[http dir2]
3957
 
scheme=http
3958
 
host=bar.org
3959
 
path=/dir2
3960
 
user=georges
3961
 
password=bendover
3962
 
"""))
3963
 
        # no path no dice
3964
 
        self._got_user_passwd(None, None,
3965
 
                              conf, 'http', host='bar.org', path='/dir3')
3966
 
        # matching path
3967
 
        self._got_user_passwd('georges', 'bendover',
3968
 
                              conf, 'http', host='bar.org', path='/dir2')
3969
 
        # matching subdir
3970
 
        self._got_user_passwd('jim', 'jimpass',
3971
 
                              conf, 'http', host='bar.org',path='/dir1/subdir')
3972
 
 
3973
 
    def test_credentials_for_user(self):
3974
 
        conf = config.AuthenticationConfig(_file=StringIO(
3975
 
                """
3976
 
[with user]
3977
 
scheme=http
3978
 
host=bar.org
3979
 
user=jim
3980
 
password=jimpass
3981
 
"""))
3982
 
        # Get user
3983
 
        self._got_user_passwd('jim', 'jimpass',
3984
 
                              conf, 'http', 'bar.org')
3985
 
        # Get same user
3986
 
        self._got_user_passwd('jim', 'jimpass',
3987
 
                              conf, 'http', 'bar.org', user='jim')
3988
 
        # Don't get a different user if one is specified
3989
 
        self._got_user_passwd(None, None,
3990
 
                              conf, 'http', 'bar.org', user='georges')
3991
 
 
3992
 
    def test_credentials_for_user_without_password(self):
3993
 
        conf = config.AuthenticationConfig(_file=StringIO(
3994
 
                """
3995
 
[without password]
3996
 
scheme=http
3997
 
host=bar.org
3998
 
user=jim
3999
 
"""))
4000
 
        # Get user but no password
4001
 
        self._got_user_passwd('jim', None,
4002
 
                              conf, 'http', 'bar.org')
4003
 
 
4004
 
    def test_verify_certificates(self):
4005
 
        conf = config.AuthenticationConfig(_file=StringIO(
4006
 
                """
4007
 
[self-signed]
4008
 
scheme=https
4009
 
host=bar.org
4010
 
user=jim
4011
 
password=jimpass
4012
 
verify_certificates=False
4013
 
[normal]
4014
 
scheme=https
4015
 
host=foo.net
4016
 
user=georges
4017
 
password=bendover
4018
 
"""))
4019
 
        credentials = conf.get_credentials('https', 'bar.org')
4020
 
        self.assertEquals(False, credentials.get('verify_certificates'))
4021
 
        credentials = conf.get_credentials('https', 'foo.net')
4022
 
        self.assertEquals(True, credentials.get('verify_certificates'))
4023
 
 
4024
 
 
4025
 
class TestAuthenticationStorage(tests.TestCaseInTempDir):
4026
 
 
4027
 
    def test_set_credentials(self):
4028
 
        conf = config.AuthenticationConfig()
4029
 
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
4030
 
        99, path='/foo', verify_certificates=False, realm='realm')
4031
 
        credentials = conf.get_credentials(host='host', scheme='scheme',
4032
 
                                           port=99, path='/foo',
4033
 
                                           realm='realm')
4034
 
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4035
 
                       'verify_certificates': False, 'scheme': 'scheme', 
4036
 
                       'host': 'host', 'port': 99, 'path': '/foo', 
4037
 
                       'realm': 'realm'}
4038
 
        self.assertEqual(CREDENTIALS, credentials)
4039
 
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
4040
 
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
4041
 
        self.assertEqual(CREDENTIALS, credentials_from_disk)
4042
 
 
4043
 
    def test_reset_credentials_different_name(self):
4044
 
        conf = config.AuthenticationConfig()
4045
 
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
4046
 
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
4047
 
        self.assertIs(None, conf._get_config().get('name'))
4048
 
        credentials = conf.get_credentials(host='host', scheme='scheme')
4049
 
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4050
 
                       'password', 'verify_certificates': True, 
4051
 
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
4052
 
                       'path': None, 'realm': None}
4053
 
        self.assertEqual(CREDENTIALS, credentials)
4054
 
 
4055
 
 
4056
 
class TestAuthenticationConfig(tests.TestCase):
4057
 
    """Test AuthenticationConfig behaviour"""
4058
 
 
4059
 
    def _check_default_password_prompt(self, expected_prompt_format, scheme,
4060
 
                                       host=None, port=None, realm=None,
4061
 
                                       path=None):
4062
 
        if host is None:
4063
 
            host = 'bar.org'
4064
 
        user, password = 'jim', 'precious'
4065
 
        expected_prompt = expected_prompt_format % {
4066
 
            'scheme': scheme, 'host': host, 'port': port,
4067
 
            'user': user, 'realm': realm}
4068
 
 
4069
 
        stdout = tests.StringIOWrapper()
4070
 
        stderr = tests.StringIOWrapper()
4071
 
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
4072
 
                                            stdout=stdout, stderr=stderr)
4073
 
        # We use an empty conf so that the user is always prompted
4074
 
        conf = config.AuthenticationConfig()
4075
 
        self.assertEquals(password,
4076
 
                          conf.get_password(scheme, host, user, port=port,
4077
 
                                            realm=realm, path=path))
4078
 
        self.assertEquals(expected_prompt, stderr.getvalue())
4079
 
        self.assertEquals('', stdout.getvalue())
4080
 
 
4081
 
    def _check_default_username_prompt(self, expected_prompt_format, scheme,
4082
 
                                       host=None, port=None, realm=None,
4083
 
                                       path=None):
4084
 
        if host is None:
4085
 
            host = 'bar.org'
4086
 
        username = 'jim'
4087
 
        expected_prompt = expected_prompt_format % {
4088
 
            'scheme': scheme, 'host': host, 'port': port,
4089
 
            'realm': realm}
4090
 
        stdout = tests.StringIOWrapper()
4091
 
        stderr = tests.StringIOWrapper()
4092
 
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
4093
 
                                            stdout=stdout, stderr=stderr)
4094
 
        # We use an empty conf so that the user is always prompted
4095
 
        conf = config.AuthenticationConfig()
4096
 
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
4097
 
                          realm=realm, path=path, ask=True))
4098
 
        self.assertEquals(expected_prompt, stderr.getvalue())
4099
 
        self.assertEquals('', stdout.getvalue())
4100
 
 
4101
 
    def test_username_defaults_prompts(self):
4102
 
        # HTTP prompts can't be tested here, see test_http.py
4103
 
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
4104
 
        self._check_default_username_prompt(
4105
 
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
4106
 
        self._check_default_username_prompt(
4107
 
            u'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
4108
 
 
4109
 
    def test_username_default_no_prompt(self):
4110
 
        conf = config.AuthenticationConfig()
4111
 
        self.assertEquals(None,
4112
 
            conf.get_user('ftp', 'example.com'))
4113
 
        self.assertEquals("explicitdefault",
4114
 
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
4115
 
 
4116
 
    def test_password_default_prompts(self):
4117
 
        # HTTP prompts can't be tested here, see test_http.py
4118
 
        self._check_default_password_prompt(
4119
 
            u'FTP %(user)s@%(host)s password: ', 'ftp')
4120
 
        self._check_default_password_prompt(
4121
 
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
4122
 
        self._check_default_password_prompt(
4123
 
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
4124
 
        # SMTP port handling is a bit special (it's handled if embedded in the
4125
 
        # host too)
4126
 
        # FIXME: should we: forbid that, extend it to other schemes, leave
4127
 
        # things as they are that's fine thank you ?
4128
 
        self._check_default_password_prompt(
4129
 
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
4130
 
        self._check_default_password_prompt(
4131
 
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
4132
 
        self._check_default_password_prompt(
4133
 
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
4134
 
 
4135
 
    def test_ssh_password_emits_warning(self):
4136
 
        conf = config.AuthenticationConfig(_file=StringIO(
4137
 
                """
4138
 
[ssh with password]
4139
 
scheme=ssh
4140
 
host=bar.org
4141
 
user=jim
4142
 
password=jimpass
4143
 
"""))
4144
 
        entered_password = 'typed-by-hand'
4145
 
        stdout = tests.StringIOWrapper()
4146
 
        stderr = tests.StringIOWrapper()
4147
 
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4148
 
                                            stdout=stdout, stderr=stderr)
4149
 
 
4150
 
        # Since the password defined in the authentication config is ignored,
4151
 
        # the user is prompted
4152
 
        self.assertEquals(entered_password,
4153
 
                          conf.get_password('ssh', 'bar.org', user='jim'))
4154
 
        self.assertContainsRe(
4155
 
            self.get_log(),
4156
 
            'password ignored in section \[ssh with password\]')
4157
 
 
4158
 
    def test_ssh_without_password_doesnt_emit_warning(self):
4159
 
        conf = config.AuthenticationConfig(_file=StringIO(
4160
 
                """
4161
 
[ssh with password]
4162
 
scheme=ssh
4163
 
host=bar.org
4164
 
user=jim
4165
 
"""))
4166
 
        entered_password = 'typed-by-hand'
4167
 
        stdout = tests.StringIOWrapper()
4168
 
        stderr = tests.StringIOWrapper()
4169
 
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4170
 
                                            stdout=stdout,
4171
 
                                            stderr=stderr)
4172
 
 
4173
 
        # Since the password defined in the authentication config is ignored,
4174
 
        # the user is prompted
4175
 
        self.assertEquals(entered_password,
4176
 
                          conf.get_password('ssh', 'bar.org', user='jim'))
4177
 
        # No warning shoud be emitted since there is no password. We are only
4178
 
        # providing "user".
4179
 
        self.assertNotContainsRe(
4180
 
            self.get_log(),
4181
 
            'password ignored in section \[ssh with password\]')
4182
 
 
4183
 
    def test_uses_fallback_stores(self):
4184
 
        self.overrideAttr(config, 'credential_store_registry',
4185
 
                          config.CredentialStoreRegistry())
4186
 
        store = StubCredentialStore()
4187
 
        store.add_credentials("http", "example.com", "joe", "secret")
4188
 
        config.credential_store_registry.register("stub", store, fallback=True)
4189
 
        conf = config.AuthenticationConfig(_file=StringIO())
4190
 
        creds = conf.get_credentials("http", "example.com")
4191
 
        self.assertEquals("joe", creds["user"])
4192
 
        self.assertEquals("secret", creds["password"])
4193
 
 
4194
 
 
4195
 
class StubCredentialStore(config.CredentialStore):
4196
 
 
4197
 
    def __init__(self):
4198
 
        self._username = {}
4199
 
        self._password = {}
4200
 
 
4201
 
    def add_credentials(self, scheme, host, user, password=None):
4202
 
        self._username[(scheme, host)] = user
4203
 
        self._password[(scheme, host)] = password
4204
 
 
4205
 
    def get_credentials(self, scheme, host, port=None, user=None,
4206
 
        path=None, realm=None):
4207
 
        key = (scheme, host)
4208
 
        if not key in self._username:
4209
 
            return None
4210
 
        return { "scheme": scheme, "host": host, "port": port,
4211
 
                "user": self._username[key], "password": self._password[key]}
4212
 
 
4213
 
 
4214
 
class CountingCredentialStore(config.CredentialStore):
4215
 
 
4216
 
    def __init__(self):
4217
 
        self._calls = 0
4218
 
 
4219
 
    def get_credentials(self, scheme, host, port=None, user=None,
4220
 
        path=None, realm=None):
4221
 
        self._calls += 1
4222
 
        return None
4223
 
 
4224
 
 
4225
 
class TestCredentialStoreRegistry(tests.TestCase):
4226
 
 
4227
 
    def _get_cs_registry(self):
4228
 
        return config.credential_store_registry
4229
 
 
4230
 
    def test_default_credential_store(self):
4231
 
        r = self._get_cs_registry()
4232
 
        default = r.get_credential_store(None)
4233
 
        self.assertIsInstance(default, config.PlainTextCredentialStore)
4234
 
 
4235
 
    def test_unknown_credential_store(self):
4236
 
        r = self._get_cs_registry()
4237
 
        # It's hard to imagine someone creating a credential store named
4238
 
        # 'unknown' so we use that as an never registered key.
4239
 
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
4240
 
 
4241
 
    def test_fallback_none_registered(self):
4242
 
        r = config.CredentialStoreRegistry()
4243
 
        self.assertEquals(None,
4244
 
                          r.get_fallback_credentials("http", "example.com"))
4245
 
 
4246
 
    def test_register(self):
4247
 
        r = config.CredentialStoreRegistry()
4248
 
        r.register("stub", StubCredentialStore(), fallback=False)
4249
 
        r.register("another", StubCredentialStore(), fallback=True)
4250
 
        self.assertEquals(["another", "stub"], r.keys())
4251
 
 
4252
 
    def test_register_lazy(self):
4253
 
        r = config.CredentialStoreRegistry()
4254
 
        r.register_lazy("stub", "bzrlib.tests.test_config",
4255
 
                        "StubCredentialStore", fallback=False)
4256
 
        self.assertEquals(["stub"], r.keys())
4257
 
        self.assertIsInstance(r.get_credential_store("stub"),
4258
 
                              StubCredentialStore)
4259
 
 
4260
 
    def test_is_fallback(self):
4261
 
        r = config.CredentialStoreRegistry()
4262
 
        r.register("stub1", None, fallback=False)
4263
 
        r.register("stub2", None, fallback=True)
4264
 
        self.assertEquals(False, r.is_fallback("stub1"))
4265
 
        self.assertEquals(True, r.is_fallback("stub2"))
4266
 
 
4267
 
    def test_no_fallback(self):
4268
 
        r = config.CredentialStoreRegistry()
4269
 
        store = CountingCredentialStore()
4270
 
        r.register("count", store, fallback=False)
4271
 
        self.assertEquals(None,
4272
 
                          r.get_fallback_credentials("http", "example.com"))
4273
 
        self.assertEquals(0, store._calls)
4274
 
 
4275
 
    def test_fallback_credentials(self):
4276
 
        r = config.CredentialStoreRegistry()
4277
 
        store = StubCredentialStore()
4278
 
        store.add_credentials("http", "example.com",
4279
 
                              "somebody", "geheim")
4280
 
        r.register("stub", store, fallback=True)
4281
 
        creds = r.get_fallback_credentials("http", "example.com")
4282
 
        self.assertEquals("somebody", creds["user"])
4283
 
        self.assertEquals("geheim", creds["password"])
4284
 
 
4285
 
    def test_fallback_first_wins(self):
4286
 
        r = config.CredentialStoreRegistry()
4287
 
        stub1 = StubCredentialStore()
4288
 
        stub1.add_credentials("http", "example.com",
4289
 
                              "somebody", "stub1")
4290
 
        r.register("stub1", stub1, fallback=True)
4291
 
        stub2 = StubCredentialStore()
4292
 
        stub2.add_credentials("http", "example.com",
4293
 
                              "somebody", "stub2")
4294
 
        r.register("stub2", stub1, fallback=True)
4295
 
        creds = r.get_fallback_credentials("http", "example.com")
4296
 
        self.assertEquals("somebody", creds["user"])
4297
 
        self.assertEquals("stub1", creds["password"])
4298
 
 
4299
 
 
4300
 
class TestPlainTextCredentialStore(tests.TestCase):
4301
 
 
4302
 
    def test_decode_password(self):
4303
 
        r = config.credential_store_registry
4304
 
        plain_text = r.get_credential_store()
4305
 
        decoded = plain_text.decode_password(dict(password='secret'))
4306
 
        self.assertEquals('secret', decoded)
4307
 
 
4308
 
 
4309
 
# FIXME: Once we have a way to declare authentication to all test servers, we
4310
 
# can implement generic tests.
4311
 
# test_user_password_in_url
4312
 
# test_user_in_url_password_from_config
4313
 
# test_user_in_url_password_prompted
4314
 
# test_user_in_config
4315
 
# test_user_getpass.getuser
4316
 
# test_user_prompted ?
4317
 
class TestAuthenticationRing(tests.TestCaseWithTransport):
4318
 
    pass
4319
 
 
4320
 
 
4321
 
class TestAutoUserId(tests.TestCase):
4322
 
    """Test inferring an automatic user name."""
4323
 
 
4324
 
    def test_auto_user_id(self):
4325
 
        """Automatic inference of user name.
4326
 
        
4327
 
        This is a bit hard to test in an isolated way, because it depends on
4328
 
        system functions that go direct to /etc or perhaps somewhere else.
4329
 
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
4330
 
        to be able to choose a user name with no configuration.
4331
 
        """
4332
 
        if sys.platform == 'win32':
4333
 
            raise tests.TestSkipped(
4334
 
                "User name inference not implemented on win32")
4335
 
        realname, address = config._auto_user_id()
4336
 
        if os.path.exists('/etc/mailname'):
4337
 
            self.assertIsNot(None, realname)
4338
 
            self.assertIsNot(None, address)
4339
 
        else:
4340
 
            self.assertEquals((None, None), (realname, address))
4341