/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: 2017-07-21 13:20:17 UTC
  • mfrom: (6733.1.1 move-errors-config)
  • Revision ID: jelmer@jelmer.uk-20170721132017-oratmmxasovq4r1q
Merge lp:~jelmer/brz/move-errors-config.

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