~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-06-30 18:28:17 UTC
  • mfrom: (5967.10.2 test-cat)
  • Revision ID: pqm@pqm.ubuntu.com-20110630182817-83a5q9r9rxfkdn8r
(mbp) don't use subprocesses for testing cat (Martin Pool)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2012 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
 
 
 
18
# import system imports here
19
19
from cStringIO import StringIO
20
 
from textwrap import dedent
21
20
import os
22
21
import sys
23
22
import threading
24
23
 
 
24
 
25
25
from testtools import matchers
26
26
 
 
27
#import bzrlib specific imports here
27
28
from bzrlib import (
28
29
    branch,
 
30
    bzrdir,
29
31
    config,
30
 
    controldir,
31
32
    diff,
32
33
    errors,
33
34
    osutils,
34
35
    mail_client,
 
36
    mergetools,
35
37
    ui,
36
38
    urlutils,
37
 
    registry as _mod_registry,
 
39
    registry,
38
40
    remote,
39
41
    tests,
40
42
    trace,
 
43
    transport,
41
44
    )
42
45
from bzrlib.symbol_versioning import (
43
46
    deprecated_in,
 
47
    deprecated_method,
44
48
    )
45
49
from bzrlib.transport import remote as transport_remote
46
50
from bzrlib.tests import (
67
71
 
68
72
# Register helpers to build stores
69
73
config.test_store_builder_registry.register(
70
 
    'configobj', lambda test: config.TransportIniFileStore(
71
 
        test.get_transport(), 'configobj.conf'))
 
74
    'configobj', lambda test: config.IniFileStore(test.get_transport(),
 
75
                                                  'configobj.conf'))
72
76
config.test_store_builder_registry.register(
73
77
    'bazaar', lambda test: config.GlobalStore())
74
78
config.test_store_builder_registry.register(
112
116
config.test_store_builder_registry.register('branch', build_branch_store)
113
117
 
114
118
 
115
 
def build_control_store(test):
116
 
    build_backing_branch(test, 'branch')
117
 
    b = controldir.ControlDir.open('branch')
118
 
    return config.ControlStore(b)
119
 
config.test_store_builder_registry.register('control', build_control_store)
120
 
 
121
 
 
122
119
def build_remote_branch_store(test):
123
120
    # There is only one permutation (but we won't be able to handle more with
124
121
    # this design anyway)
144
141
config.test_stack_builder_registry.register('branch', build_branch_stack)
145
142
 
146
143
 
147
 
def build_branch_only_stack(test):
148
 
    # There is only one permutation (but we won't be able to handle more with
149
 
    # this design anyway)
150
 
    (transport_class,
151
 
     server_class) = transport_remote.get_test_permutations()[0]
152
 
    build_backing_branch(test, 'branch', transport_class, server_class)
153
 
    b = branch.Branch.open(test.get_url('branch'))
154
 
    return config.BranchOnlyStack(b)
155
 
config.test_stack_builder_registry.register('branch_only',
156
 
                                            build_branch_only_stack)
157
 
 
158
 
def build_remote_control_stack(test):
159
 
    # There is only one permutation (but we won't be able to handle more with
160
 
    # this design anyway)
161
 
    (transport_class,
162
 
     server_class) = transport_remote.get_test_permutations()[0]
163
 
    # We need only a bzrdir for this, not a full branch, but it's not worth
164
 
    # creating a dedicated helper to create only the bzrdir
165
 
    build_backing_branch(test, 'branch', transport_class, server_class)
166
 
    b = branch.Branch.open(test.get_url('branch'))
167
 
    return config.RemoteControlStack(b.bzrdir)
168
 
config.test_stack_builder_registry.register('remote_control',
169
 
                                            build_remote_control_stack)
 
144
def build_remote_branch_stack(test):
 
145
    # There is only one permutation (but we won't be able to handle more with
 
146
    # this design anyway)
 
147
    (transport_class,
 
148
     server_class) = transport_remote.get_test_permutations()[0]
 
149
    build_backing_branch(test, 'branch', transport_class, server_class)
 
150
    b = branch.Branch.open(test.get_url('branch'))
 
151
    return config.BranchStack(b)
 
152
config.test_stack_builder_registry.register('remote_branch',
 
153
                                            build_remote_branch_stack)
170
154
 
171
155
 
172
156
sample_long_alias="log -r-15..-1 --line"
176
160
editor=vim
177
161
change_editor=vimdiff -of @new_path @old_path
178
162
gpg_signing_command=gnome-gpg
179
 
gpg_signing_key=DD4D5088
180
163
log_format=short
181
164
validate_signatures_in_log=true
182
165
acceptable_keys=amy
183
166
user_global_option=something
184
167
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
185
168
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
186
 
bzr.mergetool.newtool='"newtool with spaces" {this_temp}'
187
169
bzr.default_mergetool=sometool
188
170
[ALIASES]
189
171
h=help
232
214
[/a/]
233
215
check_signatures=check-available
234
216
gpg_signing_command=false
235
 
gpg_signing_key=default
236
217
user_local_option=local
237
218
# test trailing / matching
238
219
[/a/*]
328
309
 
329
310
class FakeBranch(object):
330
311
 
331
 
    def __init__(self, base=None):
 
312
    def __init__(self, base=None, user_id=None):
332
313
        if base is None:
333
314
            self.base = "http://example.com/branches/demo"
334
315
        else:
335
316
            self.base = base
336
317
        self._transport = self.control_files = \
337
 
            FakeControlFilesAndTransport()
 
318
            FakeControlFilesAndTransport(user_id=user_id)
338
319
 
339
320
    def _get_config(self):
340
321
        return config.TransportConfig(self._transport, 'branch.conf')
348
329
 
349
330
class FakeControlFilesAndTransport(object):
350
331
 
351
 
    def __init__(self):
 
332
    def __init__(self, user_id=None):
352
333
        self.files = {}
 
334
        if user_id:
 
335
            self.files['email'] = user_id
353
336
        self._transport = self
354
337
 
 
338
    def get_utf8(self, filename):
 
339
        # from LockableFiles
 
340
        raise AssertionError("get_utf8 should no longer be used")
 
341
 
355
342
    def get(self, filename):
356
343
        # from Transport
357
344
        try:
475
462
    def test_constructs(self):
476
463
        config.Config()
477
464
 
 
465
    def test_no_default_editor(self):
 
466
        self.assertRaises(
 
467
            NotImplementedError,
 
468
            self.applyDeprecated, deprecated_in((2, 4, 0)),
 
469
            config.Config().get_editor)
 
470
 
478
471
    def test_user_email(self):
479
472
        my_config = InstrumentedConfig()
480
473
        self.assertEqual('robert.collins@example.org', my_config.user_email())
488
481
 
489
482
    def test_signatures_default(self):
490
483
        my_config = config.Config()
491
 
        self.assertFalse(
492
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
493
 
                my_config.signature_needed))
 
484
        self.assertFalse(my_config.signature_needed())
494
485
        self.assertEqual(config.CHECK_IF_POSSIBLE,
495
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
496
 
                my_config.signature_checking))
 
486
                         my_config.signature_checking())
497
487
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
498
 
                self.applyDeprecated(deprecated_in((2, 5, 0)),
499
 
                    my_config.signing_policy))
 
488
                         my_config.signing_policy())
500
489
 
501
490
    def test_signatures_template_method(self):
502
491
        my_config = InstrumentedConfig()
503
 
        self.assertEqual(config.CHECK_NEVER,
504
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
505
 
                my_config.signature_checking))
 
492
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
506
493
        self.assertEqual(['_get_signature_checking'], my_config._calls)
507
494
 
508
495
    def test_signatures_template_method_none(self):
509
496
        my_config = InstrumentedConfig()
510
497
        my_config._signatures = None
511
498
        self.assertEqual(config.CHECK_IF_POSSIBLE,
512
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
513
 
                             my_config.signature_checking))
 
499
                         my_config.signature_checking())
514
500
        self.assertEqual(['_get_signature_checking'], my_config._calls)
515
501
 
516
502
    def test_gpg_signing_command_default(self):
517
503
        my_config = config.Config()
518
 
        self.assertEqual('gpg',
519
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
520
 
                my_config.gpg_signing_command))
 
504
        self.assertEqual('gpg', my_config.gpg_signing_command())
521
505
 
522
506
    def test_get_user_option_default(self):
523
507
        my_config = config.Config()
525
509
 
526
510
    def test_post_commit_default(self):
527
511
        my_config = config.Config()
528
 
        self.assertEqual(None, self.applyDeprecated(deprecated_in((2, 5, 0)),
529
 
                                                    my_config.post_commit))
530
 
 
 
512
        self.assertEqual(None, my_config.post_commit())
531
513
 
532
514
    def test_log_format_default(self):
533
515
        my_config = config.Config()
534
 
        self.assertEqual('long',
535
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
536
 
                                              my_config.log_format))
 
516
        self.assertEqual('long', my_config.log_format())
537
517
 
538
518
    def test_acceptable_keys_default(self):
539
519
        my_config = config.Config()
540
 
        self.assertEqual(None, self.applyDeprecated(deprecated_in((2, 5, 0)),
541
 
            my_config.acceptable_keys))
 
520
        self.assertEqual(None, my_config.acceptable_keys())
542
521
 
543
522
    def test_validate_signatures_in_log_default(self):
544
523
        my_config = config.Config()
558
537
    def setUp(self):
559
538
        super(TestConfigPath, self).setUp()
560
539
        self.overrideEnv('HOME', '/home/bogus')
561
 
        self.overrideEnv('XDG_CACHE_HOME', '')
 
540
        self.overrideEnv('XDG_CACHE_DIR', '')
562
541
        if sys.platform == 'win32':
563
542
            self.overrideEnv(
564
543
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
570
549
    def test_config_dir(self):
571
550
        self.assertEqual(config.config_dir(), self.bzr_home)
572
551
 
573
 
    def test_config_dir_is_unicode(self):
574
 
        self.assertIsInstance(config.config_dir(), unicode)
575
 
 
576
552
    def test_config_filename(self):
577
553
        self.assertEqual(config.config_filename(),
578
554
                         self.bzr_home + '/bazaar.conf')
595
571
    # subdirectory of $XDG_CONFIG_HOME
596
572
 
597
573
    def setUp(self):
598
 
        if sys.platform == 'win32':
 
574
        if sys.platform in ('darwin', 'win32'):
599
575
            raise tests.TestNotApplicable(
600
576
                'XDG config dir not used on this platform')
601
577
        super(TestXDGConfigDir, self).setUp()
628
604
class TestIniConfigBuilding(TestIniConfig):
629
605
 
630
606
    def test_contructs(self):
631
 
        config.IniBasedConfig()
 
607
        my_config = config.IniBasedConfig()
632
608
 
633
609
    def test_from_fp(self):
634
610
        my_config = config.IniBasedConfig.from_string(sample_config_text)
677
653
 
678
654
    def test_saved_with_content(self):
679
655
        content = 'foo = bar\n'
680
 
        config.IniBasedConfig.from_string(content, file_name='./test.conf',
681
 
                                          save=True)
 
656
        conf = config.IniBasedConfig.from_string(
 
657
            content, file_name='./test.conf', save=True)
682
658
        self.assertFileEqual(content, 'test.conf')
683
659
 
684
660
 
 
661
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
 
662
    """What is the default value of expand for config options.
 
663
 
 
664
    This is an opt-in beta feature used to evaluate whether or not option
 
665
    references can appear in dangerous place raising exceptions, disapearing
 
666
    (and as such corrupting data) or if it's safe to activate the option by
 
667
    default.
 
668
 
 
669
    Note that these tests relies on config._expand_default_value being already
 
670
    overwritten in the parent class setUp.
 
671
    """
 
672
 
 
673
    def setUp(self):
 
674
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
 
675
        self.config = None
 
676
        self.warnings = []
 
677
        def warning(*args):
 
678
            self.warnings.append(args[0] % args[1:])
 
679
        self.overrideAttr(trace, 'warning', warning)
 
680
 
 
681
    def get_config(self, expand):
 
682
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
 
683
                                            save=True)
 
684
        return c
 
685
 
 
686
    def assertExpandIs(self, expected):
 
687
        actual = config._get_expand_default_value()
 
688
        #self.config.get_user_option_as_bool('bzr.config.expand')
 
689
        self.assertEquals(expected, actual)
 
690
 
 
691
    def test_default_is_None(self):
 
692
        self.assertEquals(None, config._expand_default_value)
 
693
 
 
694
    def test_default_is_False_even_if_None(self):
 
695
        self.config = self.get_config(None)
 
696
        self.assertExpandIs(False)
 
697
 
 
698
    def test_default_is_False_even_if_invalid(self):
 
699
        self.config = self.get_config('<your choice>')
 
700
        self.assertExpandIs(False)
 
701
        # ...
 
702
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
 
703
        # Wait, you've been warned !
 
704
        self.assertLength(1, self.warnings)
 
705
        self.assertEquals(
 
706
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
 
707
            self.warnings[0])
 
708
 
 
709
    def test_default_is_True(self):
 
710
        self.config = self.get_config(True)
 
711
        self.assertExpandIs(True)
 
712
 
 
713
    def test_default_is_False(self):
 
714
        self.config = self.get_config(False)
 
715
        self.assertExpandIs(False)
 
716
 
 
717
 
685
718
class TestIniConfigOptionExpansion(tests.TestCase):
686
719
    """Test option expansion from the IniConfig level.
687
720
 
784
817
        self.assertEquals(['{foo', '}', '{', 'bar}'],
785
818
                          conf.get_user_option('hidden', expand=True))
786
819
 
787
 
 
788
820
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
789
821
 
790
822
    def get_config(self, location, string=None):
1001
1033
        # automatically cast to list
1002
1034
        self.assertEqual(['x'], get_list('one_item'))
1003
1035
 
1004
 
    def test_get_user_option_as_int_from_SI(self):
1005
 
        conf, parser = self.make_config_parser("""
1006
 
plain = 100
1007
 
si_k = 5k,
1008
 
si_kb = 5kb,
1009
 
si_m = 5M,
1010
 
si_mb = 5MB,
1011
 
si_g = 5g,
1012
 
si_gb = 5gB,
1013
 
""")
1014
 
        def get_si(s, default=None):
1015
 
            return self.applyDeprecated(
1016
 
                deprecated_in((2, 5, 0)),
1017
 
                conf.get_user_option_as_int_from_SI, s, default)
1018
 
        self.assertEqual(100, get_si('plain'))
1019
 
        self.assertEqual(5000, get_si('si_k'))
1020
 
        self.assertEqual(5000, get_si('si_kb'))
1021
 
        self.assertEqual(5000000, get_si('si_m'))
1022
 
        self.assertEqual(5000000, get_si('si_mb'))
1023
 
        self.assertEqual(5000000000, get_si('si_g'))
1024
 
        self.assertEqual(5000000000, get_si('si_gb'))
1025
 
        self.assertEqual(None, get_si('non-exist'))
1026
 
        self.assertEqual(42, get_si('non-exist-with-default',  42))
1027
 
 
1028
1036
 
1029
1037
class TestSupressWarning(TestIniConfig):
1030
1038
 
1046
1054
class TestGetConfig(tests.TestCase):
1047
1055
 
1048
1056
    def test_constructs(self):
1049
 
        config.GlobalConfig()
 
1057
        my_config = config.GlobalConfig()
1050
1058
 
1051
1059
    def test_calls_read_filenames(self):
1052
1060
        # replace the class that is constructed, to check its parameters
1064
1072
 
1065
1073
class TestBranchConfig(tests.TestCaseWithTransport):
1066
1074
 
1067
 
    def test_constructs_valid(self):
 
1075
    def test_constructs(self):
1068
1076
        branch = FakeBranch()
1069
1077
        my_config = config.BranchConfig(branch)
1070
 
        self.assertIsNot(None, my_config)
1071
 
 
1072
 
    def test_constructs_error(self):
1073
1078
        self.assertRaises(TypeError, config.BranchConfig)
1074
1079
 
1075
1080
    def test_get_location_config(self):
1081
1086
 
1082
1087
    def test_get_config(self):
1083
1088
        """The Branch.get_config method works properly"""
1084
 
        b = controldir.ControlDir.create_standalone_workingtree('.').branch
 
1089
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
1085
1090
        my_config = b.get_config()
1086
1091
        self.assertIs(my_config.get_user_option('wacky'), None)
1087
1092
        my_config.set_user_option('wacky', 'unlikely')
1107
1112
        conf = config.LocationConfig.from_string(
1108
1113
            '[%s]\nnickname = foobar' % (local_url,),
1109
1114
            local_url, save=True)
1110
 
        self.assertIsNot(None, conf)
1111
1115
        self.assertEqual('foobar', branch.nick)
1112
1116
 
1113
1117
    def test_config_local_path(self):
1116
1120
        self.assertEqual('branch', branch.nick)
1117
1121
 
1118
1122
        local_path = osutils.getcwd().encode('utf8')
1119
 
        config.LocationConfig.from_string(
 
1123
        conf = config.LocationConfig.from_string(
1120
1124
            '[%s/branch]\nnickname = barry' % (local_path,),
1121
1125
            'branch',  save=True)
1122
 
        # Now the branch will find its nick via the location config
1123
1126
        self.assertEqual('barry', branch.nick)
1124
1127
 
1125
1128
    def test_config_creates_local(self):
1138
1141
        b = self.make_branch('!repo')
1139
1142
        self.assertEqual('!repo', b.get_config().get_nickname())
1140
1143
 
1141
 
    def test_autonick_uses_branch_name(self):
1142
 
        b = self.make_branch('foo', name='bar')
1143
 
        self.assertEqual('bar', b.get_config().get_nickname())
1144
 
 
1145
1144
    def test_warn_if_masked(self):
1146
1145
        warnings = []
1147
1146
        def warning(*args):
1187
1186
        my_config = config.GlobalConfig()
1188
1187
        self.assertEqual(None, my_config._get_user_id())
1189
1188
 
 
1189
    def test_configured_editor(self):
 
1190
        my_config = config.GlobalConfig.from_string(sample_config_text)
 
1191
        editor = self.applyDeprecated(
 
1192
            deprecated_in((2, 4, 0)), my_config.get_editor)
 
1193
        self.assertEqual('vim', editor)
 
1194
 
1190
1195
    def test_signatures_always(self):
1191
1196
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
1192
1197
        self.assertEqual(config.CHECK_NEVER,
1193
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1194
 
                             my_config.signature_checking))
 
1198
                         my_config.signature_checking())
1195
1199
        self.assertEqual(config.SIGN_ALWAYS,
1196
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1197
 
                             my_config.signing_policy))
1198
 
        self.assertEqual(True,
1199
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1200
 
                my_config.signature_needed))
 
1200
                         my_config.signing_policy())
 
1201
        self.assertEqual(True, my_config.signature_needed())
1201
1202
 
1202
1203
    def test_signatures_if_possible(self):
1203
1204
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
1204
1205
        self.assertEqual(config.CHECK_NEVER,
1205
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1206
 
                             my_config.signature_checking))
 
1206
                         my_config.signature_checking())
1207
1207
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
1208
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1209
 
                             my_config.signing_policy))
1210
 
        self.assertEqual(False, self.applyDeprecated(deprecated_in((2, 5, 0)),
1211
 
            my_config.signature_needed))
 
1208
                         my_config.signing_policy())
 
1209
        self.assertEqual(False, my_config.signature_needed())
1212
1210
 
1213
1211
    def test_signatures_ignore(self):
1214
1212
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
1215
1213
        self.assertEqual(config.CHECK_ALWAYS,
1216
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1217
 
                             my_config.signature_checking))
 
1214
                         my_config.signature_checking())
1218
1215
        self.assertEqual(config.SIGN_NEVER,
1219
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1220
 
                             my_config.signing_policy))
1221
 
        self.assertEqual(False, self.applyDeprecated(deprecated_in((2, 5, 0)),
1222
 
            my_config.signature_needed))
 
1216
                         my_config.signing_policy())
 
1217
        self.assertEqual(False, my_config.signature_needed())
1223
1218
 
1224
1219
    def _get_sample_config(self):
1225
1220
        my_config = config.GlobalConfig.from_string(sample_config_text)
1227
1222
 
1228
1223
    def test_gpg_signing_command(self):
1229
1224
        my_config = self._get_sample_config()
1230
 
        self.assertEqual("gnome-gpg",
1231
 
            self.applyDeprecated(
1232
 
                deprecated_in((2, 5, 0)), my_config.gpg_signing_command))
1233
 
        self.assertEqual(False, self.applyDeprecated(deprecated_in((2, 5, 0)),
1234
 
            my_config.signature_needed))
1235
 
 
1236
 
    def test_gpg_signing_key(self):
1237
 
        my_config = self._get_sample_config()
1238
 
        self.assertEqual("DD4D5088",
1239
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1240
 
                my_config.gpg_signing_key))
 
1225
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
 
1226
        self.assertEqual(False, my_config.signature_needed())
1241
1227
 
1242
1228
    def _get_empty_config(self):
1243
1229
        my_config = config.GlobalConfig()
1245
1231
 
1246
1232
    def test_gpg_signing_command_unset(self):
1247
1233
        my_config = self._get_empty_config()
1248
 
        self.assertEqual("gpg",
1249
 
            self.applyDeprecated(
1250
 
                deprecated_in((2, 5, 0)), my_config.gpg_signing_command))
 
1234
        self.assertEqual("gpg", my_config.gpg_signing_command())
1251
1235
 
1252
1236
    def test_get_user_option_default(self):
1253
1237
        my_config = self._get_empty_config()
1260
1244
 
1261
1245
    def test_post_commit_default(self):
1262
1246
        my_config = self._get_sample_config()
1263
 
        self.assertEqual(None,
1264
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1265
 
                                              my_config.post_commit))
 
1247
        self.assertEqual(None, my_config.post_commit())
1266
1248
 
1267
1249
    def test_configured_logformat(self):
1268
1250
        my_config = self._get_sample_config()
1269
 
        self.assertEqual("short",
1270
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1271
 
                                              my_config.log_format))
 
1251
        self.assertEqual("short", my_config.log_format())
1272
1252
 
1273
1253
    def test_configured_acceptable_keys(self):
1274
1254
        my_config = self._get_sample_config()
1275
 
        self.assertEqual("amy",
1276
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1277
 
                my_config.acceptable_keys))
 
1255
        self.assertEqual("amy", my_config.acceptable_keys())
1278
1256
 
1279
1257
    def test_configured_validate_signatures_in_log(self):
1280
1258
        my_config = self._get_sample_config()
1318
1296
        self.log(repr(tools))
1319
1297
        self.assertEqual(
1320
1298
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
1321
 
            u'sometool' : u'sometool {base} {this} {other} -o {result}',
1322
 
            u'newtool' : u'"newtool with spaces" {this_temp}'},
 
1299
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
1323
1300
            tools)
1324
1301
 
1325
1302
    def test_get_merge_tools_empty(self):
1373
1350
 
1374
1351
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
1375
1352
 
1376
 
    def test_constructs_valid(self):
1377
 
        config.LocationConfig('http://example.com')
1378
 
 
1379
 
    def test_constructs_error(self):
 
1353
    def test_constructs(self):
 
1354
        my_config = config.LocationConfig('http://example.com')
1380
1355
        self.assertRaises(TypeError, config.LocationConfig)
1381
1356
 
1382
1357
    def test_branch_calls_read_filenames(self):
1518
1493
        self.get_branch_config('http://www.example.com',
1519
1494
                                 global_config=sample_ignore_signatures)
1520
1495
        self.assertEqual(config.CHECK_ALWAYS,
1521
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1522
 
                             self.my_config.signature_checking))
 
1496
                         self.my_config.signature_checking())
1523
1497
        self.assertEqual(config.SIGN_NEVER,
1524
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1525
 
                             self.my_config.signing_policy))
 
1498
                         self.my_config.signing_policy())
1526
1499
 
1527
1500
    def test_signatures_never(self):
1528
1501
        self.get_branch_config('/a/c')
1529
1502
        self.assertEqual(config.CHECK_NEVER,
1530
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1531
 
                             self.my_config.signature_checking))
 
1503
                         self.my_config.signature_checking())
1532
1504
 
1533
1505
    def test_signatures_when_available(self):
1534
1506
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
1535
1507
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1536
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1537
 
                             self.my_config.signature_checking))
 
1508
                         self.my_config.signature_checking())
1538
1509
 
1539
1510
    def test_signatures_always(self):
1540
1511
        self.get_branch_config('/b')
1541
1512
        self.assertEqual(config.CHECK_ALWAYS,
1542
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1543
 
                         self.my_config.signature_checking))
 
1513
                         self.my_config.signature_checking())
1544
1514
 
1545
1515
    def test_gpg_signing_command(self):
1546
1516
        self.get_branch_config('/b')
1547
 
        self.assertEqual("gnome-gpg",
1548
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1549
 
                self.my_config.gpg_signing_command))
 
1517
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
1550
1518
 
1551
1519
    def test_gpg_signing_command_missing(self):
1552
1520
        self.get_branch_config('/a')
1553
 
        self.assertEqual("false",
1554
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1555
 
                self.my_config.gpg_signing_command))
1556
 
 
1557
 
    def test_gpg_signing_key(self):
1558
 
        self.get_branch_config('/b')
1559
 
        self.assertEqual("DD4D5088", self.applyDeprecated(deprecated_in((2, 5, 0)),
1560
 
            self.my_config.gpg_signing_key))
1561
 
 
1562
 
    def test_gpg_signing_key_default(self):
1563
 
        self.get_branch_config('/a')
1564
 
        self.assertEqual("erik@bagfors.nu",
1565
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1566
 
                self.my_config.gpg_signing_key))
 
1521
        self.assertEqual("false", self.my_config.gpg_signing_command())
1567
1522
 
1568
1523
    def test_get_user_option_global(self):
1569
1524
        self.get_branch_config('/a')
1657
1612
    def test_post_commit_default(self):
1658
1613
        self.get_branch_config('/a/c')
1659
1614
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1660
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1661
 
                                              self.my_config.post_commit))
 
1615
                         self.my_config.post_commit())
1662
1616
 
1663
1617
    def get_branch_config(self, location, global_config=None,
1664
1618
                          location_config=None):
1668
1622
        if location_config is None:
1669
1623
            location_config = sample_branches_text
1670
1624
 
1671
 
        config.GlobalConfig.from_string(global_config, save=True)
1672
 
        config.LocationConfig.from_string(location_config, my_branch.base,
1673
 
                                          save=True)
 
1625
        my_global_config = config.GlobalConfig.from_string(global_config,
 
1626
                                                           save=True)
 
1627
        my_location_config = config.LocationConfig.from_string(
 
1628
            location_config, my_branch.base, save=True)
1674
1629
        my_config = config.BranchConfig(my_branch)
1675
1630
        self.my_config = my_config
1676
1631
        self.my_location_config = my_config._get_location_config()
1741
1696
                          location_config=None, branch_data_config=None):
1742
1697
        my_branch = FakeBranch(location)
1743
1698
        if global_config is not None:
1744
 
            config.GlobalConfig.from_string(global_config, save=True)
 
1699
            my_global_config = config.GlobalConfig.from_string(global_config,
 
1700
                                                               save=True)
1745
1701
        if location_config is not None:
1746
 
            config.LocationConfig.from_string(location_config, my_branch.base,
1747
 
                                              save=True)
 
1702
            my_location_config = config.LocationConfig.from_string(
 
1703
                location_config, my_branch.base, save=True)
1748
1704
        my_config = config.BranchConfig(my_branch)
1749
1705
        if branch_data_config is not None:
1750
1706
            my_config.branch.control_files.files['branch.conf'] = \
1752
1708
        return my_config
1753
1709
 
1754
1710
    def test_user_id(self):
1755
 
        branch = FakeBranch()
 
1711
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
1756
1712
        my_config = config.BranchConfig(branch)
1757
 
        self.assertIsNot(None, my_config.username())
 
1713
        self.assertEqual("Robert Collins <robertc@example.net>",
 
1714
                         my_config.username())
1758
1715
        my_config.branch.control_files.files['email'] = "John"
1759
1716
        my_config.set_user_option('email',
1760
1717
                                  "Robert Collins <robertc@example.org>")
 
1718
        self.assertEqual("John", my_config.username())
 
1719
        del my_config.branch.control_files.files['email']
1761
1720
        self.assertEqual("Robert Collins <robertc@example.org>",
1762
 
                        my_config.username())
 
1721
                         my_config.username())
 
1722
 
 
1723
    def test_not_set_in_branch(self):
 
1724
        my_config = self.get_branch_config(global_config=sample_config_text)
 
1725
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
 
1726
                         my_config._get_user_id())
 
1727
        my_config.branch.control_files.files['email'] = "John"
 
1728
        self.assertEqual("John", my_config._get_user_id())
1763
1729
 
1764
1730
    def test_BZR_EMAIL_OVERRIDES(self):
1765
1731
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1771
1737
    def test_signatures_forced(self):
1772
1738
        my_config = self.get_branch_config(
1773
1739
            global_config=sample_always_signatures)
1774
 
        self.assertEqual(config.CHECK_NEVER,
1775
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1776
 
                my_config.signature_checking))
1777
 
        self.assertEqual(config.SIGN_ALWAYS,
1778
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1779
 
                my_config.signing_policy))
1780
 
        self.assertTrue(self.applyDeprecated(deprecated_in((2, 5, 0)),
1781
 
            my_config.signature_needed))
 
1740
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
1741
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
 
1742
        self.assertTrue(my_config.signature_needed())
1782
1743
 
1783
1744
    def test_signatures_forced_branch(self):
1784
1745
        my_config = self.get_branch_config(
1785
1746
            global_config=sample_ignore_signatures,
1786
1747
            branch_data_config=sample_always_signatures)
1787
 
        self.assertEqual(config.CHECK_NEVER,
1788
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1789
 
                my_config.signature_checking))
1790
 
        self.assertEqual(config.SIGN_ALWAYS,
1791
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1792
 
                my_config.signing_policy))
1793
 
        self.assertTrue(self.applyDeprecated(deprecated_in((2, 5, 0)),
1794
 
            my_config.signature_needed))
 
1748
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
1749
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
 
1750
        self.assertTrue(my_config.signature_needed())
1795
1751
 
1796
1752
    def test_gpg_signing_command(self):
1797
1753
        my_config = self.get_branch_config(
1798
1754
            global_config=sample_config_text,
1799
1755
            # branch data cannot set gpg_signing_command
1800
1756
            branch_data_config="gpg_signing_command=pgp")
1801
 
        self.assertEqual('gnome-gpg',
1802
 
            self.applyDeprecated(deprecated_in((2, 5, 0)),
1803
 
                my_config.gpg_signing_command))
 
1757
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1804
1758
 
1805
1759
    def test_get_user_option_global(self):
1806
1760
        my_config = self.get_branch_config(global_config=sample_config_text)
1813
1767
                                      location_config=sample_branches_text)
1814
1768
        self.assertEqual(my_config.branch.base, '/a/c')
1815
1769
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1816
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1817
 
                                              my_config.post_commit))
 
1770
                         my_config.post_commit())
1818
1771
        my_config.set_user_option('post_commit', 'rmtree_root')
1819
1772
        # post-commit is ignored when present in branch data
1820
1773
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1821
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1822
 
                                              my_config.post_commit))
 
1774
                         my_config.post_commit())
1823
1775
        my_config.set_user_option('post_commit', 'rmtree_root',
1824
1776
                                  store=config.STORE_LOCATION)
1825
 
        self.assertEqual('rmtree_root',
1826
 
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
1827
 
                                              my_config.post_commit))
 
1777
        self.assertEqual('rmtree_root', my_config.post_commit())
1828
1778
 
1829
1779
    def test_config_precedence(self):
1830
1780
        # FIXME: eager test, luckily no persitent config file makes it fail
1846
1796
            location='http://example.com/specific')
1847
1797
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1848
1798
 
 
1799
    def test_get_mail_client(self):
 
1800
        config = self.get_branch_config()
 
1801
        client = config.get_mail_client()
 
1802
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1803
 
 
1804
        # Specific clients
 
1805
        config.set_user_option('mail_client', 'evolution')
 
1806
        client = config.get_mail_client()
 
1807
        self.assertIsInstance(client, mail_client.Evolution)
 
1808
 
 
1809
        config.set_user_option('mail_client', 'kmail')
 
1810
        client = config.get_mail_client()
 
1811
        self.assertIsInstance(client, mail_client.KMail)
 
1812
 
 
1813
        config.set_user_option('mail_client', 'mutt')
 
1814
        client = config.get_mail_client()
 
1815
        self.assertIsInstance(client, mail_client.Mutt)
 
1816
 
 
1817
        config.set_user_option('mail_client', 'thunderbird')
 
1818
        client = config.get_mail_client()
 
1819
        self.assertIsInstance(client, mail_client.Thunderbird)
 
1820
 
 
1821
        # Generic options
 
1822
        config.set_user_option('mail_client', 'default')
 
1823
        client = config.get_mail_client()
 
1824
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1825
 
 
1826
        config.set_user_option('mail_client', 'editor')
 
1827
        client = config.get_mail_client()
 
1828
        self.assertIsInstance(client, mail_client.Editor)
 
1829
 
 
1830
        config.set_user_option('mail_client', 'mapi')
 
1831
        client = config.get_mail_client()
 
1832
        self.assertIsInstance(client, mail_client.MAPIClient)
 
1833
 
 
1834
        config.set_user_option('mail_client', 'xdg-email')
 
1835
        client = config.get_mail_client()
 
1836
        self.assertIsInstance(client, mail_client.XDGEmail)
 
1837
 
 
1838
        config.set_user_option('mail_client', 'firebird')
 
1839
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
 
1840
 
1849
1841
 
1850
1842
class TestMailAddressExtraction(tests.TestCase):
1851
1843
 
1922
1914
        conf = config.TransportConfig(t, 'foo.conf')
1923
1915
        self.assertRaises(errors.ParseConfigError, conf._get_configobj)
1924
1916
 
1925
 
    def test_load_permission_denied(self):
1926
 
        """Ensure we get an empty config file if the file is inaccessible."""
1927
 
        warnings = []
1928
 
        def warning(*args):
1929
 
            warnings.append(args[0] % args[1:])
1930
 
        self.overrideAttr(trace, 'warning', warning)
1931
 
 
1932
 
        class DenyingTransport(object):
1933
 
 
1934
 
            def __init__(self, base):
1935
 
                self.base = base
1936
 
 
1937
 
            def get_bytes(self, relpath):
1938
 
                raise errors.PermissionDenied(relpath, "")
1939
 
 
1940
 
        cfg = config.TransportConfig(
1941
 
            DenyingTransport("nonexisting://"), 'control.conf')
1942
 
        self.assertIs(None, cfg.get_option('non-existant', 'SECTION'))
1943
 
        self.assertEquals(
1944
 
            warnings,
1945
 
            [u'Permission denied while trying to open configuration file '
1946
 
             u'nonexisting:///control.conf.'])
1947
 
 
1948
1917
    def test_get_value(self):
1949
1918
        """Test that retreiving a value from a section is possible"""
1950
1919
        bzrdir_config = config.TransportConfig(self.get_transport('.'),
2138
2107
        self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2139
2108
 
2140
2109
    def test_get_hook_remote_bzrdir(self):
2141
 
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
 
2110
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2142
2111
        conf = remote_bzrdir._get_config()
2143
2112
        conf.set_option('remotedir', 'file')
2144
2113
        self.assertGetHook(conf, 'file', 'remotedir')
2166
2135
    def test_set_hook_remote_bzrdir(self):
2167
2136
        remote_branch = branch.Branch.open(self.get_url('tree'))
2168
2137
        self.addCleanup(remote_branch.lock_write().unlock)
2169
 
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
 
2138
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2170
2139
        self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2171
2140
 
2172
2141
    def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2189
2158
        self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2190
2159
 
2191
2160
    def test_load_hook_remote_bzrdir(self):
2192
 
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
 
2161
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2193
2162
        # The config file doesn't exist, set an option to force its creation
2194
2163
        conf = remote_bzrdir._get_config()
2195
2164
        conf.set_option('remotedir', 'file')
2220
2189
    def test_save_hook_remote_bzrdir(self):
2221
2190
        remote_branch = branch.Branch.open(self.get_url('tree'))
2222
2191
        self.addCleanup(remote_branch.lock_write().unlock)
2223
 
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
 
2192
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2224
2193
        self.assertSaveHook(remote_bzrdir._get_config())
2225
2194
 
2226
2195
 
2227
 
class TestOptionNames(tests.TestCase):
2228
 
 
2229
 
    def is_valid(self, name):
2230
 
        return config._option_ref_re.match('{%s}' % name) is not None
2231
 
 
2232
 
    def test_valid_names(self):
2233
 
        self.assertTrue(self.is_valid('foo'))
2234
 
        self.assertTrue(self.is_valid('foo.bar'))
2235
 
        self.assertTrue(self.is_valid('f1'))
2236
 
        self.assertTrue(self.is_valid('_'))
2237
 
        self.assertTrue(self.is_valid('__bar__'))
2238
 
        self.assertTrue(self.is_valid('a_'))
2239
 
        self.assertTrue(self.is_valid('a1'))
2240
 
 
2241
 
    def test_invalid_names(self):
2242
 
        self.assertFalse(self.is_valid(' foo'))
2243
 
        self.assertFalse(self.is_valid('foo '))
2244
 
        self.assertFalse(self.is_valid('1'))
2245
 
        self.assertFalse(self.is_valid('1,2'))
2246
 
        self.assertFalse(self.is_valid('foo$'))
2247
 
        self.assertFalse(self.is_valid('!foo'))
2248
 
        self.assertFalse(self.is_valid('foo.'))
2249
 
        self.assertFalse(self.is_valid('foo..bar'))
2250
 
        self.assertFalse(self.is_valid('{}'))
2251
 
        self.assertFalse(self.is_valid('{a}'))
2252
 
        self.assertFalse(self.is_valid('a\n'))
2253
 
 
2254
 
    def assertSingleGroup(self, reference):
2255
 
        # the regexp is used with split and as such should match the reference
2256
 
        # *only*, if more groups needs to be defined, (?:...) should be used.
2257
 
        m = config._option_ref_re.match('{a}')
2258
 
        self.assertLength(1, m.groups())
2259
 
 
2260
 
    def test_valid_references(self):
2261
 
        self.assertSingleGroup('{a}')
2262
 
        self.assertSingleGroup('{{a}}')
2263
 
 
2264
 
 
2265
2196
class TestOption(tests.TestCase):
2266
2197
 
2267
2198
    def test_default_value(self):
2268
2199
        opt = config.Option('foo', default='bar')
2269
2200
        self.assertEquals('bar', opt.get_default())
2270
2201
 
2271
 
    def test_callable_default_value(self):
2272
 
        def bar_as_unicode():
2273
 
            return u'bar'
2274
 
        opt = config.Option('foo', default=bar_as_unicode)
2275
 
        self.assertEquals('bar', opt.get_default())
2276
 
 
2277
 
    def test_default_value_from_env(self):
2278
 
        opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2279
 
        self.overrideEnv('FOO', 'quux')
2280
 
        # Env variable provides a default taking over the option one
2281
 
        self.assertEquals('quux', opt.get_default())
2282
 
 
2283
 
    def test_first_default_value_from_env_wins(self):
2284
 
        opt = config.Option('foo', default='bar',
2285
 
                            default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2286
 
        self.overrideEnv('FOO', 'foo')
2287
 
        self.overrideEnv('BAZ', 'baz')
2288
 
        # The first env var set wins
2289
 
        self.assertEquals('foo', opt.get_default())
2290
 
 
2291
 
    def test_not_supported_list_default_value(self):
2292
 
        self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2293
 
 
2294
 
    def test_not_supported_object_default_value(self):
2295
 
        self.assertRaises(AssertionError, config.Option, 'foo',
2296
 
                          default=object())
2297
 
 
2298
 
    def test_not_supported_callable_default_value_not_unicode(self):
2299
 
        def bar_not_unicode():
2300
 
            return 'bar'
2301
 
        opt = config.Option('foo', default=bar_not_unicode)
2302
 
        self.assertRaises(AssertionError, opt.get_default)
2303
 
 
2304
 
    def test_get_help_topic(self):
2305
 
        opt = config.Option('foo')
2306
 
        self.assertEquals('foo', opt.get_help_topic())
2307
 
 
2308
 
 
2309
 
class TestOptionConverterMixin(object):
2310
 
 
2311
 
    def assertConverted(self, expected, opt, value):
2312
 
        self.assertEquals(expected, opt.convert_from_unicode(None, value))
2313
 
 
2314
 
    def assertWarns(self, opt, value):
2315
 
        warnings = []
2316
 
        def warning(*args):
2317
 
            warnings.append(args[0] % args[1:])
2318
 
        self.overrideAttr(trace, 'warning', warning)
2319
 
        self.assertEquals(None, opt.convert_from_unicode(None, value))
2320
 
        self.assertLength(1, warnings)
2321
 
        self.assertEquals(
2322
 
            'Value "%s" is not valid for "%s"' % (value, opt.name),
2323
 
            warnings[0])
2324
 
 
2325
 
    def assertErrors(self, opt, value):
2326
 
        self.assertRaises(errors.ConfigOptionValueError,
2327
 
                          opt.convert_from_unicode, None, value)
2328
 
 
2329
 
    def assertConvertInvalid(self, opt, invalid_value):
2330
 
        opt.invalid = None
2331
 
        self.assertEquals(None, opt.convert_from_unicode(None, invalid_value))
2332
 
        opt.invalid = 'warning'
2333
 
        self.assertWarns(opt, invalid_value)
2334
 
        opt.invalid = 'error'
2335
 
        self.assertErrors(opt, invalid_value)
2336
 
 
2337
 
 
2338
 
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2339
 
 
2340
 
    def get_option(self):
2341
 
        return config.Option('foo', help='A boolean.',
2342
 
                             from_unicode=config.bool_from_store)
2343
 
 
2344
 
    def test_convert_invalid(self):
2345
 
        opt = self.get_option()
2346
 
        # A string that is not recognized as a boolean
2347
 
        self.assertConvertInvalid(opt, u'invalid-boolean')
2348
 
        # A list of strings is never recognized as a boolean
2349
 
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2350
 
 
2351
 
    def test_convert_valid(self):
2352
 
        opt = self.get_option()
2353
 
        self.assertConverted(True, opt, u'True')
2354
 
        self.assertConverted(True, opt, u'1')
2355
 
        self.assertConverted(False, opt, u'False')
2356
 
 
2357
 
 
2358
 
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2359
 
 
2360
 
    def get_option(self):
2361
 
        return config.Option('foo', help='An integer.',
2362
 
                             from_unicode=config.int_from_store)
2363
 
 
2364
 
    def test_convert_invalid(self):
2365
 
        opt = self.get_option()
2366
 
        # A string that is not recognized as an integer
2367
 
        self.assertConvertInvalid(opt, u'forty-two')
2368
 
        # A list of strings is never recognized as an integer
2369
 
        self.assertConvertInvalid(opt, [u'a', u'list'])
2370
 
 
2371
 
    def test_convert_valid(self):
2372
 
        opt = self.get_option()
2373
 
        self.assertConverted(16, opt, u'16')
2374
 
 
2375
 
 
2376
 
class TestOptionWithSIUnitConverter(tests.TestCase, TestOptionConverterMixin):
2377
 
 
2378
 
    def get_option(self):
2379
 
        return config.Option('foo', help='An integer in SI units.',
2380
 
                             from_unicode=config.int_SI_from_store)
2381
 
 
2382
 
    def test_convert_invalid(self):
2383
 
        opt = self.get_option()
2384
 
        self.assertConvertInvalid(opt, u'not-a-unit')
2385
 
        self.assertConvertInvalid(opt, u'Gb') # Forgot the int
2386
 
        self.assertConvertInvalid(opt, u'1b') # Forgot the unit
2387
 
        self.assertConvertInvalid(opt, u'1GG')
2388
 
        self.assertConvertInvalid(opt, u'1Mbb')
2389
 
        self.assertConvertInvalid(opt, u'1MM')
2390
 
 
2391
 
    def test_convert_valid(self):
2392
 
        opt = self.get_option()
2393
 
        self.assertConverted(int(5e3), opt, u'5kb')
2394
 
        self.assertConverted(int(5e6), opt, u'5M')
2395
 
        self.assertConverted(int(5e6), opt, u'5MB')
2396
 
        self.assertConverted(int(5e9), opt, u'5g')
2397
 
        self.assertConverted(int(5e9), opt, u'5gB')
2398
 
        self.assertConverted(100, opt, u'100')
2399
 
 
2400
 
 
2401
 
class TestListOption(tests.TestCase, TestOptionConverterMixin):
2402
 
 
2403
 
    def get_option(self):
2404
 
        return config.ListOption('foo', help='A list.')
2405
 
 
2406
 
    def test_convert_invalid(self):
2407
 
        opt = self.get_option()
2408
 
        # We don't even try to convert a list into a list, we only expect
2409
 
        # strings
2410
 
        self.assertConvertInvalid(opt, [1])
2411
 
        # No string is invalid as all forms can be converted to a list
2412
 
 
2413
 
    def test_convert_valid(self):
2414
 
        opt = self.get_option()
2415
 
        # An empty string is an empty list
2416
 
        self.assertConverted([], opt, '') # Using a bare str() just in case
2417
 
        self.assertConverted([], opt, u'')
2418
 
        # A boolean
2419
 
        self.assertConverted([u'True'], opt, u'True')
2420
 
        # An integer
2421
 
        self.assertConverted([u'42'], opt, u'42')
2422
 
        # A single string
2423
 
        self.assertConverted([u'bar'], opt, u'bar')
2424
 
 
2425
 
 
2426
 
class TestRegistryOption(tests.TestCase, TestOptionConverterMixin):
2427
 
 
2428
 
    def get_option(self, registry):
2429
 
        return config.RegistryOption('foo', registry,
2430
 
                help='A registry option.')
2431
 
 
2432
 
    def test_convert_invalid(self):
2433
 
        registry = _mod_registry.Registry()
2434
 
        opt = self.get_option(registry)
2435
 
        self.assertConvertInvalid(opt, [1])
2436
 
        self.assertConvertInvalid(opt, u"notregistered")
2437
 
 
2438
 
    def test_convert_valid(self):
2439
 
        registry = _mod_registry.Registry()
2440
 
        registry.register("someval", 1234)
2441
 
        opt = self.get_option(registry)
2442
 
        # Using a bare str() just in case
2443
 
        self.assertConverted(1234, opt, "someval")
2444
 
        self.assertConverted(1234, opt, u'someval')
2445
 
        self.assertConverted(None, opt, None)
2446
 
 
2447
 
    def test_help(self):
2448
 
        registry = _mod_registry.Registry()
2449
 
        registry.register("someval", 1234, help="some option")
2450
 
        registry.register("dunno", 1234, help="some other option")
2451
 
        opt = self.get_option(registry)
2452
 
        self.assertEquals(
2453
 
            'A registry option.\n'
2454
 
            '\n'
2455
 
            'The following values are supported:\n'
2456
 
            ' dunno - some other option\n'
2457
 
            ' someval - some option\n',
2458
 
            opt.help)
2459
 
 
2460
 
    def test_get_help_text(self):
2461
 
        registry = _mod_registry.Registry()
2462
 
        registry.register("someval", 1234, help="some option")
2463
 
        registry.register("dunno", 1234, help="some other option")
2464
 
        opt = self.get_option(registry)
2465
 
        self.assertEquals(
2466
 
            'A registry option.\n'
2467
 
            '\n'
2468
 
            'The following values are supported:\n'
2469
 
            ' dunno - some other option\n'
2470
 
            ' someval - some option\n',
2471
 
            opt.get_help_text())
2472
 
 
2473
2202
 
2474
2203
class TestOptionRegistry(tests.TestCase):
2475
2204
 
2476
2205
    def setUp(self):
2477
2206
        super(TestOptionRegistry, self).setUp()
2478
2207
        # Always start with an empty registry
2479
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
2208
        self.overrideAttr(config, 'option_registry', registry.Registry())
2480
2209
        self.registry = config.option_registry
2481
2210
 
2482
2211
    def test_register(self):
2483
2212
        opt = config.Option('foo')
2484
 
        self.registry.register(opt)
 
2213
        self.registry.register('foo', opt)
2485
2214
        self.assertIs(opt, self.registry.get('foo'))
2486
2215
 
 
2216
    lazy_option = config.Option('lazy_foo')
 
2217
 
 
2218
    def test_register_lazy(self):
 
2219
        self.registry.register_lazy('foo', self.__module__,
 
2220
                                    'TestOptionRegistry.lazy_option')
 
2221
        self.assertIs(self.lazy_option, self.registry.get('foo'))
 
2222
 
2487
2223
    def test_registered_help(self):
2488
 
        opt = config.Option('foo', help='A simple option')
2489
 
        self.registry.register(opt)
 
2224
        opt = config.Option('foo')
 
2225
        self.registry.register('foo', opt, help='A simple option')
2490
2226
        self.assertEquals('A simple option', self.registry.get_help('foo'))
2491
2227
 
2492
 
    def test_dont_register_illegal_name(self):
2493
 
        self.assertRaises(errors.IllegalOptionName,
2494
 
                          self.registry.register, config.Option(' foo'))
2495
 
        self.assertRaises(errors.IllegalOptionName,
2496
 
                          self.registry.register, config.Option('bar,'))
2497
 
 
2498
 
    lazy_option = config.Option('lazy_foo', help='Lazy help')
2499
 
 
2500
 
    def test_register_lazy(self):
2501
 
        self.registry.register_lazy('lazy_foo', self.__module__,
2502
 
                                    'TestOptionRegistry.lazy_option')
2503
 
        self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2504
 
 
2505
 
    def test_registered_lazy_help(self):
2506
 
        self.registry.register_lazy('lazy_foo', self.__module__,
2507
 
                                    'TestOptionRegistry.lazy_option')
2508
 
        self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2509
 
 
2510
 
    def test_dont_lazy_register_illegal_name(self):
2511
 
        # This is where the root cause of http://pad.lv/1235099 is better
2512
 
        # understood: 'register_lazy' doc string mentions that key should match
2513
 
        # the option name which indirectly requires that the option name is a
2514
 
        # valid python identifier. We violate that rule here (using a key that
2515
 
        # doesn't match the option name) to test the option name checking.
2516
 
        self.assertRaises(errors.IllegalOptionName,
2517
 
                          self.registry.register_lazy, ' foo', self.__module__,
2518
 
                          'TestOptionRegistry.lazy_option')
2519
 
        self.assertRaises(errors.IllegalOptionName,
2520
 
                          self.registry.register_lazy, '1,2', self.__module__,
2521
 
                          'TestOptionRegistry.lazy_option')
2522
 
 
2523
2228
 
2524
2229
class TestRegisteredOptions(tests.TestCase):
2525
2230
    """All registered options should verify some constraints."""
2538
2243
 
2539
2244
    def test_help_is_set(self):
2540
2245
        option_help = self.registry.get_help(self.option_name)
2541
 
        # Come on, think about the user, he really wants to know what the
 
2246
        self.assertNotEquals(None, option_help)
 
2247
        # Come on, think about the user, he really wants to know whst the
2542
2248
        # option is about
2543
 
        self.assertIsNot(None, option_help)
2544
2249
        self.assertNotEquals('', option_help)
2545
2250
 
2546
2251
 
2568
2273
 
2569
2274
class TestMutableSection(tests.TestCase):
2570
2275
 
2571
 
    scenarios = [('mutable',
2572
 
                  {'get_section':
2573
 
                       lambda opts: config.MutableSection('myID', opts)},),
2574
 
        ]
 
2276
    # FIXME: Parametrize so that all sections (including os.environ and the
 
2277
    # ones produced by Stores) run these tests -- vila 2011-04-01
2575
2278
 
2576
2279
    def test_set(self):
2577
2280
        a_dict = dict(foo='bar')
2578
 
        section = self.get_section(a_dict)
 
2281
        section = config.MutableSection('myID', a_dict)
2579
2282
        section.set('foo', 'new_value')
2580
2283
        self.assertEquals('new_value', section.get('foo'))
2581
2284
        # The change appears in the shared section
2586
2289
 
2587
2290
    def test_set_preserve_original_once(self):
2588
2291
        a_dict = dict(foo='bar')
2589
 
        section = self.get_section(a_dict)
 
2292
        section = config.MutableSection('myID', a_dict)
2590
2293
        section.set('foo', 'first_value')
2591
2294
        section.set('foo', 'second_value')
2592
2295
        # We keep track of the original value
2595
2298
 
2596
2299
    def test_remove(self):
2597
2300
        a_dict = dict(foo='bar')
2598
 
        section = self.get_section(a_dict)
 
2301
        section = config.MutableSection('myID', a_dict)
2599
2302
        section.remove('foo')
2600
2303
        # We get None for unknown options via the default value
2601
2304
        self.assertEquals(None, section.get('foo'))
2608
2311
 
2609
2312
    def test_remove_new_option(self):
2610
2313
        a_dict = dict()
2611
 
        section = self.get_section(a_dict)
 
2314
        section = config.MutableSection('myID', a_dict)
2612
2315
        section.set('foo', 'bar')
2613
2316
        section.remove('foo')
2614
2317
        self.assertFalse('foo' in section.options)
2618
2321
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2619
2322
 
2620
2323
 
2621
 
class TestCommandLineStore(tests.TestCase):
2622
 
 
2623
 
    def setUp(self):
2624
 
        super(TestCommandLineStore, self).setUp()
2625
 
        self.store = config.CommandLineStore()
2626
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2627
 
 
2628
 
    def get_section(self):
2629
 
        """Get the unique section for the command line overrides."""
2630
 
        sections = list(self.store.get_sections())
2631
 
        self.assertLength(1, sections)
2632
 
        store, section = sections[0]
2633
 
        self.assertEquals(self.store, store)
2634
 
        return section
2635
 
 
2636
 
    def test_no_override(self):
2637
 
        self.store._from_cmdline([])
2638
 
        section = self.get_section()
2639
 
        self.assertLength(0, list(section.iter_option_names()))
2640
 
 
2641
 
    def test_simple_override(self):
2642
 
        self.store._from_cmdline(['a=b'])
2643
 
        section = self.get_section()
2644
 
        self.assertEqual('b', section.get('a'))
2645
 
 
2646
 
    def test_list_override(self):
2647
 
        opt = config.ListOption('l')
2648
 
        config.option_registry.register(opt)
2649
 
        self.store._from_cmdline(['l=1,2,3'])
2650
 
        val = self.get_section().get('l')
2651
 
        self.assertEqual('1,2,3', val)
2652
 
        # Reminder: lists should be registered as such explicitely, otherwise
2653
 
        # the conversion needs to be done afterwards.
2654
 
        self.assertEqual(['1', '2', '3'],
2655
 
                         opt.convert_from_unicode(self.store, val))
2656
 
 
2657
 
    def test_multiple_overrides(self):
2658
 
        self.store._from_cmdline(['a=b', 'x=y'])
2659
 
        section = self.get_section()
2660
 
        self.assertEquals('b', section.get('a'))
2661
 
        self.assertEquals('y', section.get('x'))
2662
 
 
2663
 
    def test_wrong_syntax(self):
2664
 
        self.assertRaises(errors.BzrCommandError,
2665
 
                          self.store._from_cmdline, ['a=b', 'c'])
2666
 
 
2667
 
class TestStoreMinimalAPI(tests.TestCaseWithTransport):
2668
 
 
2669
 
    scenarios = [(key, {'get_store': builder}) for key, builder
2670
 
                 in config.test_store_builder_registry.iteritems()] + [
2671
 
        ('cmdline', {'get_store': lambda test: config.CommandLineStore()})]
2672
 
 
2673
 
    def test_id(self):
2674
 
        store = self.get_store(self)
2675
 
        if type(store) == config.TransportIniFileStore:
2676
 
            raise tests.TestNotApplicable(
2677
 
                "%s is not a concrete Store implementation"
2678
 
                " so it doesn't need an id" % (store.__class__.__name__,))
2679
 
        self.assertIsNot(None, store.id)
2680
 
 
2681
 
 
2682
2324
class TestStore(tests.TestCaseWithTransport):
2683
2325
 
2684
 
    def assertSectionContent(self, expected, (store, section)):
 
2326
    def assertSectionContent(self, expected, section):
2685
2327
        """Assert that some options have the proper values in a section."""
2686
2328
        expected_name, expected_options = expected
2687
2329
        self.assertEquals(expected_name, section.id)
2695
2337
    scenarios = [(key, {'get_store': builder}) for key, builder
2696
2338
                 in config.test_store_builder_registry.iteritems()]
2697
2339
 
 
2340
    def setUp(self):
 
2341
        super(TestReadonlyStore, self).setUp()
 
2342
 
2698
2343
    def test_building_delays_load(self):
2699
2344
        store = self.get_store(self)
2700
2345
        self.assertEquals(False, store.is_loaded())
2726
2371
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2727
2372
 
2728
2373
 
2729
 
class TestStoreQuoting(TestStore):
2730
 
 
2731
 
    scenarios = [(key, {'get_store': builder}) for key, builder
2732
 
                 in config.test_store_builder_registry.iteritems()]
2733
 
 
2734
 
    def setUp(self):
2735
 
        super(TestStoreQuoting, self).setUp()
2736
 
        self.store = self.get_store(self)
2737
 
        # We need a loaded store but any content will do
2738
 
        self.store._load_from_string('')
2739
 
 
2740
 
    def assertIdempotent(self, s):
2741
 
        """Assert that quoting an unquoted string is a no-op and vice-versa.
2742
 
 
2743
 
        What matters here is that option values, as they appear in a store, can
2744
 
        be safely round-tripped out of the store and back.
2745
 
 
2746
 
        :param s: A string, quoted if required.
2747
 
        """
2748
 
        self.assertEquals(s, self.store.quote(self.store.unquote(s)))
2749
 
        self.assertEquals(s, self.store.unquote(self.store.quote(s)))
2750
 
 
2751
 
    def test_empty_string(self):
2752
 
        if isinstance(self.store, config.IniFileStore):
2753
 
            # configobj._quote doesn't handle empty values
2754
 
            self.assertRaises(AssertionError,
2755
 
                              self.assertIdempotent, '')
2756
 
        else:
2757
 
            self.assertIdempotent('')
2758
 
        # But quoted empty strings are ok
2759
 
        self.assertIdempotent('""')
2760
 
 
2761
 
    def test_embedded_spaces(self):
2762
 
        self.assertIdempotent('" a b c "')
2763
 
 
2764
 
    def test_embedded_commas(self):
2765
 
        self.assertIdempotent('" a , b c "')
2766
 
 
2767
 
    def test_simple_comma(self):
2768
 
        if isinstance(self.store, config.IniFileStore):
2769
 
            # configobj requires that lists are special-cased
2770
 
           self.assertRaises(AssertionError,
2771
 
                             self.assertIdempotent, ',')
2772
 
        else:
2773
 
            self.assertIdempotent(',')
2774
 
        # When a single comma is required, quoting is also required
2775
 
        self.assertIdempotent('","')
2776
 
 
2777
 
    def test_list(self):
2778
 
        if isinstance(self.store, config.IniFileStore):
2779
 
            # configobj requires that lists are special-cased
2780
 
            self.assertRaises(AssertionError,
2781
 
                              self.assertIdempotent, 'a,b')
2782
 
        else:
2783
 
            self.assertIdempotent('a,b')
2784
 
 
2785
 
 
2786
 
class TestDictFromStore(tests.TestCase):
2787
 
 
2788
 
    def test_unquote_not_string(self):
2789
 
        conf = config.MemoryStack('x=2\n[a_section]\na=1\n')
2790
 
        value = conf.get('a_section')
2791
 
        # Urgh, despite 'conf' asking for the no-name section, we get the
2792
 
        # content of another section as a dict o_O
2793
 
        self.assertEquals({'a': '1'}, value)
2794
 
        unquoted = conf.store.unquote(value)
2795
 
        # Which cannot be unquoted but shouldn't crash either (the use cases
2796
 
        # are getting the value or displaying it. In the later case, '%s' will
2797
 
        # do).
2798
 
        self.assertEquals({'a': '1'}, unquoted)
2799
 
        self.assertEquals("{u'a': u'1'}", '%s' % (unquoted,))
2800
 
 
2801
 
 
2802
2374
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2803
 
    """Simulate loading a config store with content of various encodings.
 
2375
    """Simulate loading a config store without content of various encodings.
2804
2376
 
2805
2377
    All files produced by bzr are in utf8 content.
2806
2378
 
2819
2391
        utf8_content = unicode_content.encode('utf8')
2820
2392
        # Store the raw content in the config file
2821
2393
        t.put_bytes('foo.conf', utf8_content)
2822
 
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2394
        store = config.IniFileStore(t, 'foo.conf')
2823
2395
        store.load()
2824
2396
        stack = config.Stack([store.get_sections], store)
2825
2397
        self.assertEquals(unicode_user, stack.get('user'))
2828
2400
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2829
2401
        t = self.get_transport()
2830
2402
        t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2831
 
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2403
        store = config.IniFileStore(t, 'foo.conf')
2832
2404
        self.assertRaises(errors.ConfigContentError, store.load)
2833
2405
 
2834
2406
    def test_load_erroneous_content(self):
2835
2407
        """Ensure we display a proper error on content that can't be parsed."""
2836
2408
        t = self.get_transport()
2837
2409
        t.put_bytes('foo.conf', '[open_section\n')
2838
 
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2410
        store = config.IniFileStore(t, 'foo.conf')
2839
2411
        self.assertRaises(errors.ParseConfigError, store.load)
2840
2412
 
2841
 
    def test_load_permission_denied(self):
2842
 
        """Ensure we get warned when trying to load an inaccessible file."""
2843
 
        warnings = []
2844
 
        def warning(*args):
2845
 
            warnings.append(args[0] % args[1:])
2846
 
        self.overrideAttr(trace, 'warning', warning)
2847
 
 
2848
 
        t = self.get_transport()
2849
 
 
2850
 
        def get_bytes(relpath):
2851
 
            raise errors.PermissionDenied(relpath, "")
2852
 
        t.get_bytes = get_bytes
2853
 
        store = config.TransportIniFileStore(t, 'foo.conf')
2854
 
        self.assertRaises(errors.PermissionDenied, store.load)
2855
 
        self.assertEquals(
2856
 
            warnings,
2857
 
            [u'Permission denied while trying to load configuration store %s.'
2858
 
             % store.external_url()])
2859
 
 
2860
2413
 
2861
2414
class TestIniConfigContent(tests.TestCaseWithTransport):
2862
 
    """Simulate loading a IniBasedConfig with content of various encodings.
 
2415
    """Simulate loading a IniBasedConfig without content of various encodings.
2863
2416
 
2864
2417
    All files produced by bzr are in utf8 content.
2865
2418
 
2920
2473
        store.save()
2921
2474
        self.assertEquals(False, self.has_store(store))
2922
2475
 
2923
 
    def test_mutable_section_shared(self):
2924
 
        store = self.get_store(self)
2925
 
        store._load_from_string('foo=bar\n')
2926
 
        # FIXME: There should be a better way than relying on the test
2927
 
        # parametrization to identify branch.conf -- vila 2011-0526
2928
 
        if self.store_id in ('branch', 'remote_branch'):
2929
 
            # branch stores requires write locked branches
2930
 
            self.addCleanup(store.branch.lock_write().unlock)
2931
 
        section1 = store.get_mutable_section(None)
2932
 
        section2 = store.get_mutable_section(None)
2933
 
        # If we get different sections, different callers won't share the
2934
 
        # modification
2935
 
        self.assertIs(section1, section2)
2936
 
 
2937
2476
    def test_save_emptied_succeeds(self):
2938
2477
        store = self.get_store(self)
2939
2478
        store._load_from_string('foo=bar\n')
2940
 
        # FIXME: There should be a better way than relying on the test
2941
 
        # parametrization to identify branch.conf -- vila 2011-0526
2942
 
        if self.store_id in ('branch', 'remote_branch'):
2943
 
            # branch stores requires write locked branches
2944
 
            self.addCleanup(store.branch.lock_write().unlock)
2945
2479
        section = store.get_mutable_section(None)
2946
2480
        section.remove('foo')
2947
2481
        store.save()
2968
2502
 
2969
2503
    def test_set_option_in_empty_store(self):
2970
2504
        store = self.get_store(self)
2971
 
        # FIXME: There should be a better way than relying on the test
2972
 
        # parametrization to identify branch.conf -- vila 2011-0526
2973
 
        if self.store_id in ('branch', 'remote_branch'):
2974
 
            # branch stores requires write locked branches
2975
 
            self.addCleanup(store.branch.lock_write().unlock)
2976
2505
        section = store.get_mutable_section(None)
2977
2506
        section.set('foo', 'bar')
2978
2507
        store.save()
2984
2513
    def test_set_option_in_default_section(self):
2985
2514
        store = self.get_store(self)
2986
2515
        store._load_from_string('')
2987
 
        # FIXME: There should be a better way than relying on the test
2988
 
        # parametrization to identify branch.conf -- vila 2011-0526
2989
 
        if self.store_id in ('branch', 'remote_branch'):
2990
 
            # branch stores requires write locked branches
2991
 
            self.addCleanup(store.branch.lock_write().unlock)
2992
2516
        section = store.get_mutable_section(None)
2993
2517
        section.set('foo', 'bar')
2994
2518
        store.save()
3000
2524
    def test_set_option_in_named_section(self):
3001
2525
        store = self.get_store(self)
3002
2526
        store._load_from_string('')
3003
 
        # FIXME: There should be a better way than relying on the test
3004
 
        # parametrization to identify branch.conf -- vila 2011-0526
3005
 
        if self.store_id in ('branch', 'remote_branch'):
3006
 
            # branch stores requires write locked branches
3007
 
            self.addCleanup(store.branch.lock_write().unlock)
3008
2527
        section = store.get_mutable_section('baz')
3009
2528
        section.set('foo', 'bar')
3010
2529
        store.save()
3014
2533
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
3015
2534
 
3016
2535
    def test_load_hook(self):
3017
 
        # First, we need to ensure that the store exists
 
2536
        # We first needs to ensure that the store exists
3018
2537
        store = self.get_store(self)
3019
 
        # FIXME: There should be a better way than relying on the test
3020
 
        # parametrization to identify branch.conf -- vila 2011-0526
3021
 
        if self.store_id in ('branch', 'remote_branch'):
3022
 
            # branch stores requires write locked branches
3023
 
            self.addCleanup(store.branch.lock_write().unlock)
3024
2538
        section = store.get_mutable_section('baz')
3025
2539
        section.set('foo', 'bar')
3026
2540
        store.save()
3042
2556
        config.ConfigHooks.install_named_hook('save', hook, None)
3043
2557
        self.assertLength(0, calls)
3044
2558
        store = self.get_store(self)
3045
 
        # FIXME: There should be a better way than relying on the test
3046
 
        # parametrization to identify branch.conf -- vila 2011-0526
3047
 
        if self.store_id in ('branch', 'remote_branch'):
3048
 
            # branch stores requires write locked branches
3049
 
            self.addCleanup(store.branch.lock_write().unlock)
3050
2559
        section = store.get_mutable_section('baz')
3051
2560
        section.set('foo', 'bar')
3052
2561
        store.save()
3053
2562
        self.assertLength(1, calls)
3054
2563
        self.assertEquals((store,), calls[0])
3055
2564
 
3056
 
    def test_set_mark_dirty(self):
3057
 
        stack = config.MemoryStack('')
3058
 
        self.assertLength(0, stack.store.dirty_sections)
3059
 
        stack.set('foo', 'baz')
3060
 
        self.assertLength(1, stack.store.dirty_sections)
3061
 
        self.assertTrue(stack.store._need_saving())
3062
 
 
3063
 
    def test_remove_mark_dirty(self):
3064
 
        stack = config.MemoryStack('foo=bar')
3065
 
        self.assertLength(0, stack.store.dirty_sections)
3066
 
        stack.remove('foo')
3067
 
        self.assertLength(1, stack.store.dirty_sections)
3068
 
        self.assertTrue(stack.store._need_saving())
3069
 
 
3070
 
 
3071
 
class TestStoreSaveChanges(tests.TestCaseWithTransport):
3072
 
    """Tests that config changes are kept in memory and saved on-demand."""
3073
 
 
3074
 
    def setUp(self):
3075
 
        super(TestStoreSaveChanges, self).setUp()
3076
 
        self.transport = self.get_transport()
3077
 
        # Most of the tests involve two stores pointing to the same persistent
3078
 
        # storage to observe the effects of concurrent changes
3079
 
        self.st1 = config.TransportIniFileStore(self.transport, 'foo.conf')
3080
 
        self.st2 = config.TransportIniFileStore(self.transport, 'foo.conf')
3081
 
        self.warnings = []
3082
 
        def warning(*args):
3083
 
            self.warnings.append(args[0] % args[1:])
3084
 
        self.overrideAttr(trace, 'warning', warning)
3085
 
 
3086
 
    def has_store(self, store):
3087
 
        store_basename = urlutils.relative_url(self.transport.external_url(),
3088
 
                                               store.external_url())
3089
 
        return self.transport.has(store_basename)
3090
 
 
3091
 
    def get_stack(self, store):
3092
 
        # Any stack will do as long as it uses the right store, just a single
3093
 
        # no-name section is enough
3094
 
        return config.Stack([store.get_sections], store)
3095
 
 
3096
 
    def test_no_changes_no_save(self):
3097
 
        s = self.get_stack(self.st1)
3098
 
        s.store.save_changes()
3099
 
        self.assertEquals(False, self.has_store(self.st1))
3100
 
 
3101
 
    def test_unrelated_concurrent_update(self):
3102
 
        s1 = self.get_stack(self.st1)
3103
 
        s2 = self.get_stack(self.st2)
3104
 
        s1.set('foo', 'bar')
3105
 
        s2.set('baz', 'quux')
3106
 
        s1.store.save()
3107
 
        # Changes don't propagate magically
3108
 
        self.assertEquals(None, s1.get('baz'))
3109
 
        s2.store.save_changes()
3110
 
        self.assertEquals('quux', s2.get('baz'))
3111
 
        # Changes are acquired when saving
3112
 
        self.assertEquals('bar', s2.get('foo'))
3113
 
        # Since there is no overlap, no warnings are emitted
3114
 
        self.assertLength(0, self.warnings)
3115
 
 
3116
 
    def test_concurrent_update_modified(self):
3117
 
        s1 = self.get_stack(self.st1)
3118
 
        s2 = self.get_stack(self.st2)
3119
 
        s1.set('foo', 'bar')
3120
 
        s2.set('foo', 'baz')
3121
 
        s1.store.save()
3122
 
        # Last speaker wins
3123
 
        s2.store.save_changes()
3124
 
        self.assertEquals('baz', s2.get('foo'))
3125
 
        # But the user get a warning
3126
 
        self.assertLength(1, self.warnings)
3127
 
        warning = self.warnings[0]
3128
 
        self.assertStartsWith(warning, 'Option foo in section None')
3129
 
        self.assertEndsWith(warning, 'was changed from <CREATED> to bar.'
3130
 
                            ' The baz value will be saved.')
3131
 
 
3132
 
    def test_concurrent_deletion(self):
3133
 
        self.st1._load_from_string('foo=bar')
3134
 
        self.st1.save()
3135
 
        s1 = self.get_stack(self.st1)
3136
 
        s2 = self.get_stack(self.st2)
3137
 
        s1.remove('foo')
3138
 
        s2.remove('foo')
3139
 
        s1.store.save_changes()
3140
 
        # No warning yet
3141
 
        self.assertLength(0, self.warnings)
3142
 
        s2.store.save_changes()
3143
 
        # Now we get one
3144
 
        self.assertLength(1, self.warnings)
3145
 
        warning = self.warnings[0]
3146
 
        self.assertStartsWith(warning, 'Option foo in section None')
3147
 
        self.assertEndsWith(warning, 'was changed from bar to <CREATED>.'
3148
 
                            ' The <DELETED> value will be saved.')
3149
 
 
3150
 
 
3151
 
class TestQuotingIniFileStore(tests.TestCaseWithTransport):
3152
 
 
3153
 
    def get_store(self):
3154
 
        return config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3155
 
 
3156
 
    def test_get_quoted_string(self):
3157
 
        store = self.get_store()
3158
 
        store._load_from_string('foo= " abc "')
3159
 
        stack = config.Stack([store.get_sections])
3160
 
        self.assertEquals(' abc ', stack.get('foo'))
3161
 
 
3162
 
    def test_set_quoted_string(self):
3163
 
        store = self.get_store()
3164
 
        stack = config.Stack([store.get_sections], store)
3165
 
        stack.set('foo', ' a b c ')
3166
 
        store.save()
3167
 
        self.assertFileEqual('foo = " a b c "' + os.linesep, 'foo.conf')
3168
 
 
3169
 
 
3170
 
class TestTransportIniFileStore(TestStore):
 
2565
 
 
2566
class TestIniFileStore(TestStore):
3171
2567
 
3172
2568
    def test_loading_unknown_file_fails(self):
3173
 
        store = config.TransportIniFileStore(self.get_transport(),
3174
 
            'I-do-not-exist')
 
2569
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
3175
2570
        self.assertRaises(errors.NoSuchFile, store.load)
3176
2571
 
3177
2572
    def test_invalid_content(self):
3178
 
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
2573
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
3179
2574
        self.assertEquals(False, store.is_loaded())
3180
2575
        exc = self.assertRaises(
3181
2576
            errors.ParseConfigError, store._load_from_string,
3189
2584
        # option names share the same name space...)
3190
2585
        # FIXME: This should be fixed by forbidding dicts as values ?
3191
2586
        # -- vila 2011-04-05
3192
 
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
2587
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
3193
2588
        store._load_from_string('''
3194
2589
foo=bar
3195
2590
l=1,2
3205
2600
        sections = list(store.get_sections())
3206
2601
        self.assertLength(4, sections)
3207
2602
        # The default section has no name.
3208
 
        # List values are provided as strings and need to be explicitly
3209
 
        # converted by specifying from_unicode=list_from_store at option
3210
 
        # registration
3211
 
        self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
 
2603
        # List values are provided as lists
 
2604
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
3212
2605
                                  sections[0])
3213
2606
        self.assertSectionContent(
3214
2607
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
3244
2637
 
3245
2638
    def setUp(self):
3246
2639
        super(TestConcurrentStoreUpdates, self).setUp()
 
2640
        self._content = 'one=1\ntwo=2\n'
3247
2641
        self.stack = self.get_stack(self)
3248
2642
        if not isinstance(self.stack, config._CompatibleStack):
3249
2643
            raise tests.TestNotApplicable(
3250
2644
                '%s is not meant to be compatible with the old config design'
3251
2645
                % (self.stack,))
3252
 
        self.stack.set('one', '1')
3253
 
        self.stack.set('two', '2')
 
2646
        self.stack.store._load_from_string(self._content)
3254
2647
        # Flush the store
3255
2648
        self.stack.store.save()
3256
2649
 
3360
2753
    # FIXME: It may be worth looking into removing the lock dir when it's not
3361
2754
    # needed anymore and look at possible fallouts for concurrent lockers. This
3362
2755
    # will matter if/when we use config files outside of bazaar directories
3363
 
    # (.bazaar or .bzr) -- vila 20110-04-111
 
2756
    # (.bazaar or .bzr) -- vila 20110-04-11
3364
2757
 
3365
2758
 
3366
2759
class TestSectionMatcher(TestStore):
3367
2760
 
3368
 
    scenarios = [('location', {'matcher': config.LocationMatcher}),
3369
 
                 ('id', {'matcher': config.NameMatcher}),]
 
2761
    scenarios = [('location', {'matcher': config.LocationMatcher})]
3370
2762
 
3371
 
    def setUp(self):
3372
 
        super(TestSectionMatcher, self).setUp()
3373
 
        # Any simple store is good enough
3374
 
        self.get_store = config.test_store_builder_registry.get('configobj')
 
2763
    def get_store(self, file_name):
 
2764
        return config.IniFileStore(self.get_readonly_transport(), file_name)
3375
2765
 
3376
2766
    def test_no_matches_for_empty_stores(self):
3377
 
        store = self.get_store(self)
 
2767
        store = self.get_store('foo.conf')
3378
2768
        store._load_from_string('')
3379
2769
        matcher = self.matcher(store, '/bar')
3380
2770
        self.assertEquals([], list(matcher.get_sections()))
3381
2771
 
3382
2772
    def test_build_doesnt_load_store(self):
3383
 
        store = self.get_store(self)
3384
 
        self.matcher(store, '/bar')
 
2773
        store = self.get_store('foo.conf')
 
2774
        matcher = self.matcher(store, '/bar')
3385
2775
        self.assertFalse(store.is_loaded())
3386
2776
 
3387
2777
 
3389
2779
 
3390
2780
    def get_section(self, options, extra_path):
3391
2781
        section = config.Section('foo', options)
3392
 
        return config.LocationSection(section, extra_path)
 
2782
        # We don't care about the length so we use '0'
 
2783
        return config.LocationSection(section, 0, extra_path)
3393
2784
 
3394
2785
    def test_simple_option(self):
3395
2786
        section = self.get_section({'foo': 'bar'}, '')
3409
2800
 
3410
2801
class TestLocationMatcher(TestStore):
3411
2802
 
3412
 
    def setUp(self):
3413
 
        super(TestLocationMatcher, self).setUp()
3414
 
        # Any simple store is good enough
3415
 
        self.get_store = config.test_store_builder_registry.get('configobj')
3416
 
 
3417
 
    def test_unrelated_section_excluded(self):
3418
 
        store = self.get_store(self)
3419
 
        store._load_from_string('''
3420
 
[/foo]
3421
 
section=/foo
3422
 
[/foo/baz]
3423
 
section=/foo/baz
3424
 
[/foo/bar]
3425
 
section=/foo/bar
3426
 
[/foo/bar/baz]
3427
 
section=/foo/bar/baz
3428
 
[/quux/quux]
3429
 
section=/quux/quux
3430
 
''')
3431
 
        self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3432
 
                           '/quux/quux'],
3433
 
                          [section.id for _, section in store.get_sections()])
3434
 
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
3435
 
        sections = [section for _, section in matcher.get_sections()]
3436
 
        self.assertEquals(['/foo/bar', '/foo'],
3437
 
                          [section.id for section in sections])
3438
 
        self.assertEquals(['quux', 'bar/quux'],
3439
 
                          [section.extra_path for section in sections])
 
2803
    def get_store(self, file_name):
 
2804
        return config.IniFileStore(self.get_readonly_transport(), file_name)
3440
2805
 
3441
2806
    def test_more_specific_sections_first(self):
3442
 
        store = self.get_store(self)
 
2807
        store = self.get_store('foo.conf')
3443
2808
        store._load_from_string('''
3444
2809
[/foo]
3445
2810
section=/foo
3447
2812
section=/foo/bar
3448
2813
''')
3449
2814
        self.assertEquals(['/foo', '/foo/bar'],
3450
 
                          [section.id for _, section in store.get_sections()])
 
2815
                          [section.id for section in store.get_sections()])
3451
2816
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
3452
 
        sections = [section for _, section in matcher.get_sections()]
 
2817
        sections = list(matcher.get_sections())
 
2818
        self.assertEquals([3, 2],
 
2819
                          [section.length for section in sections])
3453
2820
        self.assertEquals(['/foo/bar', '/foo'],
3454
2821
                          [section.id for section in sections])
3455
2822
        self.assertEquals(['baz', 'bar/baz'],
3458
2825
    def test_appendpath_in_no_name_section(self):
3459
2826
        # It's a bit weird to allow appendpath in a no-name section, but
3460
2827
        # someone may found a use for it
3461
 
        store = self.get_store(self)
 
2828
        store = self.get_store('foo.conf')
3462
2829
        store._load_from_string('''
3463
2830
foo=bar
3464
2831
foo:policy = appendpath
3466
2833
        matcher = config.LocationMatcher(store, 'dir/subdir')
3467
2834
        sections = list(matcher.get_sections())
3468
2835
        self.assertLength(1, sections)
3469
 
        self.assertEquals('bar/dir/subdir', sections[0][1].get('foo'))
 
2836
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
3470
2837
 
3471
2838
    def test_file_urls_are_normalized(self):
3472
 
        store = self.get_store(self)
 
2839
        store = self.get_store('foo.conf')
3473
2840
        if sys.platform == 'win32':
3474
2841
            expected_url = 'file:///C:/dir/subdir'
3475
2842
            expected_location = 'C:/dir/subdir'
3479
2846
        matcher = config.LocationMatcher(store, expected_url)
3480
2847
        self.assertEquals(expected_location, matcher.location)
3481
2848
 
3482
 
    def test_branch_name_colo(self):
3483
 
        store = self.get_store(self)
3484
 
        store._load_from_string(dedent("""\
3485
 
            [/]
3486
 
            push_location=my{branchname}
3487
 
        """))
3488
 
        matcher = config.LocationMatcher(store, 'file:///,branch=example%3c')
3489
 
        self.assertEqual('example<', matcher.branch_name)
3490
 
        ((_, section),) = matcher.get_sections()
3491
 
        self.assertEqual('example<', section.locals['branchname'])
3492
 
 
3493
 
    def test_branch_name_basename(self):
3494
 
        store = self.get_store(self)
3495
 
        store._load_from_string(dedent("""\
3496
 
            [/]
3497
 
            push_location=my{branchname}
3498
 
        """))
3499
 
        matcher = config.LocationMatcher(store, 'file:///parent/example%3c')
3500
 
        self.assertEqual('example<', matcher.branch_name)
3501
 
        ((_, section),) = matcher.get_sections()
3502
 
        self.assertEqual('example<', section.locals['branchname'])
3503
 
 
3504
 
 
3505
 
class TestStartingPathMatcher(TestStore):
3506
 
 
3507
 
    def setUp(self):
3508
 
        super(TestStartingPathMatcher, self).setUp()
3509
 
        # Any simple store is good enough
3510
 
        self.store = config.IniFileStore()
3511
 
 
3512
 
    def assertSectionIDs(self, expected, location, content):
3513
 
        self.store._load_from_string(content)
3514
 
        matcher = config.StartingPathMatcher(self.store, location)
3515
 
        sections = list(matcher.get_sections())
3516
 
        self.assertLength(len(expected), sections)
3517
 
        self.assertEqual(expected, [section.id for _, section in sections])
3518
 
        return sections
3519
 
 
3520
 
    def test_empty(self):
3521
 
        self.assertSectionIDs([], self.get_url(), '')
3522
 
 
3523
 
    def test_url_vs_local_paths(self):
3524
 
        # The matcher location is an url and the section names are local paths
3525
 
        self.assertSectionIDs(['/foo/bar', '/foo'],
3526
 
                              'file:///foo/bar/baz', '''\
3527
 
[/foo]
3528
 
[/foo/bar]
3529
 
''')
3530
 
 
3531
 
    def test_local_path_vs_url(self):
3532
 
        # The matcher location is a local path and the section names are urls
3533
 
        self.assertSectionIDs(['file:///foo/bar', 'file:///foo'],
3534
 
                              '/foo/bar/baz', '''\
3535
 
[file:///foo]
3536
 
[file:///foo/bar]
3537
 
''')
3538
 
 
3539
 
 
3540
 
    def test_no_name_section_included_when_present(self):
3541
 
        # Note that other tests will cover the case where the no-name section
3542
 
        # is empty and as such, not included.
3543
 
        sections = self.assertSectionIDs(['/foo/bar', '/foo', None],
3544
 
                                         '/foo/bar/baz', '''\
3545
 
option = defined so the no-name section exists
3546
 
[/foo]
3547
 
[/foo/bar]
3548
 
''')
3549
 
        self.assertEquals(['baz', 'bar/baz', '/foo/bar/baz'],
3550
 
                          [s.locals['relpath'] for _, s in sections])
3551
 
 
3552
 
    def test_order_reversed(self):
3553
 
        self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
3554
 
[/foo]
3555
 
[/foo/bar]
3556
 
''')
3557
 
 
3558
 
    def test_unrelated_section_excluded(self):
3559
 
        self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
3560
 
[/foo]
3561
 
[/foo/qux]
3562
 
[/foo/bar]
3563
 
''')
3564
 
 
3565
 
    def test_glob_included(self):
3566
 
        sections = self.assertSectionIDs(['/foo/*/baz', '/foo/b*', '/foo'],
3567
 
                                         '/foo/bar/baz', '''\
3568
 
[/foo]
3569
 
[/foo/qux]
3570
 
[/foo/b*]
3571
 
[/foo/*/baz]
3572
 
''')
3573
 
        # Note that 'baz' as a relpath for /foo/b* is not fully correct, but
3574
 
        # nothing really is... as far using {relpath} to append it to something
3575
 
        # else, this seems good enough though.
3576
 
        self.assertEquals(['', 'baz', 'bar/baz'],
3577
 
                          [s.locals['relpath'] for _, s in sections])
3578
 
 
3579
 
    def test_respect_order(self):
3580
 
        self.assertSectionIDs(['/foo', '/foo/b*', '/foo/*/baz'],
3581
 
                              '/foo/bar/baz', '''\
3582
 
[/foo/*/baz]
3583
 
[/foo/qux]
3584
 
[/foo/b*]
3585
 
[/foo]
3586
 
''')
3587
 
 
3588
 
 
3589
 
class TestNameMatcher(TestStore):
3590
 
 
3591
 
    def setUp(self):
3592
 
        super(TestNameMatcher, self).setUp()
3593
 
        self.matcher = config.NameMatcher
3594
 
        # Any simple store is good enough
3595
 
        self.get_store = config.test_store_builder_registry.get('configobj')
3596
 
 
3597
 
    def get_matching_sections(self, name):
3598
 
        store = self.get_store(self)
3599
 
        store._load_from_string('''
3600
 
[foo]
3601
 
option=foo
3602
 
[foo/baz]
3603
 
option=foo/baz
3604
 
[bar]
3605
 
option=bar
3606
 
''')
3607
 
        matcher = self.matcher(store, name)
3608
 
        return list(matcher.get_sections())
3609
 
 
3610
 
    def test_matching(self):
3611
 
        sections = self.get_matching_sections('foo')
3612
 
        self.assertLength(1, sections)
3613
 
        self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3614
 
 
3615
 
    def test_not_matching(self):
3616
 
        sections = self.get_matching_sections('baz')
3617
 
        self.assertLength(0, sections)
3618
 
 
3619
 
 
3620
 
class TestBaseStackGet(tests.TestCase):
3621
 
 
3622
 
    def setUp(self):
3623
 
        super(TestBaseStackGet, self).setUp()
3624
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3625
 
 
3626
 
    def test_get_first_definition(self):
3627
 
        store1 = config.IniFileStore()
3628
 
        store1._load_from_string('foo=bar')
3629
 
        store2 = config.IniFileStore()
3630
 
        store2._load_from_string('foo=baz')
3631
 
        conf = config.Stack([store1.get_sections, store2.get_sections])
3632
 
        self.assertEquals('bar', conf.get('foo'))
 
2849
 
 
2850
class TestStackGet(tests.TestCase):
 
2851
 
 
2852
    # FIXME: This should be parametrized for all known Stack or dedicated
 
2853
    # paramerized tests created to avoid bloating -- vila 2011-03-31
 
2854
 
 
2855
    def test_single_config_get(self):
 
2856
        conf = dict(foo='bar')
 
2857
        conf_stack = config.Stack([conf])
 
2858
        self.assertEquals('bar', conf_stack.get('foo'))
3633
2859
 
3634
2860
    def test_get_with_registered_default_value(self):
3635
 
        config.option_registry.register(config.Option('foo', default='bar'))
3636
 
        conf_stack = config.Stack([])
 
2861
        conf_stack = config.Stack([dict()])
 
2862
        opt = config.Option('foo', default='bar')
 
2863
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
2864
        config.option_registry.register('foo', opt)
3637
2865
        self.assertEquals('bar', conf_stack.get('foo'))
3638
2866
 
3639
2867
    def test_get_without_registered_default_value(self):
3640
 
        config.option_registry.register(config.Option('foo'))
3641
 
        conf_stack = config.Stack([])
 
2868
        conf_stack = config.Stack([dict()])
 
2869
        opt = config.Option('foo')
 
2870
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
2871
        config.option_registry.register('foo', opt)
3642
2872
        self.assertEquals(None, conf_stack.get('foo'))
3643
2873
 
3644
2874
    def test_get_without_default_value_for_not_registered(self):
3645
 
        conf_stack = config.Stack([])
 
2875
        conf_stack = config.Stack([dict()])
 
2876
        opt = config.Option('foo')
 
2877
        self.overrideAttr(config, 'option_registry', registry.Registry())
3646
2878
        self.assertEquals(None, conf_stack.get('foo'))
3647
2879
 
 
2880
    def test_get_first_definition(self):
 
2881
        conf1 = dict(foo='bar')
 
2882
        conf2 = dict(foo='baz')
 
2883
        conf_stack = config.Stack([conf1, conf2])
 
2884
        self.assertEquals('bar', conf_stack.get('foo'))
 
2885
 
 
2886
    def test_get_embedded_definition(self):
 
2887
        conf1 = dict(yy='12')
 
2888
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
 
2889
        conf_stack = config.Stack([conf1, conf2])
 
2890
        self.assertEquals('baz', conf_stack.get('foo'))
 
2891
 
3648
2892
    def test_get_for_empty_section_callable(self):
3649
2893
        conf_stack = config.Stack([lambda : []])
3650
2894
        self.assertEquals(None, conf_stack.get('foo'))
3651
2895
 
3652
2896
    def test_get_for_broken_callable(self):
3653
2897
        # Trying to use and invalid callable raises an exception on first use
3654
 
        conf_stack = config.Stack([object])
 
2898
        conf_stack = config.Stack([lambda : object()])
3655
2899
        self.assertRaises(TypeError, conf_stack.get, 'foo')
3656
2900
 
3657
2901
 
3658
 
class TestStackWithSimpleStore(tests.TestCase):
3659
 
 
3660
 
    def setUp(self):
3661
 
        super(TestStackWithSimpleStore, self).setUp()
3662
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3663
 
        self.registry = config.option_registry
3664
 
 
3665
 
    def get_conf(self, content=None):
3666
 
        return config.MemoryStack(content)
3667
 
 
3668
 
    def test_override_value_from_env(self):
3669
 
        self.overrideEnv('FOO', None)
3670
 
        self.registry.register(
3671
 
            config.Option('foo', default='bar', override_from_env=['FOO']))
3672
 
        self.overrideEnv('FOO', 'quux')
3673
 
        # Env variable provides a default taking over the option one
3674
 
        conf = self.get_conf('foo=store')
3675
 
        self.assertEquals('quux', conf.get('foo'))
3676
 
 
3677
 
    def test_first_override_value_from_env_wins(self):
3678
 
        self.overrideEnv('NO_VALUE', None)
3679
 
        self.overrideEnv('FOO', None)
3680
 
        self.overrideEnv('BAZ', None)
3681
 
        self.registry.register(
3682
 
            config.Option('foo', default='bar',
3683
 
                          override_from_env=['NO_VALUE', 'FOO', 'BAZ']))
3684
 
        self.overrideEnv('FOO', 'foo')
3685
 
        self.overrideEnv('BAZ', 'baz')
3686
 
        # The first env var set wins
3687
 
        conf = self.get_conf('foo=store')
3688
 
        self.assertEquals('foo', conf.get('foo'))
3689
 
 
3690
 
 
3691
 
class TestMemoryStack(tests.TestCase):
3692
 
 
3693
 
    def test_get(self):
3694
 
        conf = config.MemoryStack('foo=bar')
3695
 
        self.assertEquals('bar', conf.get('foo'))
3696
 
 
3697
 
    def test_set(self):
3698
 
        conf = config.MemoryStack('foo=bar')
3699
 
        conf.set('foo', 'baz')
3700
 
        self.assertEquals('baz', conf.get('foo'))
3701
 
 
3702
 
    def test_no_content(self):
3703
 
        conf = config.MemoryStack()
3704
 
        # No content means no loading
3705
 
        self.assertFalse(conf.store.is_loaded())
3706
 
        self.assertRaises(NotImplementedError, conf.get, 'foo')
3707
 
        # But a content can still be provided
3708
 
        conf.store._load_from_string('foo=bar')
3709
 
        self.assertEquals('bar', conf.get('foo'))
3710
 
 
3711
 
 
3712
 
class TestStackIterSections(tests.TestCase):
3713
 
 
3714
 
    def test_empty_stack(self):
3715
 
        conf = config.Stack([])
3716
 
        sections = list(conf.iter_sections())
3717
 
        self.assertLength(0, sections)
3718
 
 
3719
 
    def test_empty_store(self):
3720
 
        store = config.IniFileStore()
3721
 
        store._load_from_string('')
3722
 
        conf = config.Stack([store.get_sections])
3723
 
        sections = list(conf.iter_sections())
3724
 
        self.assertLength(0, sections)
3725
 
 
3726
 
    def test_simple_store(self):
3727
 
        store = config.IniFileStore()
3728
 
        store._load_from_string('foo=bar')
3729
 
        conf = config.Stack([store.get_sections])
3730
 
        tuples = list(conf.iter_sections())
3731
 
        self.assertLength(1, tuples)
3732
 
        (found_store, found_section) = tuples[0]
3733
 
        self.assertIs(store, found_store)
3734
 
 
3735
 
    def test_two_stores(self):
3736
 
        store1 = config.IniFileStore()
3737
 
        store1._load_from_string('foo=bar')
3738
 
        store2 = config.IniFileStore()
3739
 
        store2._load_from_string('bar=qux')
3740
 
        conf = config.Stack([store1.get_sections, store2.get_sections])
3741
 
        tuples = list(conf.iter_sections())
3742
 
        self.assertLength(2, tuples)
3743
 
        self.assertIs(store1, tuples[0][0])
3744
 
        self.assertIs(store2, tuples[1][0])
3745
 
 
3746
 
 
3747
2902
class TestStackWithTransport(tests.TestCaseWithTransport):
3748
2903
 
3749
2904
    scenarios = [(key, {'get_stack': builder}) for key, builder
3754
2909
 
3755
2910
    def test_build_stack(self):
3756
2911
        # Just a smoke test to help debug builders
3757
 
        self.get_stack(self)
 
2912
        stack = self.get_stack(self)
3758
2913
 
3759
2914
 
3760
2915
class TestStackGet(TestStackWithTransport):
3761
2916
 
3762
 
    def setUp(self):
3763
 
        super(TestStackGet, self).setUp()
3764
 
        self.conf = self.get_stack(self)
3765
 
 
3766
2917
    def test_get_for_empty_stack(self):
3767
 
        self.assertEquals(None, self.conf.get('foo'))
 
2918
        conf = self.get_stack(self)
 
2919
        self.assertEquals(None, conf.get('foo'))
3768
2920
 
3769
2921
    def test_get_hook(self):
3770
 
        self.conf.set('foo', 'bar')
 
2922
        conf = self.get_stack(self)
 
2923
        conf.store._load_from_string('foo=bar')
3771
2924
        calls = []
3772
2925
        def hook(*args):
3773
2926
            calls.append(args)
3774
2927
        config.ConfigHooks.install_named_hook('get', hook, None)
3775
2928
        self.assertLength(0, calls)
3776
 
        value = self.conf.get('foo')
 
2929
        value = conf.get('foo')
3777
2930
        self.assertEquals('bar', value)
3778
2931
        self.assertLength(1, calls)
3779
 
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3780
 
 
3781
 
 
3782
 
class TestStackGetWithConverter(tests.TestCase):
3783
 
 
3784
 
    def setUp(self):
3785
 
        super(TestStackGetWithConverter, self).setUp()
3786
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3787
 
        self.registry = config.option_registry
3788
 
 
3789
 
    def get_conf(self, content=None):
3790
 
        return config.MemoryStack(content)
3791
 
 
3792
 
    def register_bool_option(self, name, default=None, default_from_env=None):
3793
 
        b = config.Option(name, help='A boolean.',
3794
 
                          default=default, default_from_env=default_from_env,
3795
 
                          from_unicode=config.bool_from_store)
3796
 
        self.registry.register(b)
3797
 
 
3798
 
    def test_get_default_bool_None(self):
3799
 
        self.register_bool_option('foo')
3800
 
        conf = self.get_conf('')
3801
 
        self.assertEquals(None, conf.get('foo'))
3802
 
 
3803
 
    def test_get_default_bool_True(self):
3804
 
        self.register_bool_option('foo', u'True')
3805
 
        conf = self.get_conf('')
3806
 
        self.assertEquals(True, conf.get('foo'))
3807
 
 
3808
 
    def test_get_default_bool_False(self):
3809
 
        self.register_bool_option('foo', False)
3810
 
        conf = self.get_conf('')
3811
 
        self.assertEquals(False, conf.get('foo'))
3812
 
 
3813
 
    def test_get_default_bool_False_as_string(self):
3814
 
        self.register_bool_option('foo', u'False')
3815
 
        conf = self.get_conf('')
3816
 
        self.assertEquals(False, conf.get('foo'))
3817
 
 
3818
 
    def test_get_default_bool_from_env_converted(self):
3819
 
        self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3820
 
        self.overrideEnv('FOO', 'False')
3821
 
        conf = self.get_conf('')
3822
 
        self.assertEquals(False, conf.get('foo'))
3823
 
 
3824
 
    def test_get_default_bool_when_conversion_fails(self):
3825
 
        self.register_bool_option('foo', default='True')
3826
 
        conf = self.get_conf('foo=invalid boolean')
3827
 
        self.assertEquals(True, conf.get('foo'))
3828
 
 
3829
 
    def register_integer_option(self, name,
3830
 
                                default=None, default_from_env=None):
3831
 
        i = config.Option(name, help='An integer.',
3832
 
                          default=default, default_from_env=default_from_env,
3833
 
                          from_unicode=config.int_from_store)
3834
 
        self.registry.register(i)
3835
 
 
3836
 
    def test_get_default_integer_None(self):
3837
 
        self.register_integer_option('foo')
3838
 
        conf = self.get_conf('')
3839
 
        self.assertEquals(None, conf.get('foo'))
3840
 
 
3841
 
    def test_get_default_integer(self):
3842
 
        self.register_integer_option('foo', 42)
3843
 
        conf = self.get_conf('')
3844
 
        self.assertEquals(42, conf.get('foo'))
3845
 
 
3846
 
    def test_get_default_integer_as_string(self):
3847
 
        self.register_integer_option('foo', u'42')
3848
 
        conf = self.get_conf('')
3849
 
        self.assertEquals(42, conf.get('foo'))
3850
 
 
3851
 
    def test_get_default_integer_from_env(self):
3852
 
        self.register_integer_option('foo', default_from_env=['FOO'])
3853
 
        self.overrideEnv('FOO', '18')
3854
 
        conf = self.get_conf('')
3855
 
        self.assertEquals(18, conf.get('foo'))
3856
 
 
3857
 
    def test_get_default_integer_when_conversion_fails(self):
3858
 
        self.register_integer_option('foo', default='12')
3859
 
        conf = self.get_conf('foo=invalid integer')
3860
 
        self.assertEquals(12, conf.get('foo'))
3861
 
 
3862
 
    def register_list_option(self, name, default=None, default_from_env=None):
3863
 
        l = config.ListOption(name, help='A list.', default=default,
3864
 
                              default_from_env=default_from_env)
3865
 
        self.registry.register(l)
3866
 
 
3867
 
    def test_get_default_list_None(self):
3868
 
        self.register_list_option('foo')
3869
 
        conf = self.get_conf('')
3870
 
        self.assertEquals(None, conf.get('foo'))
3871
 
 
3872
 
    def test_get_default_list_empty(self):
3873
 
        self.register_list_option('foo', '')
3874
 
        conf = self.get_conf('')
3875
 
        self.assertEquals([], conf.get('foo'))
3876
 
 
3877
 
    def test_get_default_list_from_env(self):
3878
 
        self.register_list_option('foo', default_from_env=['FOO'])
3879
 
        self.overrideEnv('FOO', '')
3880
 
        conf = self.get_conf('')
3881
 
        self.assertEquals([], conf.get('foo'))
3882
 
 
3883
 
    def test_get_with_list_converter_no_item(self):
3884
 
        self.register_list_option('foo', None)
3885
 
        conf = self.get_conf('foo=,')
3886
 
        self.assertEquals([], conf.get('foo'))
3887
 
 
3888
 
    def test_get_with_list_converter_many_items(self):
3889
 
        self.register_list_option('foo', None)
3890
 
        conf = self.get_conf('foo=m,o,r,e')
3891
 
        self.assertEquals(['m', 'o', 'r', 'e'], conf.get('foo'))
3892
 
 
3893
 
    def test_get_with_list_converter_embedded_spaces_many_items(self):
3894
 
        self.register_list_option('foo', None)
3895
 
        conf = self.get_conf('foo=" bar", "baz "')
3896
 
        self.assertEquals([' bar', 'baz '], conf.get('foo'))
3897
 
 
3898
 
    def test_get_with_list_converter_stripped_spaces_many_items(self):
3899
 
        self.register_list_option('foo', None)
3900
 
        conf = self.get_conf('foo= bar ,  baz ')
3901
 
        self.assertEquals(['bar', 'baz'], conf.get('foo'))
3902
 
 
3903
 
 
3904
 
class TestIterOptionRefs(tests.TestCase):
3905
 
    """iter_option_refs is a bit unusual, document some cases."""
3906
 
 
3907
 
    def assertRefs(self, expected, string):
3908
 
        self.assertEquals(expected, list(config.iter_option_refs(string)))
3909
 
 
3910
 
    def test_empty(self):
3911
 
        self.assertRefs([(False, '')], '')
3912
 
 
3913
 
    def test_no_refs(self):
3914
 
        self.assertRefs([(False, 'foo bar')], 'foo bar')
3915
 
 
3916
 
    def test_single_ref(self):
3917
 
        self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
3918
 
 
3919
 
    def test_broken_ref(self):
3920
 
        self.assertRefs([(False, '{foo')], '{foo')
3921
 
 
3922
 
    def test_embedded_ref(self):
3923
 
        self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
3924
 
                        '{{foo}}')
3925
 
 
3926
 
    def test_two_refs(self):
3927
 
        self.assertRefs([(False, ''), (True, '{foo}'),
3928
 
                         (False, ''), (True, '{bar}'),
3929
 
                         (False, ''),],
3930
 
                        '{foo}{bar}')
3931
 
 
3932
 
    def test_newline_in_refs_are_not_matched(self):
3933
 
        self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
3934
 
 
3935
 
 
3936
 
class TestStackExpandOptions(tests.TestCaseWithTransport):
3937
 
 
3938
 
    def setUp(self):
3939
 
        super(TestStackExpandOptions, self).setUp()
3940
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3941
 
        self.registry = config.option_registry
3942
 
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3943
 
        self.conf = config.Stack([store.get_sections], store)
3944
 
 
3945
 
    def assertExpansion(self, expected, string, env=None):
3946
 
        self.assertEquals(expected, self.conf.expand_options(string, env))
3947
 
 
3948
 
    def test_no_expansion(self):
3949
 
        self.assertExpansion('foo', 'foo')
3950
 
 
3951
 
    def test_expand_default_value(self):
3952
 
        self.conf.store._load_from_string('bar=baz')
3953
 
        self.registry.register(config.Option('foo', default=u'{bar}'))
3954
 
        self.assertEquals('baz', self.conf.get('foo', expand=True))
3955
 
 
3956
 
    def test_expand_default_from_env(self):
3957
 
        self.conf.store._load_from_string('bar=baz')
3958
 
        self.registry.register(config.Option('foo', default_from_env=['FOO']))
3959
 
        self.overrideEnv('FOO', '{bar}')
3960
 
        self.assertEquals('baz', self.conf.get('foo', expand=True))
3961
 
 
3962
 
    def test_expand_default_on_failed_conversion(self):
3963
 
        self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
3964
 
        self.registry.register(
3965
 
            config.Option('foo', default=u'{bar}',
3966
 
                          from_unicode=config.int_from_store))
3967
 
        self.assertEquals(42, self.conf.get('foo', expand=True))
3968
 
 
3969
 
    def test_env_adding_options(self):
3970
 
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3971
 
 
3972
 
    def test_env_overriding_options(self):
3973
 
        self.conf.store._load_from_string('foo=baz')
3974
 
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3975
 
 
3976
 
    def test_simple_ref(self):
3977
 
        self.conf.store._load_from_string('foo=xxx')
3978
 
        self.assertExpansion('xxx', '{foo}')
3979
 
 
3980
 
    def test_unknown_ref(self):
3981
 
        self.assertRaises(errors.ExpandingUnknownOption,
3982
 
                          self.conf.expand_options, '{foo}')
3983
 
 
3984
 
    def test_illegal_def_is_ignored(self):
3985
 
        self.assertExpansion('{1,2}', '{1,2}')
3986
 
        self.assertExpansion('{ }', '{ }')
3987
 
        self.assertExpansion('${Foo,f}', '${Foo,f}')
3988
 
 
3989
 
    def test_indirect_ref(self):
3990
 
        self.conf.store._load_from_string('''
3991
 
foo=xxx
3992
 
bar={foo}
3993
 
''')
3994
 
        self.assertExpansion('xxx', '{bar}')
3995
 
 
3996
 
    def test_embedded_ref(self):
3997
 
        self.conf.store._load_from_string('''
3998
 
foo=xxx
3999
 
bar=foo
4000
 
''')
4001
 
        self.assertExpansion('xxx', '{{bar}}')
4002
 
 
4003
 
    def test_simple_loop(self):
4004
 
        self.conf.store._load_from_string('foo={foo}')
4005
 
        self.assertRaises(errors.OptionExpansionLoop,
4006
 
                          self.conf.expand_options, '{foo}')
4007
 
 
4008
 
    def test_indirect_loop(self):
4009
 
        self.conf.store._load_from_string('''
4010
 
foo={bar}
4011
 
bar={baz}
4012
 
baz={foo}''')
4013
 
        e = self.assertRaises(errors.OptionExpansionLoop,
4014
 
                              self.conf.expand_options, '{foo}')
4015
 
        self.assertEquals('foo->bar->baz', e.refs)
4016
 
        self.assertEquals('{foo}', e.string)
4017
 
 
4018
 
    def test_list(self):
4019
 
        self.conf.store._load_from_string('''
4020
 
foo=start
4021
 
bar=middle
4022
 
baz=end
4023
 
list={foo},{bar},{baz}
4024
 
''')
4025
 
        self.registry.register(
4026
 
            config.ListOption('list'))
4027
 
        self.assertEquals(['start', 'middle', 'end'],
4028
 
                           self.conf.get('list', expand=True))
4029
 
 
4030
 
    def test_cascading_list(self):
4031
 
        self.conf.store._load_from_string('''
4032
 
foo=start,{bar}
4033
 
bar=middle,{baz}
4034
 
baz=end
4035
 
list={foo}
4036
 
''')
4037
 
        self.registry.register(config.ListOption('list'))
4038
 
        # Register an intermediate option as a list to ensure no conversion
4039
 
        # happen while expanding. Conversion should only occur for the original
4040
 
        # option ('list' here).
4041
 
        self.registry.register(config.ListOption('baz'))
4042
 
        self.assertEquals(['start', 'middle', 'end'],
4043
 
                           self.conf.get('list', expand=True))
4044
 
 
4045
 
    def test_pathologically_hidden_list(self):
4046
 
        self.conf.store._load_from_string('''
4047
 
foo=bin
4048
 
bar=go
4049
 
start={foo
4050
 
middle=},{
4051
 
end=bar}
4052
 
hidden={start}{middle}{end}
4053
 
''')
4054
 
        # What matters is what the registration says, the conversion happens
4055
 
        # only after all expansions have been performed
4056
 
        self.registry.register(config.ListOption('hidden'))
4057
 
        self.assertEquals(['bin', 'go'],
4058
 
                          self.conf.get('hidden', expand=True))
4059
 
 
4060
 
 
4061
 
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
4062
 
 
4063
 
    def setUp(self):
4064
 
        super(TestStackCrossSectionsExpand, self).setUp()
4065
 
 
4066
 
    def get_config(self, location, string):
4067
 
        if string is None:
4068
 
            string = ''
4069
 
        # Since we don't save the config we won't strictly require to inherit
4070
 
        # from TestCaseInTempDir, but an error occurs so quickly...
4071
 
        c = config.LocationStack(location)
4072
 
        c.store._load_from_string(string)
4073
 
        return c
4074
 
 
4075
 
    def test_dont_cross_unrelated_section(self):
4076
 
        c = self.get_config('/another/branch/path','''
4077
 
[/one/branch/path]
4078
 
foo = hello
4079
 
bar = {foo}/2
4080
 
 
4081
 
[/another/branch/path]
4082
 
bar = {foo}/2
4083
 
''')
4084
 
        self.assertRaises(errors.ExpandingUnknownOption,
4085
 
                          c.get, 'bar', expand=True)
4086
 
 
4087
 
    def test_cross_related_sections(self):
4088
 
        c = self.get_config('/project/branch/path','''
4089
 
[/project]
4090
 
foo = qu
4091
 
 
4092
 
[/project/branch/path]
4093
 
bar = {foo}ux
4094
 
''')
4095
 
        self.assertEquals('quux', c.get('bar', expand=True))
4096
 
 
4097
 
 
4098
 
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
4099
 
 
4100
 
    def test_cross_global_locations(self):
4101
 
        l_store = config.LocationStore()
4102
 
        l_store._load_from_string('''
4103
 
[/branch]
4104
 
lfoo = loc-foo
4105
 
lbar = {gbar}
4106
 
''')
4107
 
        l_store.save()
4108
 
        g_store = config.GlobalStore()
4109
 
        g_store._load_from_string('''
4110
 
[DEFAULT]
4111
 
gfoo = {lfoo}
4112
 
gbar = glob-bar
4113
 
''')
4114
 
        g_store.save()
4115
 
        stack = config.LocationStack('/branch')
4116
 
        self.assertEquals('glob-bar', stack.get('lbar', expand=True))
4117
 
        self.assertEquals('loc-foo', stack.get('gfoo', expand=True))
4118
 
 
4119
 
 
4120
 
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
4121
 
 
4122
 
    def test_expand_locals_empty(self):
4123
 
        l_store = config.LocationStore()
4124
 
        l_store._load_from_string('''
4125
 
[/home/user/project]
4126
 
base = {basename}
4127
 
rel = {relpath}
4128
 
''')
4129
 
        l_store.save()
4130
 
        stack = config.LocationStack('/home/user/project/')
4131
 
        self.assertEquals('', stack.get('base', expand=True))
4132
 
        self.assertEquals('', stack.get('rel', expand=True))
4133
 
 
4134
 
    def test_expand_basename_locally(self):
4135
 
        l_store = config.LocationStore()
4136
 
        l_store._load_from_string('''
4137
 
[/home/user/project]
4138
 
bfoo = {basename}
4139
 
''')
4140
 
        l_store.save()
4141
 
        stack = config.LocationStack('/home/user/project/branch')
4142
 
        self.assertEquals('branch', stack.get('bfoo', expand=True))
4143
 
 
4144
 
    def test_expand_basename_locally_longer_path(self):
4145
 
        l_store = config.LocationStore()
4146
 
        l_store._load_from_string('''
4147
 
[/home/user]
4148
 
bfoo = {basename}
4149
 
''')
4150
 
        l_store.save()
4151
 
        stack = config.LocationStack('/home/user/project/dir/branch')
4152
 
        self.assertEquals('branch', stack.get('bfoo', expand=True))
4153
 
 
4154
 
    def test_expand_relpath_locally(self):
4155
 
        l_store = config.LocationStore()
4156
 
        l_store._load_from_string('''
4157
 
[/home/user/project]
4158
 
lfoo = loc-foo/{relpath}
4159
 
''')
4160
 
        l_store.save()
4161
 
        stack = config.LocationStack('/home/user/project/branch')
4162
 
        self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
4163
 
 
4164
 
    def test_expand_relpath_unknonw_in_global(self):
4165
 
        g_store = config.GlobalStore()
4166
 
        g_store._load_from_string('''
4167
 
[DEFAULT]
4168
 
gfoo = {relpath}
4169
 
''')
4170
 
        g_store.save()
4171
 
        stack = config.LocationStack('/home/user/project/branch')
4172
 
        self.assertRaises(errors.ExpandingUnknownOption,
4173
 
                          stack.get, 'gfoo', expand=True)
4174
 
 
4175
 
    def test_expand_local_option_locally(self):
4176
 
        l_store = config.LocationStore()
4177
 
        l_store._load_from_string('''
4178
 
[/home/user/project]
4179
 
lfoo = loc-foo/{relpath}
4180
 
lbar = {gbar}
4181
 
''')
4182
 
        l_store.save()
4183
 
        g_store = config.GlobalStore()
4184
 
        g_store._load_from_string('''
4185
 
[DEFAULT]
4186
 
gfoo = {lfoo}
4187
 
gbar = glob-bar
4188
 
''')
4189
 
        g_store.save()
4190
 
        stack = config.LocationStack('/home/user/project/branch')
4191
 
        self.assertEquals('glob-bar', stack.get('lbar', expand=True))
4192
 
        self.assertEquals('loc-foo/branch', stack.get('gfoo', expand=True))
4193
 
 
4194
 
    def test_locals_dont_leak(self):
4195
 
        """Make sure we chose the right local in presence of several sections.
4196
 
        """
4197
 
        l_store = config.LocationStore()
4198
 
        l_store._load_from_string('''
4199
 
[/home/user]
4200
 
lfoo = loc-foo/{relpath}
4201
 
[/home/user/project]
4202
 
lfoo = loc-foo/{relpath}
4203
 
''')
4204
 
        l_store.save()
4205
 
        stack = config.LocationStack('/home/user/project/branch')
4206
 
        self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
4207
 
        stack = config.LocationStack('/home/user/bar/baz')
4208
 
        self.assertEquals('loc-foo/bar/baz', stack.get('lfoo', expand=True))
4209
 
 
 
2932
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
4210
2933
 
4211
2934
 
4212
2935
class TestStackSet(TestStackWithTransport):
4213
2936
 
4214
2937
    def test_simple_set(self):
4215
2938
        conf = self.get_stack(self)
4216
 
        self.assertEquals(None, conf.get('foo'))
 
2939
        conf.store._load_from_string('foo=bar')
 
2940
        self.assertEquals('bar', conf.get('foo'))
4217
2941
        conf.set('foo', 'baz')
4218
2942
        # Did we get it back ?
4219
2943
        self.assertEquals('baz', conf.get('foo'))
4239
2963
 
4240
2964
    def test_remove_existing(self):
4241
2965
        conf = self.get_stack(self)
4242
 
        conf.set('foo', 'bar')
 
2966
        conf.store._load_from_string('foo=bar')
4243
2967
        self.assertEquals('bar', conf.get('foo'))
4244
2968
        conf.remove('foo')
4245
2969
        # Did we get it back ?
4256
2980
        config.ConfigHooks.install_named_hook('remove', hook, None)
4257
2981
        self.assertLength(0, calls)
4258
2982
        conf = self.get_stack(self)
4259
 
        conf.set('foo', 'bar')
 
2983
        conf.store._load_from_string('foo=bar')
4260
2984
        conf.remove('foo')
4261
2985
        self.assertLength(1, calls)
4262
2986
        self.assertEquals((conf, 'foo'), calls[0])
4363
3087
        """
4364
3088
        sections = list(conf._get_sections(name))
4365
3089
        self.assertLength(len(expected), sections)
4366
 
        self.assertEqual(expected, [n for n, _, _ in sections])
 
3090
        self.assertEqual(expected, [name for name, _, _ in sections])
4367
3091
 
4368
3092
    def test_bazaar_default_section(self):
4369
3093
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
4413
3137
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
4414
3138
 
4415
3139
 
4416
 
class TestSharedStores(tests.TestCaseInTempDir):
4417
 
 
4418
 
    def test_bazaar_conf_shared(self):
4419
 
        g1 = config.GlobalStack()
4420
 
        g2 = config.GlobalStack()
4421
 
        # The two stacks share the same store
4422
 
        self.assertIs(g1.store, g2.store)
4423
 
 
4424
 
 
4425
3140
class TestAuthenticationConfigFile(tests.TestCase):
4426
3141
    """Test the authentication.conf file matching"""
4427
3142
 
4446
3161
        conf = config.AuthenticationConfig(_file=StringIO(
4447
3162
                'foo = bar\xff'))
4448
3163
        self.assertRaises(errors.ConfigContentError, conf._get_config)
4449
 
 
 
3164
        
4450
3165
    def test_missing_auth_section_header(self):
4451
3166
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
4452
3167
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
4642
3357
                                           port=99, path='/foo',
4643
3358
                                           realm='realm')
4644
3359
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4645
 
                       'verify_certificates': False, 'scheme': 'scheme',
4646
 
                       'host': 'host', 'port': 99, 'path': '/foo',
 
3360
                       'verify_certificates': False, 'scheme': 'scheme', 
 
3361
                       'host': 'host', 'port': 99, 'path': '/foo', 
4647
3362
                       'realm': 'realm'}
4648
3363
        self.assertEqual(CREDENTIALS, credentials)
4649
3364
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
4657
3372
        self.assertIs(None, conf._get_config().get('name'))
4658
3373
        credentials = conf.get_credentials(host='host', scheme='scheme')
4659
3374
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4660
 
                       'password', 'verify_certificates': True,
4661
 
                       'scheme': 'scheme', 'host': 'host', 'port': None,
 
3375
                       'password', 'verify_certificates': True, 
 
3376
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
4662
3377
                       'path': None, 'realm': None}
4663
3378
        self.assertEqual(CREDENTIALS, credentials)
4664
3379
 
4916
3631
        self.assertEquals('secret', decoded)
4917
3632
 
4918
3633
 
4919
 
class TestBase64CredentialStore(tests.TestCase):
4920
 
 
4921
 
    def test_decode_password(self):
4922
 
        r = config.credential_store_registry
4923
 
        plain_text = r.get_credential_store('base64')
4924
 
        decoded = plain_text.decode_password(dict(password='c2VjcmV0'))
4925
 
        self.assertEquals('secret', decoded)
4926
 
 
4927
 
 
4928
3634
# FIXME: Once we have a way to declare authentication to all test servers, we
4929
3635
# can implement generic tests.
4930
3636
# test_user_password_in_url
4942
3648
 
4943
3649
    def test_auto_user_id(self):
4944
3650
        """Automatic inference of user name.
4945
 
 
 
3651
        
4946
3652
        This is a bit hard to test in an isolated way, because it depends on
4947
3653
        system functions that go direct to /etc or perhaps somewhere else.
4948
3654
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
4958
3664
        else:
4959
3665
            self.assertEquals((None, None), (realname, address))
4960
3666
 
4961
 
 
4962
 
class TestDefaultMailDomain(tests.TestCaseInTempDir):
4963
 
    """Test retrieving default domain from mailname file"""
4964
 
 
4965
 
    def test_default_mail_domain_simple(self):
4966
 
        f = file('simple', 'w')
4967
 
        try:
4968
 
            f.write("domainname.com\n")
4969
 
        finally:
4970
 
            f.close()
4971
 
        r = config._get_default_mail_domain('simple')
4972
 
        self.assertEquals('domainname.com', r)
4973
 
 
4974
 
    def test_default_mail_domain_no_eol(self):
4975
 
        f = file('no_eol', 'w')
4976
 
        try:
4977
 
            f.write("domainname.com")
4978
 
        finally:
4979
 
            f.close()
4980
 
        r = config._get_default_mail_domain('no_eol')
4981
 
        self.assertEquals('domainname.com', r)
4982
 
 
4983
 
    def test_default_mail_domain_multiple_lines(self):
4984
 
        f = file('multiple_lines', 'w')
4985
 
        try:
4986
 
            f.write("domainname.com\nsome other text\n")
4987
 
        finally:
4988
 
            f.close()
4989
 
        r = config._get_default_mail_domain('multiple_lines')
4990
 
        self.assertEquals('domainname.com', r)
4991
 
 
4992
 
 
4993
 
class EmailOptionTests(tests.TestCase):
4994
 
 
4995
 
    def test_default_email_uses_BZR_EMAIL(self):
4996
 
        conf = config.MemoryStack('email=jelmer@debian.org')
4997
 
        # BZR_EMAIL takes precedence over EMAIL
4998
 
        self.overrideEnv('BZR_EMAIL', 'jelmer@samba.org')
4999
 
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
5000
 
        self.assertEquals('jelmer@samba.org', conf.get('email'))
5001
 
 
5002
 
    def test_default_email_uses_EMAIL(self):
5003
 
        conf = config.MemoryStack('')
5004
 
        self.overrideEnv('BZR_EMAIL', None)
5005
 
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
5006
 
        self.assertEquals('jelmer@apache.org', conf.get('email'))
5007
 
 
5008
 
    def test_BZR_EMAIL_overrides(self):
5009
 
        conf = config.MemoryStack('email=jelmer@debian.org')
5010
 
        self.overrideEnv('BZR_EMAIL', 'jelmer@apache.org')
5011
 
        self.assertEquals('jelmer@apache.org', conf.get('email'))
5012
 
        self.overrideEnv('BZR_EMAIL', None)
5013
 
        self.overrideEnv('EMAIL', 'jelmer@samba.org')
5014
 
        self.assertEquals('jelmer@debian.org', conf.get('email'))
5015
 
 
5016
 
 
5017
 
class MailClientOptionTests(tests.TestCase):
5018
 
 
5019
 
    def test_default(self):
5020
 
        conf = config.MemoryStack('')
5021
 
        client = conf.get('mail_client')
5022
 
        self.assertIs(client, mail_client.DefaultMail)
5023
 
 
5024
 
    def test_evolution(self):
5025
 
        conf = config.MemoryStack('mail_client=evolution')
5026
 
        client = conf.get('mail_client')
5027
 
        self.assertIs(client, mail_client.Evolution)
5028
 
 
5029
 
    def test_kmail(self):
5030
 
        conf = config.MemoryStack('mail_client=kmail')
5031
 
        client = conf.get('mail_client')
5032
 
        self.assertIs(client, mail_client.KMail)
5033
 
 
5034
 
    def test_mutt(self):
5035
 
        conf = config.MemoryStack('mail_client=mutt')
5036
 
        client = conf.get('mail_client')
5037
 
        self.assertIs(client, mail_client.Mutt)
5038
 
 
5039
 
    def test_thunderbird(self):
5040
 
        conf = config.MemoryStack('mail_client=thunderbird')
5041
 
        client = conf.get('mail_client')
5042
 
        self.assertIs(client, mail_client.Thunderbird)
5043
 
 
5044
 
    def test_explicit_default(self):
5045
 
        conf = config.MemoryStack('mail_client=default')
5046
 
        client = conf.get('mail_client')
5047
 
        self.assertIs(client, mail_client.DefaultMail)
5048
 
 
5049
 
    def test_editor(self):
5050
 
        conf = config.MemoryStack('mail_client=editor')
5051
 
        client = conf.get('mail_client')
5052
 
        self.assertIs(client, mail_client.Editor)
5053
 
 
5054
 
    def test_mapi(self):
5055
 
        conf = config.MemoryStack('mail_client=mapi')
5056
 
        client = conf.get('mail_client')
5057
 
        self.assertIs(client, mail_client.MAPIClient)
5058
 
 
5059
 
    def test_xdg_email(self):
5060
 
        conf = config.MemoryStack('mail_client=xdg-email')
5061
 
        client = conf.get('mail_client')
5062
 
        self.assertIs(client, mail_client.XDGEmail)
5063
 
 
5064
 
    def test_unknown(self):
5065
 
        conf = config.MemoryStack('mail_client=firebird')
5066
 
        self.assertRaises(errors.ConfigOptionValueError, conf.get,
5067
 
                'mail_client')