/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/test_config.py

  • Committer: Jelmer Vernooij
  • Date: 2019-06-29 19:50:18 UTC
  • mto: This revision was merged to the branch mainline in revision 7389.
  • Revision ID: jelmer@jelmer.uk-20190629195018-jaldh0dliq1e79oh
TreeDelta holds TreeChange objects rather than tuples of various sizes.

Show diffs side-by-side

added added

removed removed

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