~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Patch Queue Manager
  • Date: 2016-01-31 13:36:59 UTC
  • mfrom: (6613.1.5 1538480-match-hostname)
  • Revision ID: pqm@pqm.ubuntu.com-20160131133659-ouy92ee2wlv9xz8m
(vila) Use ssl.match_hostname instead of our own. (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2014, 2016 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Tests for finding and reading the bzr config file[s]."""
18
 
# import system imports here
 
18
 
19
19
from cStringIO import StringIO
 
20
from textwrap import dedent
20
21
import os
21
22
import sys
22
23
import threading
23
24
 
24
 
 
25
25
from testtools import matchers
26
26
 
27
 
#import bzrlib specific imports here
28
27
from bzrlib import (
29
28
    branch,
30
 
    bzrdir,
31
29
    config,
 
30
    controldir,
32
31
    diff,
33
32
    errors,
34
33
    osutils,
35
34
    mail_client,
36
35
    ui,
37
36
    urlutils,
 
37
    registry as _mod_registry,
38
38
    remote,
39
39
    tests,
40
40
    trace,
67
67
 
68
68
# Register helpers to build stores
69
69
config.test_store_builder_registry.register(
70
 
    'configobj', lambda test: config.IniFileStore(test.get_transport(),
71
 
                                                  'configobj.conf'))
 
70
    'configobj', lambda test: config.TransportIniFileStore(
 
71
        test.get_transport(), 'configobj.conf'))
72
72
config.test_store_builder_registry.register(
73
73
    'bazaar', lambda test: config.GlobalStore())
74
74
config.test_store_builder_registry.register(
114
114
 
115
115
def build_control_store(test):
116
116
    build_backing_branch(test, 'branch')
117
 
    b = bzrdir.BzrDir.open('branch')
 
117
    b = controldir.ControlDir.open('branch')
118
118
    return config.ControlStore(b)
119
119
config.test_store_builder_registry.register('control', build_control_store)
120
120
 
144
144
config.test_stack_builder_registry.register('branch', build_branch_stack)
145
145
 
146
146
 
147
 
def build_remote_branch_stack(test):
 
147
def build_branch_only_stack(test):
148
148
    # There is only one permutation (but we won't be able to handle more with
149
149
    # this design anyway)
150
150
    (transport_class,
151
151
     server_class) = transport_remote.get_test_permutations()[0]
152
152
    build_backing_branch(test, 'branch', transport_class, server_class)
153
153
    b = branch.Branch.open(test.get_url('branch'))
154
 
    return config.RemoteBranchStack(b)
155
 
config.test_stack_builder_registry.register('remote_branch',
156
 
                                            build_remote_branch_stack)
 
154
    return config.BranchOnlyStack(b)
 
155
config.test_stack_builder_registry.register('branch_only',
 
156
                                            build_branch_only_stack)
157
157
 
158
158
def build_remote_control_stack(test):
159
159
    # There is only one permutation (but we won't be able to handle more with
328
328
 
329
329
class FakeBranch(object):
330
330
 
331
 
    def __init__(self, base=None, user_id=None):
 
331
    def __init__(self, base=None):
332
332
        if base is None:
333
333
            self.base = "http://example.com/branches/demo"
334
334
        else:
335
335
            self.base = base
336
336
        self._transport = self.control_files = \
337
 
            FakeControlFilesAndTransport(user_id=user_id)
 
337
            FakeControlFilesAndTransport()
338
338
 
339
339
    def _get_config(self):
340
340
        return config.TransportConfig(self._transport, 'branch.conf')
348
348
 
349
349
class FakeControlFilesAndTransport(object):
350
350
 
351
 
    def __init__(self, user_id=None):
 
351
    def __init__(self):
352
352
        self.files = {}
353
 
        if user_id:
354
 
            self.files['email'] = user_id
355
353
        self._transport = self
356
354
 
357
 
    def get_utf8(self, filename):
358
 
        # from LockableFiles
359
 
        raise AssertionError("get_utf8 should no longer be used")
360
 
 
361
355
    def get(self, filename):
362
356
        # from Transport
363
357
        try:
481
475
    def test_constructs(self):
482
476
        config.Config()
483
477
 
484
 
    def test_no_default_editor(self):
485
 
        self.assertRaises(
486
 
            NotImplementedError,
487
 
            self.applyDeprecated, deprecated_in((2, 4, 0)),
488
 
            config.Config().get_editor)
489
 
 
490
478
    def test_user_email(self):
491
479
        my_config = InstrumentedConfig()
492
480
        self.assertEqual('robert.collins@example.org', my_config.user_email())
500
488
 
501
489
    def test_signatures_default(self):
502
490
        my_config = config.Config()
503
 
        self.assertFalse(my_config.signature_needed())
 
491
        self.assertFalse(
 
492
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
493
                my_config.signature_needed))
504
494
        self.assertEqual(config.CHECK_IF_POSSIBLE,
505
 
                         my_config.signature_checking())
 
495
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
496
                my_config.signature_checking))
506
497
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
507
 
                         my_config.signing_policy())
 
498
                self.applyDeprecated(deprecated_in((2, 5, 0)),
 
499
                    my_config.signing_policy))
508
500
 
509
501
    def test_signatures_template_method(self):
510
502
        my_config = InstrumentedConfig()
511
 
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
503
        self.assertEqual(config.CHECK_NEVER,
 
504
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
505
                my_config.signature_checking))
512
506
        self.assertEqual(['_get_signature_checking'], my_config._calls)
513
507
 
514
508
    def test_signatures_template_method_none(self):
515
509
        my_config = InstrumentedConfig()
516
510
        my_config._signatures = None
517
511
        self.assertEqual(config.CHECK_IF_POSSIBLE,
518
 
                         my_config.signature_checking())
 
512
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
513
                             my_config.signature_checking))
519
514
        self.assertEqual(['_get_signature_checking'], my_config._calls)
520
515
 
521
516
    def test_gpg_signing_command_default(self):
522
517
        my_config = config.Config()
523
 
        self.assertEqual('gpg', my_config.gpg_signing_command())
 
518
        self.assertEqual('gpg',
 
519
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
520
                my_config.gpg_signing_command))
524
521
 
525
522
    def test_get_user_option_default(self):
526
523
        my_config = config.Config()
528
525
 
529
526
    def test_post_commit_default(self):
530
527
        my_config = config.Config()
531
 
        self.assertEqual(None, my_config.post_commit())
 
528
        self.assertEqual(None, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
529
                                                    my_config.post_commit))
 
530
 
532
531
 
533
532
    def test_log_format_default(self):
534
533
        my_config = config.Config()
535
 
        self.assertEqual('long', my_config.log_format())
 
534
        self.assertEqual('long',
 
535
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
536
                                              my_config.log_format))
536
537
 
537
538
    def test_acceptable_keys_default(self):
538
539
        my_config = config.Config()
539
 
        self.assertEqual(None, my_config.acceptable_keys())
 
540
        self.assertEqual(None, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
541
            my_config.acceptable_keys))
540
542
 
541
543
    def test_validate_signatures_in_log_default(self):
542
544
        my_config = config.Config()
556
558
    def setUp(self):
557
559
        super(TestConfigPath, self).setUp()
558
560
        self.overrideEnv('HOME', '/home/bogus')
559
 
        self.overrideEnv('XDG_CACHE_DIR', '')
 
561
        self.overrideEnv('XDG_CACHE_HOME', '')
560
562
        if sys.platform == 'win32':
561
563
            self.overrideEnv(
562
564
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
568
570
    def test_config_dir(self):
569
571
        self.assertEqual(config.config_dir(), self.bzr_home)
570
572
 
 
573
    def test_config_dir_is_unicode(self):
 
574
        self.assertIsInstance(config.config_dir(), unicode)
 
575
 
571
576
    def test_config_filename(self):
572
577
        self.assertEqual(config.config_filename(),
573
578
                         self.bzr_home + '/bazaar.conf')
590
595
    # subdirectory of $XDG_CONFIG_HOME
591
596
 
592
597
    def setUp(self):
593
 
        if sys.platform in ('darwin', 'win32'):
 
598
        if sys.platform == 'win32':
594
599
            raise tests.TestNotApplicable(
595
600
                'XDG config dir not used on this platform')
596
601
        super(TestXDGConfigDir, self).setUp()
623
628
class TestIniConfigBuilding(TestIniConfig):
624
629
 
625
630
    def test_contructs(self):
626
 
        my_config = config.IniBasedConfig()
 
631
        config.IniBasedConfig()
627
632
 
628
633
    def test_from_fp(self):
629
634
        my_config = config.IniBasedConfig.from_string(sample_config_text)
672
677
 
673
678
    def test_saved_with_content(self):
674
679
        content = 'foo = bar\n'
675
 
        conf = config.IniBasedConfig.from_string(
676
 
            content, file_name='./test.conf', save=True)
 
680
        config.IniBasedConfig.from_string(content, file_name='./test.conf',
 
681
                                          save=True)
677
682
        self.assertFileEqual(content, 'test.conf')
678
683
 
679
684
 
680
 
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
681
 
    """What is the default value of expand for config options.
682
 
 
683
 
    This is an opt-in beta feature used to evaluate whether or not option
684
 
    references can appear in dangerous place raising exceptions, disapearing
685
 
    (and as such corrupting data) or if it's safe to activate the option by
686
 
    default.
687
 
 
688
 
    Note that these tests relies on config._expand_default_value being already
689
 
    overwritten in the parent class setUp.
690
 
    """
691
 
 
692
 
    def setUp(self):
693
 
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
694
 
        self.config = None
695
 
        self.warnings = []
696
 
        def warning(*args):
697
 
            self.warnings.append(args[0] % args[1:])
698
 
        self.overrideAttr(trace, 'warning', warning)
699
 
 
700
 
    def get_config(self, expand):
701
 
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
702
 
                                            save=True)
703
 
        return c
704
 
 
705
 
    def assertExpandIs(self, expected):
706
 
        actual = config._get_expand_default_value()
707
 
        #self.config.get_user_option_as_bool('bzr.config.expand')
708
 
        self.assertEquals(expected, actual)
709
 
 
710
 
    def test_default_is_None(self):
711
 
        self.assertEquals(None, config._expand_default_value)
712
 
 
713
 
    def test_default_is_False_even_if_None(self):
714
 
        self.config = self.get_config(None)
715
 
        self.assertExpandIs(False)
716
 
 
717
 
    def test_default_is_False_even_if_invalid(self):
718
 
        self.config = self.get_config('<your choice>')
719
 
        self.assertExpandIs(False)
720
 
        # ...
721
 
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
722
 
        # Wait, you've been warned !
723
 
        self.assertLength(1, self.warnings)
724
 
        self.assertEquals(
725
 
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
726
 
            self.warnings[0])
727
 
 
728
 
    def test_default_is_True(self):
729
 
        self.config = self.get_config(True)
730
 
        self.assertExpandIs(True)
731
 
 
732
 
    def test_default_is_False(self):
733
 
        self.config = self.get_config(False)
734
 
        self.assertExpandIs(False)
735
 
 
736
 
 
737
685
class TestIniConfigOptionExpansion(tests.TestCase):
738
686
    """Test option expansion from the IniConfig level.
739
687
 
1063
1011
si_g = 5g,
1064
1012
si_gb = 5gB,
1065
1013
""")
1066
 
        get_si = conf.get_user_option_as_int_from_SI
 
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)
1067
1018
        self.assertEqual(100, get_si('plain'))
1068
1019
        self.assertEqual(5000, get_si('si_k'))
1069
1020
        self.assertEqual(5000, get_si('si_kb'))
1074
1025
        self.assertEqual(None, get_si('non-exist'))
1075
1026
        self.assertEqual(42, get_si('non-exist-with-default',  42))
1076
1027
 
 
1028
 
1077
1029
class TestSupressWarning(TestIniConfig):
1078
1030
 
1079
1031
    def make_warnings_config(self, s):
1094
1046
class TestGetConfig(tests.TestCase):
1095
1047
 
1096
1048
    def test_constructs(self):
1097
 
        my_config = config.GlobalConfig()
 
1049
        config.GlobalConfig()
1098
1050
 
1099
1051
    def test_calls_read_filenames(self):
1100
1052
        # replace the class that is constructed, to check its parameters
1112
1064
 
1113
1065
class TestBranchConfig(tests.TestCaseWithTransport):
1114
1066
 
1115
 
    def test_constructs(self):
 
1067
    def test_constructs_valid(self):
1116
1068
        branch = FakeBranch()
1117
1069
        my_config = config.BranchConfig(branch)
 
1070
        self.assertIsNot(None, my_config)
 
1071
 
 
1072
    def test_constructs_error(self):
1118
1073
        self.assertRaises(TypeError, config.BranchConfig)
1119
1074
 
1120
1075
    def test_get_location_config(self):
1126
1081
 
1127
1082
    def test_get_config(self):
1128
1083
        """The Branch.get_config method works properly"""
1129
 
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
 
1084
        b = controldir.ControlDir.create_standalone_workingtree('.').branch
1130
1085
        my_config = b.get_config()
1131
1086
        self.assertIs(my_config.get_user_option('wacky'), None)
1132
1087
        my_config.set_user_option('wacky', 'unlikely')
1152
1107
        conf = config.LocationConfig.from_string(
1153
1108
            '[%s]\nnickname = foobar' % (local_url,),
1154
1109
            local_url, save=True)
 
1110
        self.assertIsNot(None, conf)
1155
1111
        self.assertEqual('foobar', branch.nick)
1156
1112
 
1157
1113
    def test_config_local_path(self):
1160
1116
        self.assertEqual('branch', branch.nick)
1161
1117
 
1162
1118
        local_path = osutils.getcwd().encode('utf8')
1163
 
        conf = config.LocationConfig.from_string(
 
1119
        config.LocationConfig.from_string(
1164
1120
            '[%s/branch]\nnickname = barry' % (local_path,),
1165
1121
            'branch',  save=True)
 
1122
        # Now the branch will find its nick via the location config
1166
1123
        self.assertEqual('barry', branch.nick)
1167
1124
 
1168
1125
    def test_config_creates_local(self):
1181
1138
        b = self.make_branch('!repo')
1182
1139
        self.assertEqual('!repo', b.get_config().get_nickname())
1183
1140
 
 
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
 
1184
1145
    def test_warn_if_masked(self):
1185
1146
        warnings = []
1186
1147
        def warning(*args):
1226
1187
        my_config = config.GlobalConfig()
1227
1188
        self.assertEqual(None, my_config._get_user_id())
1228
1189
 
1229
 
    def test_configured_editor(self):
1230
 
        my_config = config.GlobalConfig.from_string(sample_config_text)
1231
 
        editor = self.applyDeprecated(
1232
 
            deprecated_in((2, 4, 0)), my_config.get_editor)
1233
 
        self.assertEqual('vim', editor)
1234
 
 
1235
1190
    def test_signatures_always(self):
1236
1191
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
1237
1192
        self.assertEqual(config.CHECK_NEVER,
1238
 
                         my_config.signature_checking())
 
1193
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1194
                             my_config.signature_checking))
1239
1195
        self.assertEqual(config.SIGN_ALWAYS,
1240
 
                         my_config.signing_policy())
1241
 
        self.assertEqual(True, my_config.signature_needed())
 
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))
1242
1201
 
1243
1202
    def test_signatures_if_possible(self):
1244
1203
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
1245
1204
        self.assertEqual(config.CHECK_NEVER,
1246
 
                         my_config.signature_checking())
 
1205
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1206
                             my_config.signature_checking))
1247
1207
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
1248
 
                         my_config.signing_policy())
1249
 
        self.assertEqual(False, my_config.signature_needed())
 
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))
1250
1212
 
1251
1213
    def test_signatures_ignore(self):
1252
1214
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
1253
1215
        self.assertEqual(config.CHECK_ALWAYS,
1254
 
                         my_config.signature_checking())
 
1216
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1217
                             my_config.signature_checking))
1255
1218
        self.assertEqual(config.SIGN_NEVER,
1256
 
                         my_config.signing_policy())
1257
 
        self.assertEqual(False, my_config.signature_needed())
 
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))
1258
1223
 
1259
1224
    def _get_sample_config(self):
1260
1225
        my_config = config.GlobalConfig.from_string(sample_config_text)
1262
1227
 
1263
1228
    def test_gpg_signing_command(self):
1264
1229
        my_config = self._get_sample_config()
1265
 
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
1266
 
        self.assertEqual(False, my_config.signature_needed())
 
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))
1267
1235
 
1268
1236
    def test_gpg_signing_key(self):
1269
1237
        my_config = self._get_sample_config()
1270
 
        self.assertEqual("DD4D5088", my_config.gpg_signing_key())
 
1238
        self.assertEqual("DD4D5088",
 
1239
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1240
                my_config.gpg_signing_key))
1271
1241
 
1272
1242
    def _get_empty_config(self):
1273
1243
        my_config = config.GlobalConfig()
1275
1245
 
1276
1246
    def test_gpg_signing_command_unset(self):
1277
1247
        my_config = self._get_empty_config()
1278
 
        self.assertEqual("gpg", my_config.gpg_signing_command())
 
1248
        self.assertEqual("gpg",
 
1249
            self.applyDeprecated(
 
1250
                deprecated_in((2, 5, 0)), my_config.gpg_signing_command))
1279
1251
 
1280
1252
    def test_get_user_option_default(self):
1281
1253
        my_config = self._get_empty_config()
1288
1260
 
1289
1261
    def test_post_commit_default(self):
1290
1262
        my_config = self._get_sample_config()
1291
 
        self.assertEqual(None, my_config.post_commit())
 
1263
        self.assertEqual(None,
 
1264
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1265
                                              my_config.post_commit))
1292
1266
 
1293
1267
    def test_configured_logformat(self):
1294
1268
        my_config = self._get_sample_config()
1295
 
        self.assertEqual("short", my_config.log_format())
 
1269
        self.assertEqual("short",
 
1270
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1271
                                              my_config.log_format))
1296
1272
 
1297
1273
    def test_configured_acceptable_keys(self):
1298
1274
        my_config = self._get_sample_config()
1299
 
        self.assertEqual("amy", my_config.acceptable_keys())
 
1275
        self.assertEqual("amy",
 
1276
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1277
                my_config.acceptable_keys))
1300
1278
 
1301
1279
    def test_configured_validate_signatures_in_log(self):
1302
1280
        my_config = self._get_sample_config()
1395
1373
 
1396
1374
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
1397
1375
 
1398
 
    def test_constructs(self):
1399
 
        my_config = config.LocationConfig('http://example.com')
 
1376
    def test_constructs_valid(self):
 
1377
        config.LocationConfig('http://example.com')
 
1378
 
 
1379
    def test_constructs_error(self):
1400
1380
        self.assertRaises(TypeError, config.LocationConfig)
1401
1381
 
1402
1382
    def test_branch_calls_read_filenames(self):
1538
1518
        self.get_branch_config('http://www.example.com',
1539
1519
                                 global_config=sample_ignore_signatures)
1540
1520
        self.assertEqual(config.CHECK_ALWAYS,
1541
 
                         self.my_config.signature_checking())
 
1521
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1522
                             self.my_config.signature_checking))
1542
1523
        self.assertEqual(config.SIGN_NEVER,
1543
 
                         self.my_config.signing_policy())
 
1524
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1525
                             self.my_config.signing_policy))
1544
1526
 
1545
1527
    def test_signatures_never(self):
1546
1528
        self.get_branch_config('/a/c')
1547
1529
        self.assertEqual(config.CHECK_NEVER,
1548
 
                         self.my_config.signature_checking())
 
1530
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1531
                             self.my_config.signature_checking))
1549
1532
 
1550
1533
    def test_signatures_when_available(self):
1551
1534
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
1552
1535
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1553
 
                         self.my_config.signature_checking())
 
1536
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1537
                             self.my_config.signature_checking))
1554
1538
 
1555
1539
    def test_signatures_always(self):
1556
1540
        self.get_branch_config('/b')
1557
1541
        self.assertEqual(config.CHECK_ALWAYS,
1558
 
                         self.my_config.signature_checking())
 
1542
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1543
                         self.my_config.signature_checking))
1559
1544
 
1560
1545
    def test_gpg_signing_command(self):
1561
1546
        self.get_branch_config('/b')
1562
 
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
 
1547
        self.assertEqual("gnome-gpg",
 
1548
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1549
                self.my_config.gpg_signing_command))
1563
1550
 
1564
1551
    def test_gpg_signing_command_missing(self):
1565
1552
        self.get_branch_config('/a')
1566
 
        self.assertEqual("false", self.my_config.gpg_signing_command())
 
1553
        self.assertEqual("false",
 
1554
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1555
                self.my_config.gpg_signing_command))
1567
1556
 
1568
1557
    def test_gpg_signing_key(self):
1569
1558
        self.get_branch_config('/b')
1570
 
        self.assertEqual("DD4D5088", self.my_config.gpg_signing_key())
 
1559
        self.assertEqual("DD4D5088", self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1560
            self.my_config.gpg_signing_key))
1571
1561
 
1572
1562
    def test_gpg_signing_key_default(self):
1573
1563
        self.get_branch_config('/a')
1574
 
        self.assertEqual("erik@bagfors.nu", self.my_config.gpg_signing_key())
 
1564
        self.assertEqual("erik@bagfors.nu",
 
1565
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1566
                self.my_config.gpg_signing_key))
1575
1567
 
1576
1568
    def test_get_user_option_global(self):
1577
1569
        self.get_branch_config('/a')
1665
1657
    def test_post_commit_default(self):
1666
1658
        self.get_branch_config('/a/c')
1667
1659
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1668
 
                         self.my_config.post_commit())
 
1660
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1661
                                              self.my_config.post_commit))
1669
1662
 
1670
1663
    def get_branch_config(self, location, global_config=None,
1671
1664
                          location_config=None):
1675
1668
        if location_config is None:
1676
1669
            location_config = sample_branches_text
1677
1670
 
1678
 
        my_global_config = config.GlobalConfig.from_string(global_config,
1679
 
                                                           save=True)
1680
 
        my_location_config = config.LocationConfig.from_string(
1681
 
            location_config, my_branch.base, save=True)
 
1671
        config.GlobalConfig.from_string(global_config, save=True)
 
1672
        config.LocationConfig.from_string(location_config, my_branch.base,
 
1673
                                          save=True)
1682
1674
        my_config = config.BranchConfig(my_branch)
1683
1675
        self.my_config = my_config
1684
1676
        self.my_location_config = my_config._get_location_config()
1749
1741
                          location_config=None, branch_data_config=None):
1750
1742
        my_branch = FakeBranch(location)
1751
1743
        if global_config is not None:
1752
 
            my_global_config = config.GlobalConfig.from_string(global_config,
1753
 
                                                               save=True)
 
1744
            config.GlobalConfig.from_string(global_config, save=True)
1754
1745
        if location_config is not None:
1755
 
            my_location_config = config.LocationConfig.from_string(
1756
 
                location_config, my_branch.base, save=True)
 
1746
            config.LocationConfig.from_string(location_config, my_branch.base,
 
1747
                                              save=True)
1757
1748
        my_config = config.BranchConfig(my_branch)
1758
1749
        if branch_data_config is not None:
1759
1750
            my_config.branch.control_files.files['branch.conf'] = \
1761
1752
        return my_config
1762
1753
 
1763
1754
    def test_user_id(self):
1764
 
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
 
1755
        branch = FakeBranch()
1765
1756
        my_config = config.BranchConfig(branch)
1766
 
        self.assertEqual("Robert Collins <robertc@example.net>",
1767
 
                         my_config.username())
 
1757
        self.assertIsNot(None, my_config.username())
1768
1758
        my_config.branch.control_files.files['email'] = "John"
1769
1759
        my_config.set_user_option('email',
1770
1760
                                  "Robert Collins <robertc@example.org>")
1771
 
        self.assertEqual("John", my_config.username())
1772
 
        del my_config.branch.control_files.files['email']
1773
1761
        self.assertEqual("Robert Collins <robertc@example.org>",
1774
 
                         my_config.username())
1775
 
 
1776
 
    def test_not_set_in_branch(self):
1777
 
        my_config = self.get_branch_config(global_config=sample_config_text)
1778
 
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1779
 
                         my_config._get_user_id())
1780
 
        my_config.branch.control_files.files['email'] = "John"
1781
 
        self.assertEqual("John", my_config._get_user_id())
 
1762
                        my_config.username())
1782
1763
 
1783
1764
    def test_BZR_EMAIL_OVERRIDES(self):
1784
1765
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1790
1771
    def test_signatures_forced(self):
1791
1772
        my_config = self.get_branch_config(
1792
1773
            global_config=sample_always_signatures)
1793
 
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1794
 
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1795
 
        self.assertTrue(my_config.signature_needed())
 
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))
1796
1782
 
1797
1783
    def test_signatures_forced_branch(self):
1798
1784
        my_config = self.get_branch_config(
1799
1785
            global_config=sample_ignore_signatures,
1800
1786
            branch_data_config=sample_always_signatures)
1801
 
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1802
 
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1803
 
        self.assertTrue(my_config.signature_needed())
 
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))
1804
1795
 
1805
1796
    def test_gpg_signing_command(self):
1806
1797
        my_config = self.get_branch_config(
1807
1798
            global_config=sample_config_text,
1808
1799
            # branch data cannot set gpg_signing_command
1809
1800
            branch_data_config="gpg_signing_command=pgp")
1810
 
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
 
1801
        self.assertEqual('gnome-gpg',
 
1802
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1803
                my_config.gpg_signing_command))
1811
1804
 
1812
1805
    def test_get_user_option_global(self):
1813
1806
        my_config = self.get_branch_config(global_config=sample_config_text)
1820
1813
                                      location_config=sample_branches_text)
1821
1814
        self.assertEqual(my_config.branch.base, '/a/c')
1822
1815
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1823
 
                         my_config.post_commit())
 
1816
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1817
                                              my_config.post_commit))
1824
1818
        my_config.set_user_option('post_commit', 'rmtree_root')
1825
1819
        # post-commit is ignored when present in branch data
1826
1820
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1827
 
                         my_config.post_commit())
 
1821
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1822
                                              my_config.post_commit))
1828
1823
        my_config.set_user_option('post_commit', 'rmtree_root',
1829
1824
                                  store=config.STORE_LOCATION)
1830
 
        self.assertEqual('rmtree_root', my_config.post_commit())
 
1825
        self.assertEqual('rmtree_root',
 
1826
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1827
                                              my_config.post_commit))
1831
1828
 
1832
1829
    def test_config_precedence(self):
1833
1830
        # FIXME: eager test, luckily no persitent config file makes it fail
1849
1846
            location='http://example.com/specific')
1850
1847
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1851
1848
 
1852
 
    def test_get_mail_client(self):
1853
 
        config = self.get_branch_config()
1854
 
        client = config.get_mail_client()
1855
 
        self.assertIsInstance(client, mail_client.DefaultMail)
1856
 
 
1857
 
        # Specific clients
1858
 
        config.set_user_option('mail_client', 'evolution')
1859
 
        client = config.get_mail_client()
1860
 
        self.assertIsInstance(client, mail_client.Evolution)
1861
 
 
1862
 
        config.set_user_option('mail_client', 'kmail')
1863
 
        client = config.get_mail_client()
1864
 
        self.assertIsInstance(client, mail_client.KMail)
1865
 
 
1866
 
        config.set_user_option('mail_client', 'mutt')
1867
 
        client = config.get_mail_client()
1868
 
        self.assertIsInstance(client, mail_client.Mutt)
1869
 
 
1870
 
        config.set_user_option('mail_client', 'thunderbird')
1871
 
        client = config.get_mail_client()
1872
 
        self.assertIsInstance(client, mail_client.Thunderbird)
1873
 
 
1874
 
        # Generic options
1875
 
        config.set_user_option('mail_client', 'default')
1876
 
        client = config.get_mail_client()
1877
 
        self.assertIsInstance(client, mail_client.DefaultMail)
1878
 
 
1879
 
        config.set_user_option('mail_client', 'editor')
1880
 
        client = config.get_mail_client()
1881
 
        self.assertIsInstance(client, mail_client.Editor)
1882
 
 
1883
 
        config.set_user_option('mail_client', 'mapi')
1884
 
        client = config.get_mail_client()
1885
 
        self.assertIsInstance(client, mail_client.MAPIClient)
1886
 
 
1887
 
        config.set_user_option('mail_client', 'xdg-email')
1888
 
        client = config.get_mail_client()
1889
 
        self.assertIsInstance(client, mail_client.XDGEmail)
1890
 
 
1891
 
        config.set_user_option('mail_client', 'firebird')
1892
 
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1893
 
 
1894
1849
 
1895
1850
class TestMailAddressExtraction(tests.TestCase):
1896
1851
 
2183
2138
        self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2184
2139
 
2185
2140
    def test_get_hook_remote_bzrdir(self):
2186
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2141
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
2187
2142
        conf = remote_bzrdir._get_config()
2188
2143
        conf.set_option('remotedir', 'file')
2189
2144
        self.assertGetHook(conf, 'file', 'remotedir')
2211
2166
    def test_set_hook_remote_bzrdir(self):
2212
2167
        remote_branch = branch.Branch.open(self.get_url('tree'))
2213
2168
        self.addCleanup(remote_branch.lock_write().unlock)
2214
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2169
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
2215
2170
        self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2216
2171
 
2217
2172
    def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2234
2189
        self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2235
2190
 
2236
2191
    def test_load_hook_remote_bzrdir(self):
2237
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2192
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
2238
2193
        # The config file doesn't exist, set an option to force its creation
2239
2194
        conf = remote_bzrdir._get_config()
2240
2195
        conf.set_option('remotedir', 'file')
2265
2220
    def test_save_hook_remote_bzrdir(self):
2266
2221
        remote_branch = branch.Branch.open(self.get_url('tree'))
2267
2222
        self.addCleanup(remote_branch.lock_write().unlock)
2268
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2223
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
2269
2224
        self.assertSaveHook(remote_bzrdir._get_config())
2270
2225
 
2271
2226
 
 
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
        # Don't break bzr-svn for no good reason
 
2241
        self.assertTrue(self.is_valid('guessed-layout'))
 
2242
 
 
2243
    def test_invalid_names(self):
 
2244
        self.assertFalse(self.is_valid(' foo'))
 
2245
        self.assertFalse(self.is_valid('foo '))
 
2246
        self.assertFalse(self.is_valid('1'))
 
2247
        self.assertFalse(self.is_valid('1,2'))
 
2248
        self.assertFalse(self.is_valid('foo$'))
 
2249
        self.assertFalse(self.is_valid('!foo'))
 
2250
        self.assertFalse(self.is_valid('foo.'))
 
2251
        self.assertFalse(self.is_valid('foo..bar'))
 
2252
        self.assertFalse(self.is_valid('{}'))
 
2253
        self.assertFalse(self.is_valid('{a}'))
 
2254
        self.assertFalse(self.is_valid('a\n'))
 
2255
        self.assertFalse(self.is_valid('-'))
 
2256
        self.assertFalse(self.is_valid('-a'))
 
2257
        self.assertFalse(self.is_valid('a-'))
 
2258
        self.assertFalse(self.is_valid('a--a'))
 
2259
 
 
2260
    def assertSingleGroup(self, reference):
 
2261
        # the regexp is used with split and as such should match the reference
 
2262
        # *only*, if more groups needs to be defined, (?:...) should be used.
 
2263
        m = config._option_ref_re.match('{a}')
 
2264
        self.assertLength(1, m.groups())
 
2265
 
 
2266
    def test_valid_references(self):
 
2267
        self.assertSingleGroup('{a}')
 
2268
        self.assertSingleGroup('{{a}}')
 
2269
 
 
2270
 
2272
2271
class TestOption(tests.TestCase):
2273
2272
 
2274
2273
    def test_default_value(self):
2275
2274
        opt = config.Option('foo', default='bar')
2276
2275
        self.assertEquals('bar', opt.get_default())
2277
2276
 
 
2277
    def test_callable_default_value(self):
 
2278
        def bar_as_unicode():
 
2279
            return u'bar'
 
2280
        opt = config.Option('foo', default=bar_as_unicode)
 
2281
        self.assertEquals('bar', opt.get_default())
 
2282
 
2278
2283
    def test_default_value_from_env(self):
2279
2284
        opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2280
2285
        self.overrideEnv('FOO', 'quux')
2296
2301
        self.assertRaises(AssertionError, config.Option, 'foo',
2297
2302
                          default=object())
2298
2303
 
2299
 
 
2300
 
class TestOptionConverterMixin(object):
2301
 
 
2302
 
    def assertConverted(self, expected, opt, value):
2303
 
        self.assertEquals(expected, opt.convert_from_unicode(value))
2304
 
 
2305
 
    def assertWarns(self, opt, value):
2306
 
        warnings = []
2307
 
        def warning(*args):
2308
 
            warnings.append(args[0] % args[1:])
2309
 
        self.overrideAttr(trace, 'warning', warning)
2310
 
        self.assertEquals(None, opt.convert_from_unicode(value))
2311
 
        self.assertLength(1, warnings)
2312
 
        self.assertEquals(
2313
 
            'Value "%s" is not valid for "%s"' % (value, opt.name),
2314
 
            warnings[0])
2315
 
 
2316
 
    def assertErrors(self, opt, value):
2317
 
        self.assertRaises(errors.ConfigOptionValueError,
2318
 
                          opt.convert_from_unicode, value)
2319
 
 
2320
 
    def assertConvertInvalid(self, opt, invalid_value):
2321
 
        opt.invalid = None
2322
 
        self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2323
 
        opt.invalid = 'warning'
2324
 
        self.assertWarns(opt, invalid_value)
2325
 
        opt.invalid = 'error'
2326
 
        self.assertErrors(opt, invalid_value)
2327
 
 
2328
 
 
2329
 
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2330
 
 
2331
 
    def get_option(self):
2332
 
        return config.Option('foo', help='A boolean.',
2333
 
                             from_unicode=config.bool_from_store)
2334
 
 
2335
 
    def test_convert_invalid(self):
2336
 
        opt = self.get_option()
2337
 
        # A string that is not recognized as a boolean
2338
 
        self.assertConvertInvalid(opt, u'invalid-boolean')
2339
 
        # A list of strings is never recognized as a boolean
2340
 
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2341
 
 
2342
 
    def test_convert_valid(self):
2343
 
        opt = self.get_option()
2344
 
        self.assertConverted(True, opt, u'True')
2345
 
        self.assertConverted(True, opt, u'1')
2346
 
        self.assertConverted(False, opt, u'False')
2347
 
 
2348
 
 
2349
 
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2350
 
 
2351
 
    def get_option(self):
2352
 
        return config.Option('foo', help='An integer.',
2353
 
                             from_unicode=config.int_from_store)
2354
 
 
2355
 
    def test_convert_invalid(self):
2356
 
        opt = self.get_option()
2357
 
        # A string that is not recognized as an integer
2358
 
        self.assertConvertInvalid(opt, u'forty-two')
2359
 
        # A list of strings is never recognized as an integer
2360
 
        self.assertConvertInvalid(opt, [u'a', u'list'])
2361
 
 
2362
 
    def test_convert_valid(self):
2363
 
        opt = self.get_option()
2364
 
        self.assertConverted(16, opt, u'16')
2365
 
 
2366
 
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2367
 
 
2368
 
    def get_option(self):
2369
 
        return config.Option('foo', help='A list.',
2370
 
                             from_unicode=config.list_from_store)
2371
 
 
2372
 
    def test_convert_invalid(self):
2373
 
        # No string is invalid as all forms can be converted to a list
2374
 
        pass
2375
 
 
2376
 
    def test_convert_valid(self):
2377
 
        opt = self.get_option()
2378
 
        # An empty string is an empty list
2379
 
        self.assertConverted([], opt, '') # Using a bare str() just in case
2380
 
        self.assertConverted([], opt, u'')
2381
 
        # A boolean
2382
 
        self.assertConverted([u'True'], opt, u'True')
2383
 
        # An integer
2384
 
        self.assertConverted([u'42'], opt, u'42')
2385
 
        # A single string
2386
 
        self.assertConverted([u'bar'], opt, u'bar')
2387
 
        # A list remains a list (configObj will turn a string containing commas
2388
 
        # into a list, but that's not what we're testing here)
2389
 
        self.assertConverted([u'foo', u'1', u'True'],
2390
 
                             opt, [u'foo', u'1', u'True'])
2391
 
 
2392
 
 
2393
 
class TestOptionConverterMixin(object):
2394
 
 
2395
 
    def assertConverted(self, expected, opt, value):
2396
 
        self.assertEquals(expected, opt.convert_from_unicode(value))
2397
 
 
2398
 
    def assertWarns(self, opt, value):
2399
 
        warnings = []
2400
 
        def warning(*args):
2401
 
            warnings.append(args[0] % args[1:])
2402
 
        self.overrideAttr(trace, 'warning', warning)
2403
 
        self.assertEquals(None, opt.convert_from_unicode(value))
2404
 
        self.assertLength(1, warnings)
2405
 
        self.assertEquals(
2406
 
            'Value "%s" is not valid for "%s"' % (value, opt.name),
2407
 
            warnings[0])
2408
 
 
2409
 
    def assertErrors(self, opt, value):
2410
 
        self.assertRaises(errors.ConfigOptionValueError,
2411
 
                          opt.convert_from_unicode, value)
2412
 
 
2413
 
    def assertConvertInvalid(self, opt, invalid_value):
2414
 
        opt.invalid = None
2415
 
        self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2416
 
        opt.invalid = 'warning'
2417
 
        self.assertWarns(opt, invalid_value)
2418
 
        opt.invalid = 'error'
2419
 
        self.assertErrors(opt, invalid_value)
2420
 
 
2421
 
 
2422
 
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2423
 
 
2424
 
    def get_option(self):
2425
 
        return config.Option('foo', help='A boolean.',
2426
 
                             from_unicode=config.bool_from_store)
2427
 
 
2428
 
    def test_convert_invalid(self):
2429
 
        opt = self.get_option()
2430
 
        # A string that is not recognized as a boolean
2431
 
        self.assertConvertInvalid(opt, u'invalid-boolean')
2432
 
        # A list of strings is never recognized as a boolean
2433
 
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2434
 
 
2435
 
    def test_convert_valid(self):
2436
 
        opt = self.get_option()
2437
 
        self.assertConverted(True, opt, u'True')
2438
 
        self.assertConverted(True, opt, u'1')
2439
 
        self.assertConverted(False, opt, u'False')
2440
 
 
2441
 
 
2442
 
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2443
 
 
2444
 
    def get_option(self):
2445
 
        return config.Option('foo', help='An integer.',
2446
 
                             from_unicode=config.int_from_store)
2447
 
 
2448
 
    def test_convert_invalid(self):
2449
 
        opt = self.get_option()
2450
 
        # A string that is not recognized as an integer
2451
 
        self.assertConvertInvalid(opt, u'forty-two')
2452
 
        # A list of strings is never recognized as an integer
2453
 
        self.assertConvertInvalid(opt, [u'a', u'list'])
2454
 
 
2455
 
    def test_convert_valid(self):
2456
 
        opt = self.get_option()
2457
 
        self.assertConverted(16, opt, u'16')
2458
 
 
2459
 
 
2460
 
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2461
 
 
2462
 
    def get_option(self):
2463
 
        return config.Option('foo', help='A list.',
2464
 
                             from_unicode=config.list_from_store)
 
2304
    def test_not_supported_callable_default_value_not_unicode(self):
 
2305
        def bar_not_unicode():
 
2306
            return 'bar'
 
2307
        opt = config.Option('foo', default=bar_not_unicode)
 
2308
        self.assertRaises(AssertionError, opt.get_default)
 
2309
 
 
2310
    def test_get_help_topic(self):
 
2311
        opt = config.Option('foo')
 
2312
        self.assertEquals('foo', opt.get_help_topic())
 
2313
 
 
2314
 
 
2315
class TestOptionConverter(tests.TestCase):
 
2316
 
 
2317
    def assertConverted(self, expected, opt, value):
 
2318
        self.assertEquals(expected, opt.convert_from_unicode(None, value))
 
2319
 
 
2320
    def assertCallsWarning(self, opt, value):
 
2321
        warnings = []
 
2322
 
 
2323
        def warning(*args):
 
2324
            warnings.append(args[0] % args[1:])
 
2325
        self.overrideAttr(trace, 'warning', warning)
 
2326
        self.assertEquals(None, opt.convert_from_unicode(None, value))
 
2327
        self.assertLength(1, warnings)
 
2328
        self.assertEquals(
 
2329
            'Value "%s" is not valid for "%s"' % (value, opt.name),
 
2330
            warnings[0])
 
2331
 
 
2332
    def assertCallsError(self, opt, value):
 
2333
        self.assertRaises(errors.ConfigOptionValueError,
 
2334
                          opt.convert_from_unicode, None, value)
 
2335
 
 
2336
    def assertConvertInvalid(self, opt, invalid_value):
 
2337
        opt.invalid = None
 
2338
        self.assertEquals(None, opt.convert_from_unicode(None, invalid_value))
 
2339
        opt.invalid = 'warning'
 
2340
        self.assertCallsWarning(opt, invalid_value)
 
2341
        opt.invalid = 'error'
 
2342
        self.assertCallsError(opt, invalid_value)
 
2343
 
 
2344
 
 
2345
class TestOptionWithBooleanConverter(TestOptionConverter):
 
2346
 
 
2347
    def get_option(self):
 
2348
        return config.Option('foo', help='A boolean.',
 
2349
                             from_unicode=config.bool_from_store)
 
2350
 
 
2351
    def test_convert_invalid(self):
 
2352
        opt = self.get_option()
 
2353
        # A string that is not recognized as a boolean
 
2354
        self.assertConvertInvalid(opt, u'invalid-boolean')
 
2355
        # A list of strings is never recognized as a boolean
 
2356
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
 
2357
 
 
2358
    def test_convert_valid(self):
 
2359
        opt = self.get_option()
 
2360
        self.assertConverted(True, opt, u'True')
 
2361
        self.assertConverted(True, opt, u'1')
 
2362
        self.assertConverted(False, opt, u'False')
 
2363
 
 
2364
 
 
2365
class TestOptionWithIntegerConverter(TestOptionConverter):
 
2366
 
 
2367
    def get_option(self):
 
2368
        return config.Option('foo', help='An integer.',
 
2369
                             from_unicode=config.int_from_store)
 
2370
 
 
2371
    def test_convert_invalid(self):
 
2372
        opt = self.get_option()
 
2373
        # A string that is not recognized as an integer
 
2374
        self.assertConvertInvalid(opt, u'forty-two')
 
2375
        # A list of strings is never recognized as an integer
 
2376
        self.assertConvertInvalid(opt, [u'a', u'list'])
 
2377
 
 
2378
    def test_convert_valid(self):
 
2379
        opt = self.get_option()
 
2380
        self.assertConverted(16, opt, u'16')
 
2381
 
 
2382
 
 
2383
class TestOptionWithSIUnitConverter(TestOptionConverter):
 
2384
 
 
2385
    def get_option(self):
 
2386
        return config.Option('foo', help='An integer in SI units.',
 
2387
                             from_unicode=config.int_SI_from_store)
 
2388
 
 
2389
    def test_convert_invalid(self):
 
2390
        opt = self.get_option()
 
2391
        self.assertConvertInvalid(opt, u'not-a-unit')
 
2392
        self.assertConvertInvalid(opt, u'Gb')  # Forgot the value
 
2393
        self.assertConvertInvalid(opt, u'1b')  # Forgot the unit
 
2394
        self.assertConvertInvalid(opt, u'1GG')
 
2395
        self.assertConvertInvalid(opt, u'1Mbb')
 
2396
        self.assertConvertInvalid(opt, u'1MM')
 
2397
 
 
2398
    def test_convert_valid(self):
 
2399
        opt = self.get_option()
 
2400
        self.assertConverted(int(5e3), opt, u'5kb')
 
2401
        self.assertConverted(int(5e6), opt, u'5M')
 
2402
        self.assertConverted(int(5e6), opt, u'5MB')
 
2403
        self.assertConverted(int(5e9), opt, u'5g')
 
2404
        self.assertConverted(int(5e9), opt, u'5gB')
 
2405
        self.assertConverted(100, opt, u'100')
 
2406
 
 
2407
 
 
2408
class TestListOption(TestOptionConverter):
 
2409
 
 
2410
    def get_option(self):
 
2411
        return config.ListOption('foo', help='A list.')
2465
2412
 
2466
2413
    def test_convert_invalid(self):
2467
2414
        opt = self.get_option()
2473
2420
    def test_convert_valid(self):
2474
2421
        opt = self.get_option()
2475
2422
        # An empty string is an empty list
2476
 
        self.assertConverted([], opt, '') # Using a bare str() just in case
 
2423
        self.assertConverted([], opt, '')  # Using a bare str() just in case
2477
2424
        self.assertConverted([], opt, u'')
2478
2425
        # A boolean
2479
2426
        self.assertConverted([u'True'], opt, u'True')
2483
2430
        self.assertConverted([u'bar'], opt, u'bar')
2484
2431
 
2485
2432
 
 
2433
class TestRegistryOption(TestOptionConverter):
 
2434
 
 
2435
    def get_option(self, registry):
 
2436
        return config.RegistryOption('foo', registry,
 
2437
                                     help='A registry option.')
 
2438
 
 
2439
    def test_convert_invalid(self):
 
2440
        registry = _mod_registry.Registry()
 
2441
        opt = self.get_option(registry)
 
2442
        self.assertConvertInvalid(opt, [1])
 
2443
        self.assertConvertInvalid(opt, u"notregistered")
 
2444
 
 
2445
    def test_convert_valid(self):
 
2446
        registry = _mod_registry.Registry()
 
2447
        registry.register("someval", 1234)
 
2448
        opt = self.get_option(registry)
 
2449
        # Using a bare str() just in case
 
2450
        self.assertConverted(1234, opt, "someval")
 
2451
        self.assertConverted(1234, opt, u'someval')
 
2452
        self.assertConverted(None, opt, None)
 
2453
 
 
2454
    def test_help(self):
 
2455
        registry = _mod_registry.Registry()
 
2456
        registry.register("someval", 1234, help="some option")
 
2457
        registry.register("dunno", 1234, help="some other option")
 
2458
        opt = self.get_option(registry)
 
2459
        self.assertEquals(
 
2460
            'A registry option.\n'
 
2461
            '\n'
 
2462
            'The following values are supported:\n'
 
2463
            ' dunno - some other option\n'
 
2464
            ' someval - some option\n',
 
2465
            opt.help)
 
2466
 
 
2467
    def test_get_help_text(self):
 
2468
        registry = _mod_registry.Registry()
 
2469
        registry.register("someval", 1234, help="some option")
 
2470
        registry.register("dunno", 1234, help="some other option")
 
2471
        opt = self.get_option(registry)
 
2472
        self.assertEquals(
 
2473
            'A registry option.\n'
 
2474
            '\n'
 
2475
            'The following values are supported:\n'
 
2476
            ' dunno - some other option\n'
 
2477
            ' someval - some option\n',
 
2478
            opt.get_help_text())
 
2479
 
 
2480
 
2486
2481
class TestOptionRegistry(tests.TestCase):
2487
2482
 
2488
2483
    def setUp(self):
2501
2496
        self.registry.register(opt)
2502
2497
        self.assertEquals('A simple option', self.registry.get_help('foo'))
2503
2498
 
 
2499
    def test_dont_register_illegal_name(self):
 
2500
        self.assertRaises(errors.IllegalOptionName,
 
2501
                          self.registry.register, config.Option(' foo'))
 
2502
        self.assertRaises(errors.IllegalOptionName,
 
2503
                          self.registry.register, config.Option('bar,'))
 
2504
 
2504
2505
    lazy_option = config.Option('lazy_foo', help='Lazy help')
2505
2506
 
2506
2507
    def test_register_lazy(self):
2513
2514
                                    'TestOptionRegistry.lazy_option')
2514
2515
        self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2515
2516
 
 
2517
    def test_dont_lazy_register_illegal_name(self):
 
2518
        # This is where the root cause of http://pad.lv/1235099 is better
 
2519
        # understood: 'register_lazy' doc string mentions that key should match
 
2520
        # the option name which indirectly requires that the option name is a
 
2521
        # valid python identifier. We violate that rule here (using a key that
 
2522
        # doesn't match the option name) to test the option name checking.
 
2523
        self.assertRaises(errors.IllegalOptionName,
 
2524
                          self.registry.register_lazy, ' foo', self.__module__,
 
2525
                          'TestOptionRegistry.lazy_option')
 
2526
        self.assertRaises(errors.IllegalOptionName,
 
2527
                          self.registry.register_lazy, '1,2', self.__module__,
 
2528
                          'TestOptionRegistry.lazy_option')
 
2529
 
2516
2530
 
2517
2531
class TestRegisteredOptions(tests.TestCase):
2518
2532
    """All registered options should verify some constraints."""
2531
2545
 
2532
2546
    def test_help_is_set(self):
2533
2547
        option_help = self.registry.get_help(self.option_name)
2534
 
        self.assertNotEquals(None, option_help)
2535
2548
        # Come on, think about the user, he really wants to know what the
2536
2549
        # option is about
2537
2550
        self.assertIsNot(None, option_help)
2565
2578
    scenarios = [('mutable',
2566
2579
                  {'get_section':
2567
2580
                       lambda opts: config.MutableSection('myID', opts)},),
2568
 
                 ('cmdline',
2569
 
                  {'get_section':
2570
 
                       lambda opts: config.CommandLineSection(opts)},),
2571
2581
        ]
2572
2582
 
2573
2583
    def test_set(self):
2615
2625
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2616
2626
 
2617
2627
 
2618
 
class TestCommandLineSection(tests.TestCase):
 
2628
class TestCommandLineStore(tests.TestCase):
2619
2629
 
2620
2630
    def setUp(self):
2621
 
        super(TestCommandLineSection, self).setUp()
2622
 
        self.section = config.CommandLineSection()
 
2631
        super(TestCommandLineStore, self).setUp()
 
2632
        self.store = config.CommandLineStore()
 
2633
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
2634
 
 
2635
    def get_section(self):
 
2636
        """Get the unique section for the command line overrides."""
 
2637
        sections = list(self.store.get_sections())
 
2638
        self.assertLength(1, sections)
 
2639
        store, section = sections[0]
 
2640
        self.assertEquals(self.store, store)
 
2641
        return section
2623
2642
 
2624
2643
    def test_no_override(self):
2625
 
        self.section._from_cmdline([])
2626
 
        # FIXME: we want some iterator over all options, failing that, we peek
2627
 
        # under the cover -- vila 2011-09026
2628
 
        self.assertLength(0, self.section.options)
 
2644
        self.store._from_cmdline([])
 
2645
        section = self.get_section()
 
2646
        self.assertLength(0, list(section.iter_option_names()))
2629
2647
 
2630
2648
    def test_simple_override(self):
2631
 
        self.section._from_cmdline(['a=b'])
2632
 
        self.assertEqual('b', self.section.get('a'))
 
2649
        self.store._from_cmdline(['a=b'])
 
2650
        section = self.get_section()
 
2651
        self.assertEqual('b', section.get('a'))
2633
2652
 
2634
2653
    def test_list_override(self):
2635
 
        self.section._from_cmdline(['l=1,2,3'])
2636
 
        val = self.section.get('l')
 
2654
        opt = config.ListOption('l')
 
2655
        config.option_registry.register(opt)
 
2656
        self.store._from_cmdline(['l=1,2,3'])
 
2657
        val = self.get_section().get('l')
2637
2658
        self.assertEqual('1,2,3', val)
2638
 
        # Reminder: lists should registered as such explicitely, otherwise the
2639
 
        # conversion needs to be done afterwards.
2640
 
        self.assertEqual(['1', '2', '3'], config.list_from_store(val))
 
2659
        # Reminder: lists should be registered as such explicitely, otherwise
 
2660
        # the conversion needs to be done afterwards.
 
2661
        self.assertEqual(['1', '2', '3'],
 
2662
                         opt.convert_from_unicode(self.store, val))
2641
2663
 
2642
2664
    def test_multiple_overrides(self):
2643
 
        self.section._from_cmdline(['a=b', 'x=y'])
2644
 
        self.assertEquals('b', self.section.get('a'))
2645
 
        self.assertEquals('y', self.section.get('x'))
 
2665
        self.store._from_cmdline(['a=b', 'x=y'])
 
2666
        section = self.get_section()
 
2667
        self.assertEquals('b', section.get('a'))
 
2668
        self.assertEquals('y', section.get('x'))
2646
2669
 
2647
2670
    def test_wrong_syntax(self):
2648
2671
        self.assertRaises(errors.BzrCommandError,
2649
 
                          self.section._from_cmdline, ['a=b', 'c'])
 
2672
                          self.store._from_cmdline, ['a=b', 'c'])
 
2673
 
 
2674
class TestStoreMinimalAPI(tests.TestCaseWithTransport):
 
2675
 
 
2676
    scenarios = [(key, {'get_store': builder}) for key, builder
 
2677
                 in config.test_store_builder_registry.iteritems()] + [
 
2678
        ('cmdline', {'get_store': lambda test: config.CommandLineStore()})]
 
2679
 
 
2680
    def test_id(self):
 
2681
        store = self.get_store(self)
 
2682
        if type(store) == config.TransportIniFileStore:
 
2683
            raise tests.TestNotApplicable(
 
2684
                "%s is not a concrete Store implementation"
 
2685
                " so it doesn't need an id" % (store.__class__.__name__,))
 
2686
        self.assertIsNot(None, store.id)
2650
2687
 
2651
2688
 
2652
2689
class TestStore(tests.TestCaseWithTransport):
2653
2690
 
2654
 
    def assertSectionContent(self, expected, section):
 
2691
    def assertSectionContent(self, expected, (store, section)):
2655
2692
        """Assert that some options have the proper values in a section."""
2656
2693
        expected_name, expected_options = expected
2657
2694
        self.assertEquals(expected_name, section.id)
2696
2733
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2697
2734
 
2698
2735
 
 
2736
class TestStoreQuoting(TestStore):
 
2737
 
 
2738
    scenarios = [(key, {'get_store': builder}) for key, builder
 
2739
                 in config.test_store_builder_registry.iteritems()]
 
2740
 
 
2741
    def setUp(self):
 
2742
        super(TestStoreQuoting, self).setUp()
 
2743
        self.store = self.get_store(self)
 
2744
        # We need a loaded store but any content will do
 
2745
        self.store._load_from_string('')
 
2746
 
 
2747
    def assertIdempotent(self, s):
 
2748
        """Assert that quoting an unquoted string is a no-op and vice-versa.
 
2749
 
 
2750
        What matters here is that option values, as they appear in a store, can
 
2751
        be safely round-tripped out of the store and back.
 
2752
 
 
2753
        :param s: A string, quoted if required.
 
2754
        """
 
2755
        self.assertEquals(s, self.store.quote(self.store.unquote(s)))
 
2756
        self.assertEquals(s, self.store.unquote(self.store.quote(s)))
 
2757
 
 
2758
    def test_empty_string(self):
 
2759
        if isinstance(self.store, config.IniFileStore):
 
2760
            # configobj._quote doesn't handle empty values
 
2761
            self.assertRaises(AssertionError,
 
2762
                              self.assertIdempotent, '')
 
2763
        else:
 
2764
            self.assertIdempotent('')
 
2765
        # But quoted empty strings are ok
 
2766
        self.assertIdempotent('""')
 
2767
 
 
2768
    def test_embedded_spaces(self):
 
2769
        self.assertIdempotent('" a b c "')
 
2770
 
 
2771
    def test_embedded_commas(self):
 
2772
        self.assertIdempotent('" a , b c "')
 
2773
 
 
2774
    def test_simple_comma(self):
 
2775
        if isinstance(self.store, config.IniFileStore):
 
2776
            # configobj requires that lists are special-cased
 
2777
           self.assertRaises(AssertionError,
 
2778
                             self.assertIdempotent, ',')
 
2779
        else:
 
2780
            self.assertIdempotent(',')
 
2781
        # When a single comma is required, quoting is also required
 
2782
        self.assertIdempotent('","')
 
2783
 
 
2784
    def test_list(self):
 
2785
        if isinstance(self.store, config.IniFileStore):
 
2786
            # configobj requires that lists are special-cased
 
2787
            self.assertRaises(AssertionError,
 
2788
                              self.assertIdempotent, 'a,b')
 
2789
        else:
 
2790
            self.assertIdempotent('a,b')
 
2791
 
 
2792
 
 
2793
class TestDictFromStore(tests.TestCase):
 
2794
 
 
2795
    def test_unquote_not_string(self):
 
2796
        conf = config.MemoryStack('x=2\n[a_section]\na=1\n')
 
2797
        value = conf.get('a_section')
 
2798
        # Urgh, despite 'conf' asking for the no-name section, we get the
 
2799
        # content of another section as a dict o_O
 
2800
        self.assertEquals({'a': '1'}, value)
 
2801
        unquoted = conf.store.unquote(value)
 
2802
        # Which cannot be unquoted but shouldn't crash either (the use cases
 
2803
        # are getting the value or displaying it. In the later case, '%s' will
 
2804
        # do).
 
2805
        self.assertEquals({'a': '1'}, unquoted)
 
2806
        self.assertEquals("{u'a': u'1'}", '%s' % (unquoted,))
 
2807
 
 
2808
 
2699
2809
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2700
2810
    """Simulate loading a config store with content of various encodings.
2701
2811
 
2716
2826
        utf8_content = unicode_content.encode('utf8')
2717
2827
        # Store the raw content in the config file
2718
2828
        t.put_bytes('foo.conf', utf8_content)
2719
 
        store = config.IniFileStore(t, 'foo.conf')
 
2829
        store = config.TransportIniFileStore(t, 'foo.conf')
2720
2830
        store.load()
2721
2831
        stack = config.Stack([store.get_sections], store)
2722
2832
        self.assertEquals(unicode_user, stack.get('user'))
2725
2835
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2726
2836
        t = self.get_transport()
2727
2837
        t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2728
 
        store = config.IniFileStore(t, 'foo.conf')
 
2838
        store = config.TransportIniFileStore(t, 'foo.conf')
2729
2839
        self.assertRaises(errors.ConfigContentError, store.load)
2730
2840
 
2731
2841
    def test_load_erroneous_content(self):
2732
2842
        """Ensure we display a proper error on content that can't be parsed."""
2733
2843
        t = self.get_transport()
2734
2844
        t.put_bytes('foo.conf', '[open_section\n')
2735
 
        store = config.IniFileStore(t, 'foo.conf')
 
2845
        store = config.TransportIniFileStore(t, 'foo.conf')
2736
2846
        self.assertRaises(errors.ParseConfigError, store.load)
2737
2847
 
2738
2848
    def test_load_permission_denied(self):
2747
2857
        def get_bytes(relpath):
2748
2858
            raise errors.PermissionDenied(relpath, "")
2749
2859
        t.get_bytes = get_bytes
2750
 
        store = config.IniFileStore(t, 'foo.conf')
 
2860
        store = config.TransportIniFileStore(t, 'foo.conf')
2751
2861
        self.assertRaises(errors.PermissionDenied, store.load)
2752
2862
        self.assertEquals(
2753
2863
            warnings,
2817
2927
        store.save()
2818
2928
        self.assertEquals(False, self.has_store(store))
2819
2929
 
 
2930
    def test_mutable_section_shared(self):
 
2931
        store = self.get_store(self)
 
2932
        store._load_from_string('foo=bar\n')
 
2933
        # FIXME: There should be a better way than relying on the test
 
2934
        # parametrization to identify branch.conf -- vila 2011-0526
 
2935
        if self.store_id in ('branch', 'remote_branch'):
 
2936
            # branch stores requires write locked branches
 
2937
            self.addCleanup(store.branch.lock_write().unlock)
 
2938
        section1 = store.get_mutable_section(None)
 
2939
        section2 = store.get_mutable_section(None)
 
2940
        # If we get different sections, different callers won't share the
 
2941
        # modification
 
2942
        self.assertIs(section1, section2)
 
2943
 
2820
2944
    def test_save_emptied_succeeds(self):
2821
2945
        store = self.get_store(self)
2822
2946
        store._load_from_string('foo=bar\n')
 
2947
        # FIXME: There should be a better way than relying on the test
 
2948
        # parametrization to identify branch.conf -- vila 2011-0526
 
2949
        if self.store_id in ('branch', 'remote_branch'):
 
2950
            # branch stores requires write locked branches
 
2951
            self.addCleanup(store.branch.lock_write().unlock)
2823
2952
        section = store.get_mutable_section(None)
2824
2953
        section.remove('foo')
2825
2954
        store.save()
2846
2975
 
2847
2976
    def test_set_option_in_empty_store(self):
2848
2977
        store = self.get_store(self)
 
2978
        # FIXME: There should be a better way than relying on the test
 
2979
        # parametrization to identify branch.conf -- vila 2011-0526
 
2980
        if self.store_id in ('branch', 'remote_branch'):
 
2981
            # branch stores requires write locked branches
 
2982
            self.addCleanup(store.branch.lock_write().unlock)
2849
2983
        section = store.get_mutable_section(None)
2850
2984
        section.set('foo', 'bar')
2851
2985
        store.save()
2857
2991
    def test_set_option_in_default_section(self):
2858
2992
        store = self.get_store(self)
2859
2993
        store._load_from_string('')
 
2994
        # FIXME: There should be a better way than relying on the test
 
2995
        # parametrization to identify branch.conf -- vila 2011-0526
 
2996
        if self.store_id in ('branch', 'remote_branch'):
 
2997
            # branch stores requires write locked branches
 
2998
            self.addCleanup(store.branch.lock_write().unlock)
2860
2999
        section = store.get_mutable_section(None)
2861
3000
        section.set('foo', 'bar')
2862
3001
        store.save()
2868
3007
    def test_set_option_in_named_section(self):
2869
3008
        store = self.get_store(self)
2870
3009
        store._load_from_string('')
 
3010
        # FIXME: There should be a better way than relying on the test
 
3011
        # parametrization to identify branch.conf -- vila 2011-0526
 
3012
        if self.store_id in ('branch', 'remote_branch'):
 
3013
            # branch stores requires write locked branches
 
3014
            self.addCleanup(store.branch.lock_write().unlock)
2871
3015
        section = store.get_mutable_section('baz')
2872
3016
        section.set('foo', 'bar')
2873
3017
        store.save()
2877
3021
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2878
3022
 
2879
3023
    def test_load_hook(self):
2880
 
        # We first needs to ensure that the store exists
 
3024
        # First, we need to ensure that the store exists
2881
3025
        store = self.get_store(self)
 
3026
        # FIXME: There should be a better way than relying on the test
 
3027
        # parametrization to identify branch.conf -- vila 2011-0526
 
3028
        if self.store_id in ('branch', 'remote_branch'):
 
3029
            # branch stores requires write locked branches
 
3030
            self.addCleanup(store.branch.lock_write().unlock)
2882
3031
        section = store.get_mutable_section('baz')
2883
3032
        section.set('foo', 'bar')
2884
3033
        store.save()
2900
3049
        config.ConfigHooks.install_named_hook('save', hook, None)
2901
3050
        self.assertLength(0, calls)
2902
3051
        store = self.get_store(self)
 
3052
        # FIXME: There should be a better way than relying on the test
 
3053
        # parametrization to identify branch.conf -- vila 2011-0526
 
3054
        if self.store_id in ('branch', 'remote_branch'):
 
3055
            # branch stores requires write locked branches
 
3056
            self.addCleanup(store.branch.lock_write().unlock)
2903
3057
        section = store.get_mutable_section('baz')
2904
3058
        section.set('foo', 'bar')
2905
3059
        store.save()
2906
3060
        self.assertLength(1, calls)
2907
3061
        self.assertEquals((store,), calls[0])
2908
3062
 
2909
 
 
2910
 
class TestIniFileStore(TestStore):
 
3063
    def test_set_mark_dirty(self):
 
3064
        stack = config.MemoryStack('')
 
3065
        self.assertLength(0, stack.store.dirty_sections)
 
3066
        stack.set('foo', 'baz')
 
3067
        self.assertLength(1, stack.store.dirty_sections)
 
3068
        self.assertTrue(stack.store._need_saving())
 
3069
 
 
3070
    def test_remove_mark_dirty(self):
 
3071
        stack = config.MemoryStack('foo=bar')
 
3072
        self.assertLength(0, stack.store.dirty_sections)
 
3073
        stack.remove('foo')
 
3074
        self.assertLength(1, stack.store.dirty_sections)
 
3075
        self.assertTrue(stack.store._need_saving())
 
3076
 
 
3077
 
 
3078
class TestStoreSaveChanges(tests.TestCaseWithTransport):
 
3079
    """Tests that config changes are kept in memory and saved on-demand."""
 
3080
 
 
3081
    def setUp(self):
 
3082
        super(TestStoreSaveChanges, self).setUp()
 
3083
        self.transport = self.get_transport()
 
3084
        # Most of the tests involve two stores pointing to the same persistent
 
3085
        # storage to observe the effects of concurrent changes
 
3086
        self.st1 = config.TransportIniFileStore(self.transport, 'foo.conf')
 
3087
        self.st2 = config.TransportIniFileStore(self.transport, 'foo.conf')
 
3088
        self.warnings = []
 
3089
        def warning(*args):
 
3090
            self.warnings.append(args[0] % args[1:])
 
3091
        self.overrideAttr(trace, 'warning', warning)
 
3092
 
 
3093
    def has_store(self, store):
 
3094
        store_basename = urlutils.relative_url(self.transport.external_url(),
 
3095
                                               store.external_url())
 
3096
        return self.transport.has(store_basename)
 
3097
 
 
3098
    def get_stack(self, store):
 
3099
        # Any stack will do as long as it uses the right store, just a single
 
3100
        # no-name section is enough
 
3101
        return config.Stack([store.get_sections], store)
 
3102
 
 
3103
    def test_no_changes_no_save(self):
 
3104
        s = self.get_stack(self.st1)
 
3105
        s.store.save_changes()
 
3106
        self.assertEquals(False, self.has_store(self.st1))
 
3107
 
 
3108
    def test_unrelated_concurrent_update(self):
 
3109
        s1 = self.get_stack(self.st1)
 
3110
        s2 = self.get_stack(self.st2)
 
3111
        s1.set('foo', 'bar')
 
3112
        s2.set('baz', 'quux')
 
3113
        s1.store.save()
 
3114
        # Changes don't propagate magically
 
3115
        self.assertEquals(None, s1.get('baz'))
 
3116
        s2.store.save_changes()
 
3117
        self.assertEquals('quux', s2.get('baz'))
 
3118
        # Changes are acquired when saving
 
3119
        self.assertEquals('bar', s2.get('foo'))
 
3120
        # Since there is no overlap, no warnings are emitted
 
3121
        self.assertLength(0, self.warnings)
 
3122
 
 
3123
    def test_concurrent_update_modified(self):
 
3124
        s1 = self.get_stack(self.st1)
 
3125
        s2 = self.get_stack(self.st2)
 
3126
        s1.set('foo', 'bar')
 
3127
        s2.set('foo', 'baz')
 
3128
        s1.store.save()
 
3129
        # Last speaker wins
 
3130
        s2.store.save_changes()
 
3131
        self.assertEquals('baz', s2.get('foo'))
 
3132
        # But the user get a warning
 
3133
        self.assertLength(1, self.warnings)
 
3134
        warning = self.warnings[0]
 
3135
        self.assertStartsWith(warning, 'Option foo in section None')
 
3136
        self.assertEndsWith(warning, 'was changed from <CREATED> to bar.'
 
3137
                            ' The baz value will be saved.')
 
3138
 
 
3139
    def test_concurrent_deletion(self):
 
3140
        self.st1._load_from_string('foo=bar')
 
3141
        self.st1.save()
 
3142
        s1 = self.get_stack(self.st1)
 
3143
        s2 = self.get_stack(self.st2)
 
3144
        s1.remove('foo')
 
3145
        s2.remove('foo')
 
3146
        s1.store.save_changes()
 
3147
        # No warning yet
 
3148
        self.assertLength(0, self.warnings)
 
3149
        s2.store.save_changes()
 
3150
        # Now we get one
 
3151
        self.assertLength(1, self.warnings)
 
3152
        warning = self.warnings[0]
 
3153
        self.assertStartsWith(warning, 'Option foo in section None')
 
3154
        self.assertEndsWith(warning, 'was changed from bar to <CREATED>.'
 
3155
                            ' The <DELETED> value will be saved.')
 
3156
 
 
3157
 
 
3158
class TestQuotingIniFileStore(tests.TestCaseWithTransport):
 
3159
 
 
3160
    def get_store(self):
 
3161
        return config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
3162
 
 
3163
    def test_get_quoted_string(self):
 
3164
        store = self.get_store()
 
3165
        store._load_from_string('foo= " abc "')
 
3166
        stack = config.Stack([store.get_sections])
 
3167
        self.assertEquals(' abc ', stack.get('foo'))
 
3168
 
 
3169
    def test_set_quoted_string(self):
 
3170
        store = self.get_store()
 
3171
        stack = config.Stack([store.get_sections], store)
 
3172
        stack.set('foo', ' a b c ')
 
3173
        store.save()
 
3174
        self.assertFileEqual('foo = " a b c "' + os.linesep, 'foo.conf')
 
3175
 
 
3176
 
 
3177
class TestTransportIniFileStore(TestStore):
2911
3178
 
2912
3179
    def test_loading_unknown_file_fails(self):
2913
 
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
 
3180
        store = config.TransportIniFileStore(self.get_transport(),
 
3181
            'I-do-not-exist')
2914
3182
        self.assertRaises(errors.NoSuchFile, store.load)
2915
3183
 
2916
3184
    def test_invalid_content(self):
2917
 
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
3185
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2918
3186
        self.assertEquals(False, store.is_loaded())
2919
3187
        exc = self.assertRaises(
2920
3188
            errors.ParseConfigError, store._load_from_string,
2928
3196
        # option names share the same name space...)
2929
3197
        # FIXME: This should be fixed by forbidding dicts as values ?
2930
3198
        # -- vila 2011-04-05
2931
 
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
3199
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2932
3200
        store._load_from_string('''
2933
3201
foo=bar
2934
3202
l=1,2
2983
3251
 
2984
3252
    def setUp(self):
2985
3253
        super(TestConcurrentStoreUpdates, self).setUp()
2986
 
        self._content = 'one=1\ntwo=2\n'
2987
3254
        self.stack = self.get_stack(self)
2988
3255
        if not isinstance(self.stack, config._CompatibleStack):
2989
3256
            raise tests.TestNotApplicable(
2990
3257
                '%s is not meant to be compatible with the old config design'
2991
3258
                % (self.stack,))
2992
 
        self.stack.store._load_from_string(self._content)
 
3259
        self.stack.set('one', '1')
 
3260
        self.stack.set('two', '2')
2993
3261
        # Flush the store
2994
3262
        self.stack.store.save()
2995
3263
 
3120
3388
 
3121
3389
    def test_build_doesnt_load_store(self):
3122
3390
        store = self.get_store(self)
3123
 
        matcher = self.matcher(store, '/bar')
 
3391
        self.matcher(store, '/bar')
3124
3392
        self.assertFalse(store.is_loaded())
3125
3393
 
3126
3394
 
3128
3396
 
3129
3397
    def get_section(self, options, extra_path):
3130
3398
        section = config.Section('foo', options)
3131
 
        # We don't care about the length so we use '0'
3132
 
        return config.LocationSection(section, 0, extra_path)
 
3399
        return config.LocationSection(section, extra_path)
3133
3400
 
3134
3401
    def test_simple_option(self):
3135
3402
        section = self.get_section({'foo': 'bar'}, '')
3170
3437
''')
3171
3438
        self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3172
3439
                           '/quux/quux'],
3173
 
                          [section.id for section in store.get_sections()])
 
3440
                          [section.id for _, section in store.get_sections()])
3174
3441
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
3175
 
        sections = list(matcher.get_sections())
3176
 
        self.assertEquals([3, 2],
3177
 
                          [section.length for section in sections])
 
3442
        sections = [section for _, section in matcher.get_sections()]
3178
3443
        self.assertEquals(['/foo/bar', '/foo'],
3179
3444
                          [section.id for section in sections])
3180
3445
        self.assertEquals(['quux', 'bar/quux'],
3189
3454
section=/foo/bar
3190
3455
''')
3191
3456
        self.assertEquals(['/foo', '/foo/bar'],
3192
 
                          [section.id for section in store.get_sections()])
 
3457
                          [section.id for _, section in store.get_sections()])
3193
3458
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
3194
 
        sections = list(matcher.get_sections())
3195
 
        self.assertEquals([3, 2],
3196
 
                          [section.length for section in sections])
 
3459
        sections = [section for _, section in matcher.get_sections()]
3197
3460
        self.assertEquals(['/foo/bar', '/foo'],
3198
3461
                          [section.id for section in sections])
3199
3462
        self.assertEquals(['baz', 'bar/baz'],
3210
3473
        matcher = config.LocationMatcher(store, 'dir/subdir')
3211
3474
        sections = list(matcher.get_sections())
3212
3475
        self.assertLength(1, sections)
3213
 
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
 
3476
        self.assertEquals('bar/dir/subdir', sections[0][1].get('foo'))
3214
3477
 
3215
3478
    def test_file_urls_are_normalized(self):
3216
3479
        store = self.get_store(self)
3223
3486
        matcher = config.LocationMatcher(store, expected_url)
3224
3487
        self.assertEquals(expected_location, matcher.location)
3225
3488
 
 
3489
    def test_branch_name_colo(self):
 
3490
        store = self.get_store(self)
 
3491
        store._load_from_string(dedent("""\
 
3492
            [/]
 
3493
            push_location=my{branchname}
 
3494
        """))
 
3495
        matcher = config.LocationMatcher(store, 'file:///,branch=example%3c')
 
3496
        self.assertEqual('example<', matcher.branch_name)
 
3497
        ((_, section),) = matcher.get_sections()
 
3498
        self.assertEqual('example<', section.locals['branchname'])
 
3499
 
 
3500
    def test_branch_name_basename(self):
 
3501
        store = self.get_store(self)
 
3502
        store._load_from_string(dedent("""\
 
3503
            [/]
 
3504
            push_location=my{branchname}
 
3505
        """))
 
3506
        matcher = config.LocationMatcher(store, 'file:///parent/example%3c')
 
3507
        self.assertEqual('example<', matcher.branch_name)
 
3508
        ((_, section),) = matcher.get_sections()
 
3509
        self.assertEqual('example<', section.locals['branchname'])
 
3510
 
 
3511
 
 
3512
class TestStartingPathMatcher(TestStore):
 
3513
 
 
3514
    def setUp(self):
 
3515
        super(TestStartingPathMatcher, self).setUp()
 
3516
        # Any simple store is good enough
 
3517
        self.store = config.IniFileStore()
 
3518
 
 
3519
    def assertSectionIDs(self, expected, location, content):
 
3520
        self.store._load_from_string(content)
 
3521
        matcher = config.StartingPathMatcher(self.store, location)
 
3522
        sections = list(matcher.get_sections())
 
3523
        self.assertLength(len(expected), sections)
 
3524
        self.assertEqual(expected, [section.id for _, section in sections])
 
3525
        return sections
 
3526
 
 
3527
    def test_empty(self):
 
3528
        self.assertSectionIDs([], self.get_url(), '')
 
3529
 
 
3530
    def test_url_vs_local_paths(self):
 
3531
        # The matcher location is an url and the section names are local paths
 
3532
        self.assertSectionIDs(['/foo/bar', '/foo'],
 
3533
                              'file:///foo/bar/baz', '''\
 
3534
[/foo]
 
3535
[/foo/bar]
 
3536
''')
 
3537
 
 
3538
    def test_local_path_vs_url(self):
 
3539
        # The matcher location is a local path and the section names are urls
 
3540
        self.assertSectionIDs(['file:///foo/bar', 'file:///foo'],
 
3541
                              '/foo/bar/baz', '''\
 
3542
[file:///foo]
 
3543
[file:///foo/bar]
 
3544
''')
 
3545
 
 
3546
 
 
3547
    def test_no_name_section_included_when_present(self):
 
3548
        # Note that other tests will cover the case where the no-name section
 
3549
        # is empty and as such, not included.
 
3550
        sections = self.assertSectionIDs(['/foo/bar', '/foo', None],
 
3551
                                         '/foo/bar/baz', '''\
 
3552
option = defined so the no-name section exists
 
3553
[/foo]
 
3554
[/foo/bar]
 
3555
''')
 
3556
        self.assertEquals(['baz', 'bar/baz', '/foo/bar/baz'],
 
3557
                          [s.locals['relpath'] for _, s in sections])
 
3558
 
 
3559
    def test_order_reversed(self):
 
3560
        self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
 
3561
[/foo]
 
3562
[/foo/bar]
 
3563
''')
 
3564
 
 
3565
    def test_unrelated_section_excluded(self):
 
3566
        self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
 
3567
[/foo]
 
3568
[/foo/qux]
 
3569
[/foo/bar]
 
3570
''')
 
3571
 
 
3572
    def test_glob_included(self):
 
3573
        sections = self.assertSectionIDs(['/foo/*/baz', '/foo/b*', '/foo'],
 
3574
                                         '/foo/bar/baz', '''\
 
3575
[/foo]
 
3576
[/foo/qux]
 
3577
[/foo/b*]
 
3578
[/foo/*/baz]
 
3579
''')
 
3580
        # Note that 'baz' as a relpath for /foo/b* is not fully correct, but
 
3581
        # nothing really is... as far using {relpath} to append it to something
 
3582
        # else, this seems good enough though.
 
3583
        self.assertEquals(['', 'baz', 'bar/baz'],
 
3584
                          [s.locals['relpath'] for _, s in sections])
 
3585
 
 
3586
    def test_respect_order(self):
 
3587
        self.assertSectionIDs(['/foo', '/foo/b*', '/foo/*/baz'],
 
3588
                              '/foo/bar/baz', '''\
 
3589
[/foo/*/baz]
 
3590
[/foo/qux]
 
3591
[/foo/b*]
 
3592
[/foo]
 
3593
''')
 
3594
 
3226
3595
 
3227
3596
class TestNameMatcher(TestStore):
3228
3597
 
3255
3624
        self.assertLength(0, sections)
3256
3625
 
3257
3626
 
3258
 
class TestStackGet(tests.TestCase):
3259
 
 
3260
 
    # FIXME: This should be parametrized for all known Stack or dedicated
3261
 
    # paramerized tests created to avoid bloating -- vila 2011-03-31
3262
 
 
3263
 
    def overrideOptionRegistry(self):
 
3627
class TestBaseStackGet(tests.TestCase):
 
3628
 
 
3629
    def setUp(self):
 
3630
        super(TestBaseStackGet, self).setUp()
3264
3631
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3265
3632
 
3266
 
    def test_single_config_get(self):
3267
 
        conf = dict(foo='bar')
3268
 
        conf_stack = config.Stack([conf])
3269
 
        self.assertEquals('bar', conf_stack.get('foo'))
 
3633
    def test_get_first_definition(self):
 
3634
        store1 = config.IniFileStore()
 
3635
        store1._load_from_string('foo=bar')
 
3636
        store2 = config.IniFileStore()
 
3637
        store2._load_from_string('foo=baz')
 
3638
        conf = config.Stack([store1.get_sections, store2.get_sections])
 
3639
        self.assertEquals('bar', conf.get('foo'))
3270
3640
 
3271
3641
    def test_get_with_registered_default_value(self):
3272
 
        conf_stack = config.Stack([dict()])
3273
 
        opt = config.Option('foo', default='bar')
3274
 
        self.overrideOptionRegistry()
3275
 
        config.option_registry.register('foo', opt)
 
3642
        config.option_registry.register(config.Option('foo', default='bar'))
 
3643
        conf_stack = config.Stack([])
3276
3644
        self.assertEquals('bar', conf_stack.get('foo'))
3277
3645
 
3278
3646
    def test_get_without_registered_default_value(self):
3279
 
        conf_stack = config.Stack([dict()])
3280
 
        opt = config.Option('foo')
3281
 
        self.overrideOptionRegistry()
3282
 
        config.option_registry.register('foo', opt)
 
3647
        config.option_registry.register(config.Option('foo'))
 
3648
        conf_stack = config.Stack([])
3283
3649
        self.assertEquals(None, conf_stack.get('foo'))
3284
3650
 
3285
3651
    def test_get_without_default_value_for_not_registered(self):
3286
 
        conf_stack = config.Stack([dict()])
3287
 
        opt = config.Option('foo')
3288
 
        self.overrideOptionRegistry()
 
3652
        conf_stack = config.Stack([])
3289
3653
        self.assertEquals(None, conf_stack.get('foo'))
3290
3654
 
3291
 
    def test_get_first_definition(self):
3292
 
        conf1 = dict(foo='bar')
3293
 
        conf2 = dict(foo='baz')
3294
 
        conf_stack = config.Stack([conf1, conf2])
3295
 
        self.assertEquals('bar', conf_stack.get('foo'))
3296
 
 
3297
 
    def test_get_embedded_definition(self):
3298
 
        conf1 = dict(yy='12')
3299
 
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
3300
 
        conf_stack = config.Stack([conf1, conf2])
3301
 
        self.assertEquals('baz', conf_stack.get('foo'))
3302
 
 
3303
3655
    def test_get_for_empty_section_callable(self):
3304
3656
        conf_stack = config.Stack([lambda : []])
3305
3657
        self.assertEquals(None, conf_stack.get('foo'))
3306
3658
 
3307
3659
    def test_get_for_broken_callable(self):
3308
3660
        # Trying to use and invalid callable raises an exception on first use
3309
 
        conf_stack = config.Stack([lambda : object()])
 
3661
        conf_stack = config.Stack([object])
3310
3662
        self.assertRaises(TypeError, conf_stack.get, 'foo')
3311
3663
 
3312
3664
 
 
3665
class TestStackWithSimpleStore(tests.TestCase):
 
3666
 
 
3667
    def setUp(self):
 
3668
        super(TestStackWithSimpleStore, self).setUp()
 
3669
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3670
        self.registry = config.option_registry
 
3671
 
 
3672
    def get_conf(self, content=None):
 
3673
        return config.MemoryStack(content)
 
3674
 
 
3675
    def test_override_value_from_env(self):
 
3676
        self.overrideEnv('FOO', None)
 
3677
        self.registry.register(
 
3678
            config.Option('foo', default='bar', override_from_env=['FOO']))
 
3679
        self.overrideEnv('FOO', 'quux')
 
3680
        # Env variable provides a default taking over the option one
 
3681
        conf = self.get_conf('foo=store')
 
3682
        self.assertEquals('quux', conf.get('foo'))
 
3683
 
 
3684
    def test_first_override_value_from_env_wins(self):
 
3685
        self.overrideEnv('NO_VALUE', None)
 
3686
        self.overrideEnv('FOO', None)
 
3687
        self.overrideEnv('BAZ', None)
 
3688
        self.registry.register(
 
3689
            config.Option('foo', default='bar',
 
3690
                          override_from_env=['NO_VALUE', 'FOO', 'BAZ']))
 
3691
        self.overrideEnv('FOO', 'foo')
 
3692
        self.overrideEnv('BAZ', 'baz')
 
3693
        # The first env var set wins
 
3694
        conf = self.get_conf('foo=store')
 
3695
        self.assertEquals('foo', conf.get('foo'))
 
3696
 
 
3697
 
 
3698
class TestMemoryStack(tests.TestCase):
 
3699
 
 
3700
    def test_get(self):
 
3701
        conf = config.MemoryStack('foo=bar')
 
3702
        self.assertEquals('bar', conf.get('foo'))
 
3703
 
 
3704
    def test_set(self):
 
3705
        conf = config.MemoryStack('foo=bar')
 
3706
        conf.set('foo', 'baz')
 
3707
        self.assertEquals('baz', conf.get('foo'))
 
3708
 
 
3709
    def test_no_content(self):
 
3710
        conf = config.MemoryStack()
 
3711
        # No content means no loading
 
3712
        self.assertFalse(conf.store.is_loaded())
 
3713
        self.assertRaises(NotImplementedError, conf.get, 'foo')
 
3714
        # But a content can still be provided
 
3715
        conf.store._load_from_string('foo=bar')
 
3716
        self.assertEquals('bar', conf.get('foo'))
 
3717
 
 
3718
 
 
3719
class TestStackIterSections(tests.TestCase):
 
3720
 
 
3721
    def test_empty_stack(self):
 
3722
        conf = config.Stack([])
 
3723
        sections = list(conf.iter_sections())
 
3724
        self.assertLength(0, sections)
 
3725
 
 
3726
    def test_empty_store(self):
 
3727
        store = config.IniFileStore()
 
3728
        store._load_from_string('')
 
3729
        conf = config.Stack([store.get_sections])
 
3730
        sections = list(conf.iter_sections())
 
3731
        self.assertLength(0, sections)
 
3732
 
 
3733
    def test_simple_store(self):
 
3734
        store = config.IniFileStore()
 
3735
        store._load_from_string('foo=bar')
 
3736
        conf = config.Stack([store.get_sections])
 
3737
        tuples = list(conf.iter_sections())
 
3738
        self.assertLength(1, tuples)
 
3739
        (found_store, found_section) = tuples[0]
 
3740
        self.assertIs(store, found_store)
 
3741
 
 
3742
    def test_two_stores(self):
 
3743
        store1 = config.IniFileStore()
 
3744
        store1._load_from_string('foo=bar')
 
3745
        store2 = config.IniFileStore()
 
3746
        store2._load_from_string('bar=qux')
 
3747
        conf = config.Stack([store1.get_sections, store2.get_sections])
 
3748
        tuples = list(conf.iter_sections())
 
3749
        self.assertLength(2, tuples)
 
3750
        self.assertIs(store1, tuples[0][0])
 
3751
        self.assertIs(store2, tuples[1][0])
 
3752
 
 
3753
 
3313
3754
class TestStackWithTransport(tests.TestCaseWithTransport):
3314
3755
 
3315
3756
    scenarios = [(key, {'get_stack': builder}) for key, builder
3320
3761
 
3321
3762
    def test_build_stack(self):
3322
3763
        # Just a smoke test to help debug builders
3323
 
        stack = self.get_stack(self)
 
3764
        self.get_stack(self)
3324
3765
 
3325
3766
 
3326
3767
class TestStackGet(TestStackWithTransport):
3333
3774
        self.assertEquals(None, self.conf.get('foo'))
3334
3775
 
3335
3776
    def test_get_hook(self):
3336
 
        self.conf.store._load_from_string('foo=bar')
 
3777
        self.conf.set('foo', 'bar')
3337
3778
        calls = []
3338
3779
        def hook(*args):
3339
3780
            calls.append(args)
3345
3786
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3346
3787
 
3347
3788
 
3348
 
class TestStackGetWithConverter(TestStackGet):
 
3789
class TestStackGetWithConverter(tests.TestCase):
3349
3790
 
3350
3791
    def setUp(self):
3351
3792
        super(TestStackGetWithConverter, self).setUp()
3352
3793
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3353
3794
        self.registry = config.option_registry
3354
3795
 
 
3796
    def get_conf(self, content=None):
 
3797
        return config.MemoryStack(content)
 
3798
 
3355
3799
    def register_bool_option(self, name, default=None, default_from_env=None):
3356
3800
        b = config.Option(name, help='A boolean.',
3357
3801
                          default=default, default_from_env=default_from_env,
3360
3804
 
3361
3805
    def test_get_default_bool_None(self):
3362
3806
        self.register_bool_option('foo')
3363
 
        self.assertEquals(None, self.conf.get('foo'))
 
3807
        conf = self.get_conf('')
 
3808
        self.assertEquals(None, conf.get('foo'))
3364
3809
 
3365
3810
    def test_get_default_bool_True(self):
3366
3811
        self.register_bool_option('foo', u'True')
3367
 
        self.assertEquals(True, self.conf.get('foo'))
 
3812
        conf = self.get_conf('')
 
3813
        self.assertEquals(True, conf.get('foo'))
3368
3814
 
3369
3815
    def test_get_default_bool_False(self):
3370
3816
        self.register_bool_option('foo', False)
3371
 
        self.assertEquals(False, self.conf.get('foo'))
 
3817
        conf = self.get_conf('')
 
3818
        self.assertEquals(False, conf.get('foo'))
3372
3819
 
3373
3820
    def test_get_default_bool_False_as_string(self):
3374
3821
        self.register_bool_option('foo', u'False')
3375
 
        self.assertEquals(False, self.conf.get('foo'))
 
3822
        conf = self.get_conf('')
 
3823
        self.assertEquals(False, conf.get('foo'))
3376
3824
 
3377
3825
    def test_get_default_bool_from_env_converted(self):
3378
3826
        self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3379
3827
        self.overrideEnv('FOO', 'False')
3380
 
        self.assertEquals(False, self.conf.get('foo'))
 
3828
        conf = self.get_conf('')
 
3829
        self.assertEquals(False, conf.get('foo'))
3381
3830
 
3382
3831
    def test_get_default_bool_when_conversion_fails(self):
3383
3832
        self.register_bool_option('foo', default='True')
3384
 
        self.conf.store._load_from_string('foo=invalid boolean')
3385
 
        self.assertEquals(True, self.conf.get('foo'))
 
3833
        conf = self.get_conf('foo=invalid boolean')
 
3834
        self.assertEquals(True, conf.get('foo'))
3386
3835
 
3387
3836
    def register_integer_option(self, name,
3388
3837
                                default=None, default_from_env=None):
3393
3842
 
3394
3843
    def test_get_default_integer_None(self):
3395
3844
        self.register_integer_option('foo')
3396
 
        self.assertEquals(None, self.conf.get('foo'))
 
3845
        conf = self.get_conf('')
 
3846
        self.assertEquals(None, conf.get('foo'))
3397
3847
 
3398
3848
    def test_get_default_integer(self):
3399
3849
        self.register_integer_option('foo', 42)
3400
 
        self.assertEquals(42, self.conf.get('foo'))
 
3850
        conf = self.get_conf('')
 
3851
        self.assertEquals(42, conf.get('foo'))
3401
3852
 
3402
3853
    def test_get_default_integer_as_string(self):
3403
3854
        self.register_integer_option('foo', u'42')
3404
 
        self.assertEquals(42, self.conf.get('foo'))
 
3855
        conf = self.get_conf('')
 
3856
        self.assertEquals(42, conf.get('foo'))
3405
3857
 
3406
3858
    def test_get_default_integer_from_env(self):
3407
3859
        self.register_integer_option('foo', default_from_env=['FOO'])
3408
3860
        self.overrideEnv('FOO', '18')
3409
 
        self.assertEquals(18, self.conf.get('foo'))
 
3861
        conf = self.get_conf('')
 
3862
        self.assertEquals(18, conf.get('foo'))
3410
3863
 
3411
3864
    def test_get_default_integer_when_conversion_fails(self):
3412
3865
        self.register_integer_option('foo', default='12')
3413
 
        self.conf.store._load_from_string('foo=invalid integer')
3414
 
        self.assertEquals(12, self.conf.get('foo'))
 
3866
        conf = self.get_conf('foo=invalid integer')
 
3867
        self.assertEquals(12, conf.get('foo'))
3415
3868
 
3416
3869
    def register_list_option(self, name, default=None, default_from_env=None):
3417
 
        l = config.Option(name, help='A list.',
3418
 
                          default=default, default_from_env=default_from_env,
3419
 
                          from_unicode=config.list_from_store)
 
3870
        l = config.ListOption(name, help='A list.', default=default,
 
3871
                              default_from_env=default_from_env)
3420
3872
        self.registry.register(l)
3421
3873
 
3422
3874
    def test_get_default_list_None(self):
3423
3875
        self.register_list_option('foo')
3424
 
        self.assertEquals(None, self.conf.get('foo'))
 
3876
        conf = self.get_conf('')
 
3877
        self.assertEquals(None, conf.get('foo'))
3425
3878
 
3426
3879
    def test_get_default_list_empty(self):
3427
3880
        self.register_list_option('foo', '')
3428
 
        self.assertEquals([], self.conf.get('foo'))
 
3881
        conf = self.get_conf('')
 
3882
        self.assertEquals([], conf.get('foo'))
3429
3883
 
3430
3884
    def test_get_default_list_from_env(self):
3431
3885
        self.register_list_option('foo', default_from_env=['FOO'])
3432
3886
        self.overrideEnv('FOO', '')
3433
 
        self.assertEquals([], self.conf.get('foo'))
 
3887
        conf = self.get_conf('')
 
3888
        self.assertEquals([], conf.get('foo'))
3434
3889
 
3435
3890
    def test_get_with_list_converter_no_item(self):
3436
3891
        self.register_list_option('foo', None)
3437
 
        self.conf.store._load_from_string('foo=,')
3438
 
        self.assertEquals([], self.conf.get('foo'))
 
3892
        conf = self.get_conf('foo=,')
 
3893
        self.assertEquals([], conf.get('foo'))
3439
3894
 
3440
3895
    def test_get_with_list_converter_many_items(self):
3441
3896
        self.register_list_option('foo', None)
3442
 
        self.conf.store._load_from_string('foo=m,o,r,e')
3443
 
        self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
 
3897
        conf = self.get_conf('foo=m,o,r,e')
 
3898
        self.assertEquals(['m', 'o', 'r', 'e'], conf.get('foo'))
3444
3899
 
3445
3900
    def test_get_with_list_converter_embedded_spaces_many_items(self):
3446
3901
        self.register_list_option('foo', None)
3447
 
        self.conf.store._load_from_string('foo=" bar", "baz "')
3448
 
        self.assertEquals([' bar', 'baz '], self.conf.get('foo'))
 
3902
        conf = self.get_conf('foo=" bar", "baz "')
 
3903
        self.assertEquals([' bar', 'baz '], conf.get('foo'))
3449
3904
 
3450
3905
    def test_get_with_list_converter_stripped_spaces_many_items(self):
3451
3906
        self.register_list_option('foo', None)
3452
 
        self.conf.store._load_from_string('foo= bar ,  baz ')
3453
 
        self.assertEquals(['bar', 'baz'], self.conf.get('foo'))
 
3907
        conf = self.get_conf('foo= bar ,  baz ')
 
3908
        self.assertEquals(['bar', 'baz'], conf.get('foo'))
 
3909
 
 
3910
 
 
3911
class TestIterOptionRefs(tests.TestCase):
 
3912
    """iter_option_refs is a bit unusual, document some cases."""
 
3913
 
 
3914
    def assertRefs(self, expected, string):
 
3915
        self.assertEquals(expected, list(config.iter_option_refs(string)))
 
3916
 
 
3917
    def test_empty(self):
 
3918
        self.assertRefs([(False, '')], '')
 
3919
 
 
3920
    def test_no_refs(self):
 
3921
        self.assertRefs([(False, 'foo bar')], 'foo bar')
 
3922
 
 
3923
    def test_single_ref(self):
 
3924
        self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
 
3925
 
 
3926
    def test_broken_ref(self):
 
3927
        self.assertRefs([(False, '{foo')], '{foo')
 
3928
 
 
3929
    def test_embedded_ref(self):
 
3930
        self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
 
3931
                        '{{foo}}')
 
3932
 
 
3933
    def test_two_refs(self):
 
3934
        self.assertRefs([(False, ''), (True, '{foo}'),
 
3935
                         (False, ''), (True, '{bar}'),
 
3936
                         (False, ''),],
 
3937
                        '{foo}{bar}')
 
3938
 
 
3939
    def test_newline_in_refs_are_not_matched(self):
 
3940
        self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
3454
3941
 
3455
3942
 
3456
3943
class TestStackExpandOptions(tests.TestCaseWithTransport):
3459
3946
        super(TestStackExpandOptions, self).setUp()
3460
3947
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3461
3948
        self.registry = config.option_registry
3462
 
        self.conf = build_branch_stack(self)
 
3949
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
3950
        self.conf = config.Stack([store.get_sections], store)
3463
3951
 
3464
3952
    def assertExpansion(self, expected, string, env=None):
3465
3953
        self.assertEquals(expected, self.conf.expand_options(string, env))
3500
3988
        self.assertRaises(errors.ExpandingUnknownOption,
3501
3989
                          self.conf.expand_options, '{foo}')
3502
3990
 
 
3991
    def test_illegal_def_is_ignored(self):
 
3992
        self.assertExpansion('{1,2}', '{1,2}')
 
3993
        self.assertExpansion('{ }', '{ }')
 
3994
        self.assertExpansion('${Foo,f}', '${Foo,f}')
 
3995
 
3503
3996
    def test_indirect_ref(self):
3504
3997
        self.conf.store._load_from_string('''
3505
3998
foo=xxx
3537
4030
list={foo},{bar},{baz}
3538
4031
''')
3539
4032
        self.registry.register(
3540
 
            config.Option('list', from_unicode=config.list_from_store))
 
4033
            config.ListOption('list'))
3541
4034
        self.assertEquals(['start', 'middle', 'end'],
3542
4035
                           self.conf.get('list', expand=True))
3543
4036
 
3548
4041
baz=end
3549
4042
list={foo}
3550
4043
''')
3551
 
        self.registry.register(
3552
 
            config.Option('list', from_unicode=config.list_from_store))
 
4044
        self.registry.register(config.ListOption('list'))
 
4045
        # Register an intermediate option as a list to ensure no conversion
 
4046
        # happen while expanding. Conversion should only occur for the original
 
4047
        # option ('list' here).
 
4048
        self.registry.register(config.ListOption('baz'))
3553
4049
        self.assertEquals(['start', 'middle', 'end'],
3554
4050
                           self.conf.get('list', expand=True))
3555
4051
 
3564
4060
''')
3565
4061
        # What matters is what the registration says, the conversion happens
3566
4062
        # only after all expansions have been performed
3567
 
        self.registry.register(
3568
 
            config.Option('hidden', from_unicode=config.list_from_store))
 
4063
        self.registry.register(config.ListOption('hidden'))
3569
4064
        self.assertEquals(['bin', 'go'],
3570
4065
                          self.conf.get('hidden', expand=True))
3571
4066
 
3607
4102
        self.assertEquals('quux', c.get('bar', expand=True))
3608
4103
 
3609
4104
 
 
4105
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
 
4106
 
 
4107
    def test_cross_global_locations(self):
 
4108
        l_store = config.LocationStore()
 
4109
        l_store._load_from_string('''
 
4110
[/branch]
 
4111
lfoo = loc-foo
 
4112
lbar = {gbar}
 
4113
''')
 
4114
        l_store.save()
 
4115
        g_store = config.GlobalStore()
 
4116
        g_store._load_from_string('''
 
4117
[DEFAULT]
 
4118
gfoo = {lfoo}
 
4119
gbar = glob-bar
 
4120
''')
 
4121
        g_store.save()
 
4122
        stack = config.LocationStack('/branch')
 
4123
        self.assertEquals('glob-bar', stack.get('lbar', expand=True))
 
4124
        self.assertEquals('loc-foo', stack.get('gfoo', expand=True))
 
4125
 
 
4126
 
 
4127
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
 
4128
 
 
4129
    def test_expand_locals_empty(self):
 
4130
        l_store = config.LocationStore()
 
4131
        l_store._load_from_string('''
 
4132
[/home/user/project]
 
4133
base = {basename}
 
4134
rel = {relpath}
 
4135
''')
 
4136
        l_store.save()
 
4137
        stack = config.LocationStack('/home/user/project/')
 
4138
        self.assertEquals('', stack.get('base', expand=True))
 
4139
        self.assertEquals('', stack.get('rel', expand=True))
 
4140
 
 
4141
    def test_expand_basename_locally(self):
 
4142
        l_store = config.LocationStore()
 
4143
        l_store._load_from_string('''
 
4144
[/home/user/project]
 
4145
bfoo = {basename}
 
4146
''')
 
4147
        l_store.save()
 
4148
        stack = config.LocationStack('/home/user/project/branch')
 
4149
        self.assertEquals('branch', stack.get('bfoo', expand=True))
 
4150
 
 
4151
    def test_expand_basename_locally_longer_path(self):
 
4152
        l_store = config.LocationStore()
 
4153
        l_store._load_from_string('''
 
4154
[/home/user]
 
4155
bfoo = {basename}
 
4156
''')
 
4157
        l_store.save()
 
4158
        stack = config.LocationStack('/home/user/project/dir/branch')
 
4159
        self.assertEquals('branch', stack.get('bfoo', expand=True))
 
4160
 
 
4161
    def test_expand_relpath_locally(self):
 
4162
        l_store = config.LocationStore()
 
4163
        l_store._load_from_string('''
 
4164
[/home/user/project]
 
4165
lfoo = loc-foo/{relpath}
 
4166
''')
 
4167
        l_store.save()
 
4168
        stack = config.LocationStack('/home/user/project/branch')
 
4169
        self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
 
4170
 
 
4171
    def test_expand_relpath_unknonw_in_global(self):
 
4172
        g_store = config.GlobalStore()
 
4173
        g_store._load_from_string('''
 
4174
[DEFAULT]
 
4175
gfoo = {relpath}
 
4176
''')
 
4177
        g_store.save()
 
4178
        stack = config.LocationStack('/home/user/project/branch')
 
4179
        self.assertRaises(errors.ExpandingUnknownOption,
 
4180
                          stack.get, 'gfoo', expand=True)
 
4181
 
 
4182
    def test_expand_local_option_locally(self):
 
4183
        l_store = config.LocationStore()
 
4184
        l_store._load_from_string('''
 
4185
[/home/user/project]
 
4186
lfoo = loc-foo/{relpath}
 
4187
lbar = {gbar}
 
4188
''')
 
4189
        l_store.save()
 
4190
        g_store = config.GlobalStore()
 
4191
        g_store._load_from_string('''
 
4192
[DEFAULT]
 
4193
gfoo = {lfoo}
 
4194
gbar = glob-bar
 
4195
''')
 
4196
        g_store.save()
 
4197
        stack = config.LocationStack('/home/user/project/branch')
 
4198
        self.assertEquals('glob-bar', stack.get('lbar', expand=True))
 
4199
        self.assertEquals('loc-foo/branch', stack.get('gfoo', expand=True))
 
4200
 
 
4201
    def test_locals_dont_leak(self):
 
4202
        """Make sure we chose the right local in presence of several sections.
 
4203
        """
 
4204
        l_store = config.LocationStore()
 
4205
        l_store._load_from_string('''
 
4206
[/home/user]
 
4207
lfoo = loc-foo/{relpath}
 
4208
[/home/user/project]
 
4209
lfoo = loc-foo/{relpath}
 
4210
''')
 
4211
        l_store.save()
 
4212
        stack = config.LocationStack('/home/user/project/branch')
 
4213
        self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
 
4214
        stack = config.LocationStack('/home/user/bar/baz')
 
4215
        self.assertEquals('loc-foo/bar/baz', stack.get('lfoo', expand=True))
 
4216
 
 
4217
 
 
4218
 
3610
4219
class TestStackSet(TestStackWithTransport):
3611
4220
 
3612
4221
    def test_simple_set(self):
3613
4222
        conf = self.get_stack(self)
3614
 
        conf.store._load_from_string('foo=bar')
3615
 
        self.assertEquals('bar', conf.get('foo'))
 
4223
        self.assertEquals(None, conf.get('foo'))
3616
4224
        conf.set('foo', 'baz')
3617
4225
        # Did we get it back ?
3618
4226
        self.assertEquals('baz', conf.get('foo'))
3762
4370
        """
3763
4371
        sections = list(conf._get_sections(name))
3764
4372
        self.assertLength(len(expected), sections)
3765
 
        self.assertEqual(expected, [name for name, _, _ in sections])
 
4373
        self.assertEqual(expected, [n for n, _, _ in sections])
3766
4374
 
3767
4375
    def test_bazaar_default_section(self):
3768
4376
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
3812
4420
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
3813
4421
 
3814
4422
 
 
4423
class TestSharedStores(tests.TestCaseInTempDir):
 
4424
 
 
4425
    def test_bazaar_conf_shared(self):
 
4426
        g1 = config.GlobalStack()
 
4427
        g2 = config.GlobalStack()
 
4428
        # The two stacks share the same store
 
4429
        self.assertIs(g1.store, g2.store)
 
4430
 
 
4431
 
3815
4432
class TestAuthenticationConfigFile(tests.TestCase):
3816
4433
    """Test the authentication.conf file matching"""
3817
4434
 
4032
4649
                                           port=99, path='/foo',
4033
4650
                                           realm='realm')
4034
4651
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4035
 
                       'verify_certificates': False, 'scheme': 'scheme', 
4036
 
                       'host': 'host', 'port': 99, 'path': '/foo', 
 
4652
                       'verify_certificates': False, 'scheme': 'scheme',
 
4653
                       'host': 'host', 'port': 99, 'path': '/foo',
4037
4654
                       'realm': 'realm'}
4038
4655
        self.assertEqual(CREDENTIALS, credentials)
4039
4656
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
4047
4664
        self.assertIs(None, conf._get_config().get('name'))
4048
4665
        credentials = conf.get_credentials(host='host', scheme='scheme')
4049
4666
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4050
 
                       'password', 'verify_certificates': True, 
4051
 
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
 
4667
                       'password', 'verify_certificates': True,
 
4668
                       'scheme': 'scheme', 'host': 'host', 'port': None,
4052
4669
                       'path': None, 'realm': None}
4053
4670
        self.assertEqual(CREDENTIALS, credentials)
4054
4671
 
4306
4923
        self.assertEquals('secret', decoded)
4307
4924
 
4308
4925
 
 
4926
class TestBase64CredentialStore(tests.TestCase):
 
4927
 
 
4928
    def test_decode_password(self):
 
4929
        r = config.credential_store_registry
 
4930
        plain_text = r.get_credential_store('base64')
 
4931
        decoded = plain_text.decode_password(dict(password='c2VjcmV0'))
 
4932
        self.assertEquals('secret', decoded)
 
4933
 
 
4934
 
4309
4935
# FIXME: Once we have a way to declare authentication to all test servers, we
4310
4936
# can implement generic tests.
4311
4937
# test_user_password_in_url
4323
4949
 
4324
4950
    def test_auto_user_id(self):
4325
4951
        """Automatic inference of user name.
4326
 
        
 
4952
 
4327
4953
        This is a bit hard to test in an isolated way, because it depends on
4328
4954
        system functions that go direct to /etc or perhaps somewhere else.
4329
4955
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
4339
4965
        else:
4340
4966
            self.assertEquals((None, None), (realname, address))
4341
4967
 
 
4968
 
 
4969
class TestDefaultMailDomain(tests.TestCaseInTempDir):
 
4970
    """Test retrieving default domain from mailname file"""
 
4971
 
 
4972
    def test_default_mail_domain_simple(self):
 
4973
        f = file('simple', 'w')
 
4974
        try:
 
4975
            f.write("domainname.com\n")
 
4976
        finally:
 
4977
            f.close()
 
4978
        r = config._get_default_mail_domain('simple')
 
4979
        self.assertEquals('domainname.com', r)
 
4980
 
 
4981
    def test_default_mail_domain_no_eol(self):
 
4982
        f = file('no_eol', 'w')
 
4983
        try:
 
4984
            f.write("domainname.com")
 
4985
        finally:
 
4986
            f.close()
 
4987
        r = config._get_default_mail_domain('no_eol')
 
4988
        self.assertEquals('domainname.com', r)
 
4989
 
 
4990
    def test_default_mail_domain_multiple_lines(self):
 
4991
        f = file('multiple_lines', 'w')
 
4992
        try:
 
4993
            f.write("domainname.com\nsome other text\n")
 
4994
        finally:
 
4995
            f.close()
 
4996
        r = config._get_default_mail_domain('multiple_lines')
 
4997
        self.assertEquals('domainname.com', r)
 
4998
 
 
4999
 
 
5000
class EmailOptionTests(tests.TestCase):
 
5001
 
 
5002
    def test_default_email_uses_BZR_EMAIL(self):
 
5003
        conf = config.MemoryStack('email=jelmer@debian.org')
 
5004
        # BZR_EMAIL takes precedence over EMAIL
 
5005
        self.overrideEnv('BZR_EMAIL', 'jelmer@samba.org')
 
5006
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
 
5007
        self.assertEquals('jelmer@samba.org', conf.get('email'))
 
5008
 
 
5009
    def test_default_email_uses_EMAIL(self):
 
5010
        conf = config.MemoryStack('')
 
5011
        self.overrideEnv('BZR_EMAIL', None)
 
5012
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
 
5013
        self.assertEquals('jelmer@apache.org', conf.get('email'))
 
5014
 
 
5015
    def test_BZR_EMAIL_overrides(self):
 
5016
        conf = config.MemoryStack('email=jelmer@debian.org')
 
5017
        self.overrideEnv('BZR_EMAIL', 'jelmer@apache.org')
 
5018
        self.assertEquals('jelmer@apache.org', conf.get('email'))
 
5019
        self.overrideEnv('BZR_EMAIL', None)
 
5020
        self.overrideEnv('EMAIL', 'jelmer@samba.org')
 
5021
        self.assertEquals('jelmer@debian.org', conf.get('email'))
 
5022
 
 
5023
 
 
5024
class MailClientOptionTests(tests.TestCase):
 
5025
 
 
5026
    def test_default(self):
 
5027
        conf = config.MemoryStack('')
 
5028
        client = conf.get('mail_client')
 
5029
        self.assertIs(client, mail_client.DefaultMail)
 
5030
 
 
5031
    def test_evolution(self):
 
5032
        conf = config.MemoryStack('mail_client=evolution')
 
5033
        client = conf.get('mail_client')
 
5034
        self.assertIs(client, mail_client.Evolution)
 
5035
 
 
5036
    def test_kmail(self):
 
5037
        conf = config.MemoryStack('mail_client=kmail')
 
5038
        client = conf.get('mail_client')
 
5039
        self.assertIs(client, mail_client.KMail)
 
5040
 
 
5041
    def test_mutt(self):
 
5042
        conf = config.MemoryStack('mail_client=mutt')
 
5043
        client = conf.get('mail_client')
 
5044
        self.assertIs(client, mail_client.Mutt)
 
5045
 
 
5046
    def test_thunderbird(self):
 
5047
        conf = config.MemoryStack('mail_client=thunderbird')
 
5048
        client = conf.get('mail_client')
 
5049
        self.assertIs(client, mail_client.Thunderbird)
 
5050
 
 
5051
    def test_explicit_default(self):
 
5052
        conf = config.MemoryStack('mail_client=default')
 
5053
        client = conf.get('mail_client')
 
5054
        self.assertIs(client, mail_client.DefaultMail)
 
5055
 
 
5056
    def test_editor(self):
 
5057
        conf = config.MemoryStack('mail_client=editor')
 
5058
        client = conf.get('mail_client')
 
5059
        self.assertIs(client, mail_client.Editor)
 
5060
 
 
5061
    def test_mapi(self):
 
5062
        conf = config.MemoryStack('mail_client=mapi')
 
5063
        client = conf.get('mail_client')
 
5064
        self.assertIs(client, mail_client.MAPIClient)
 
5065
 
 
5066
    def test_xdg_email(self):
 
5067
        conf = config.MemoryStack('mail_client=xdg-email')
 
5068
        client = conf.get('mail_client')
 
5069
        self.assertIs(client, mail_client.XDGEmail)
 
5070
 
 
5071
    def test_unknown(self):
 
5072
        conf = config.MemoryStack('mail_client=firebird')
 
5073
        self.assertRaises(errors.ConfigOptionValueError, conf.get,
 
5074
                'mail_client')