~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-04-05 14:47:26 UTC
  • mfrom: (5752.2.11 2.4-windows-lfstat)
  • Revision ID: pqm@pqm.ubuntu.com-20110405144726-zi3lj2kwvjml4kx5
(jameinel) Add osutils.lstat/fstat so that even on Windows lstat(fname) ==
 fstat(open(fname).fileno()) (John A Meinel)

Show diffs side-by-side

added added

removed removed

Lines of Context:
33
33
    errors,
34
34
    osutils,
35
35
    mail_client,
 
36
    mergetools,
36
37
    ui,
37
38
    urlutils,
38
 
    remote,
39
39
    tests,
40
40
    trace,
41
 
    )
42
 
from bzrlib.symbol_versioning import (
43
 
    deprecated_in,
44
 
    )
45
 
from bzrlib.transport import remote as transport_remote
 
41
    transport,
 
42
    )
46
43
from bzrlib.tests import (
47
44
    features,
 
45
    TestSkipped,
48
46
    scenarios,
49
 
    test_server,
50
47
    )
51
48
from bzrlib.util.configobj import configobj
52
49
 
65
62
 
66
63
load_tests = scenarios.load_tests_apply_scenarios
67
64
 
68
 
# Register helpers to build stores
69
 
config.test_store_builder_registry.register(
70
 
    'configobj', lambda test: config.IniFileStore(test.get_transport(),
71
 
                                                  'configobj.conf'))
72
 
config.test_store_builder_registry.register(
73
 
    'bazaar', lambda test: config.GlobalStore())
74
 
config.test_store_builder_registry.register(
75
 
    'location', lambda test: config.LocationStore())
76
 
 
77
 
 
78
 
def build_backing_branch(test, relpath,
79
 
                         transport_class=None, server_class=None):
80
 
    """Test helper to create a backing branch only once.
81
 
 
82
 
    Some tests needs multiple stores/stacks to check concurrent update
83
 
    behaviours. As such, they need to build different branch *objects* even if
84
 
    they share the branch on disk.
85
 
 
86
 
    :param relpath: The relative path to the branch. (Note that the helper
87
 
        should always specify the same relpath).
88
 
 
89
 
    :param transport_class: The Transport class the test needs to use.
90
 
 
91
 
    :param server_class: The server associated with the ``transport_class``
92
 
        above.
93
 
 
94
 
    Either both or neither of ``transport_class`` and ``server_class`` should
95
 
    be specified.
96
 
    """
97
 
    if transport_class is not None and server_class is not None:
98
 
        test.transport_class = transport_class
99
 
        test.transport_server = server_class
100
 
    elif not (transport_class is None and server_class is None):
101
 
        raise AssertionError('Specify both ``transport_class`` and '
102
 
                             '``server_class`` or neither of them')
103
 
    if getattr(test, 'backing_branch', None) is None:
104
 
        # First call, let's build the branch on disk
105
 
        test.backing_branch = test.make_branch(relpath)
106
 
 
107
 
 
108
 
def build_branch_store(test):
109
 
    build_backing_branch(test, 'branch')
110
 
    b = branch.Branch.open('branch')
111
 
    return config.BranchStore(b)
112
 
config.test_store_builder_registry.register('branch', build_branch_store)
113
 
 
114
 
 
115
 
def build_control_store(test):
116
 
    build_backing_branch(test, 'branch')
117
 
    b = bzrdir.BzrDir.open('branch')
118
 
    return config.ControlStore(b)
119
 
config.test_store_builder_registry.register('control', build_control_store)
120
 
 
121
 
 
122
 
def build_remote_branch_store(test):
123
 
    # There is only one permutation (but we won't be able to handle more with
124
 
    # this design anyway)
125
 
    (transport_class,
126
 
     server_class) = transport_remote.get_test_permutations()[0]
127
 
    build_backing_branch(test, 'branch', transport_class, server_class)
128
 
    b = branch.Branch.open(test.get_url('branch'))
129
 
    return config.BranchStore(b)
130
 
config.test_store_builder_registry.register('remote_branch',
131
 
                                            build_remote_branch_store)
132
 
 
133
 
 
134
 
config.test_stack_builder_registry.register(
135
 
    'bazaar', lambda test: config.GlobalStack())
136
 
config.test_stack_builder_registry.register(
137
 
    'location', lambda test: config.LocationStack('.'))
138
 
 
139
 
 
140
 
def build_branch_stack(test):
141
 
    build_backing_branch(test, 'branch')
142
 
    b = branch.Branch.open('branch')
143
 
    return config.BranchStack(b)
144
 
config.test_stack_builder_registry.register('branch', build_branch_stack)
145
 
 
146
 
 
147
 
def build_remote_branch_stack(test):
148
 
    # There is only one permutation (but we won't be able to handle more with
149
 
    # this design anyway)
150
 
    (transport_class,
151
 
     server_class) = transport_remote.get_test_permutations()[0]
152
 
    build_backing_branch(test, 'branch', transport_class, server_class)
153
 
    b = branch.Branch.open(test.get_url('branch'))
154
 
    return config.RemoteBranchStack(b)
155
 
config.test_stack_builder_registry.register('remote_branch',
156
 
                                            build_remote_branch_stack)
157
 
 
158
 
def build_remote_control_stack(test):
159
 
    # There is only one permutation (but we won't be able to handle more with
160
 
    # this design anyway)
161
 
    (transport_class,
162
 
     server_class) = transport_remote.get_test_permutations()[0]
163
 
    # We need only a bzrdir for this, not a full branch, but it's not worth
164
 
    # creating a dedicated helper to create only the bzrdir
165
 
    build_backing_branch(test, 'branch', transport_class, server_class)
166
 
    b = branch.Branch.open(test.get_url('branch'))
167
 
    return config.RemoteControlStack(b.bzrdir)
168
 
config.test_stack_builder_registry.register('remote_control',
169
 
                                            build_remote_control_stack)
170
 
 
171
65
 
172
66
sample_long_alias="log -r-15..-1 --line"
173
67
sample_config_text = u"""
176
70
editor=vim
177
71
change_editor=vimdiff -of @new_path @old_path
178
72
gpg_signing_command=gnome-gpg
179
 
gpg_signing_key=DD4D5088
180
73
log_format=short
181
 
validate_signatures_in_log=true
182
 
acceptable_keys=amy
183
74
user_global_option=something
184
75
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
185
76
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
186
 
bzr.mergetool.newtool='"newtool with spaces" {this_temp}'
187
77
bzr.default_mergetool=sometool
188
78
[ALIASES]
189
79
h=help
232
122
[/a/]
233
123
check_signatures=check-available
234
124
gpg_signing_command=false
235
 
gpg_signing_key=default
236
125
user_local_option=local
237
126
# test trailing / matching
238
127
[/a/*]
482
371
        config.Config()
483
372
 
484
373
    def test_no_default_editor(self):
485
 
        self.assertRaises(
486
 
            NotImplementedError,
487
 
            self.applyDeprecated, deprecated_in((2, 4, 0)),
488
 
            config.Config().get_editor)
 
374
        self.assertRaises(NotImplementedError, config.Config().get_editor)
489
375
 
490
376
    def test_user_email(self):
491
377
        my_config = InstrumentedConfig()
534
420
        my_config = config.Config()
535
421
        self.assertEqual('long', my_config.log_format())
536
422
 
537
 
    def test_acceptable_keys_default(self):
538
 
        my_config = config.Config()
539
 
        self.assertEqual(None, my_config.acceptable_keys())
540
 
 
541
 
    def test_validate_signatures_in_log_default(self):
542
 
        my_config = config.Config()
543
 
        self.assertEqual(False, my_config.validate_signatures_in_log())
544
 
 
545
423
    def test_get_change_editor(self):
546
424
        my_config = InstrumentedConfig()
547
425
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
632
510
    def test_cached(self):
633
511
        my_config = config.IniBasedConfig.from_string(sample_config_text)
634
512
        parser = my_config._get_parser()
635
 
        self.assertTrue(my_config._get_parser() is parser)
 
513
        self.failUnless(my_config._get_parser() is parser)
636
514
 
637
515
    def _dummy_chown(self, path, uid, gid):
638
516
        self.path, self.uid, self.gid = path, uid, gid
728
606
    def test_default_is_True(self):
729
607
        self.config = self.get_config(True)
730
608
        self.assertExpandIs(True)
731
 
 
 
609
        
732
610
    def test_default_is_False(self):
733
611
        self.config = self.get_config(False)
734
612
        self.assertExpandIs(False)
735
 
 
 
613
        
736
614
 
737
615
class TestIniConfigOptionExpansion(tests.TestCase):
738
616
    """Test option expansion from the IniConfig level.
836
714
        self.assertEquals(['{foo', '}', '{', 'bar}'],
837
715
                          conf.get_user_option('hidden', expand=True))
838
716
 
839
 
 
840
717
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
841
718
 
842
719
    def get_config(self, location, string=None):
955
832
        def c1_write_config_file():
956
833
            before_writing.set()
957
834
            c1_orig()
958
 
            # The lock is held. We wait for the main thread to decide when to
 
835
            # The lock is held we wait for the main thread to decide when to
959
836
            # continue
960
837
            after_writing.wait()
961
838
        c1._write_config_file = c1_write_config_file
988
865
       c1_orig = c1._write_config_file
989
866
       def c1_write_config_file():
990
867
           ready_to_write.set()
991
 
           # The lock is held. We wait for the main thread to decide when to
 
868
           # The lock is held we wait for the main thread to decide when to
992
869
           # continue
993
870
           do_writing.wait()
994
871
           c1_orig()
1053
930
        # automatically cast to list
1054
931
        self.assertEqual(['x'], get_list('one_item'))
1055
932
 
1056
 
    def test_get_user_option_as_int_from_SI(self):
1057
 
        conf, parser = self.make_config_parser("""
1058
 
plain = 100
1059
 
si_k = 5k,
1060
 
si_kb = 5kb,
1061
 
si_m = 5M,
1062
 
si_mb = 5MB,
1063
 
si_g = 5g,
1064
 
si_gb = 5gB,
1065
 
""")
1066
 
        get_si = conf.get_user_option_as_int_from_SI
1067
 
        self.assertEqual(100, get_si('plain'))
1068
 
        self.assertEqual(5000, get_si('si_k'))
1069
 
        self.assertEqual(5000, get_si('si_kb'))
1070
 
        self.assertEqual(5000000, get_si('si_m'))
1071
 
        self.assertEqual(5000000, get_si('si_mb'))
1072
 
        self.assertEqual(5000000000, get_si('si_g'))
1073
 
        self.assertEqual(5000000000, get_si('si_gb'))
1074
 
        self.assertEqual(None, get_si('non-exist'))
1075
 
        self.assertEqual(42, get_si('non-exist-with-default',  42))
1076
933
 
1077
934
class TestSupressWarning(TestIniConfig):
1078
935
 
1105
962
            parser = my_config._get_parser()
1106
963
        finally:
1107
964
            config.ConfigObj = oldparserclass
1108
 
        self.assertIsInstance(parser, InstrumentedConfigObj)
 
965
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1109
966
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
1110
967
                                          'utf-8')])
1111
968
 
1122
979
        my_config = config.BranchConfig(branch)
1123
980
        location_config = my_config._get_location_config()
1124
981
        self.assertEqual(branch.base, location_config.location)
1125
 
        self.assertIs(location_config, my_config._get_location_config())
 
982
        self.failUnless(location_config is my_config._get_location_config())
1126
983
 
1127
984
    def test_get_config(self):
1128
985
        """The Branch.get_config method works properly"""
1228
1085
 
1229
1086
    def test_configured_editor(self):
1230
1087
        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)
 
1088
        self.assertEqual("vim", my_config.get_editor())
1234
1089
 
1235
1090
    def test_signatures_always(self):
1236
1091
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
1265
1120
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
1266
1121
        self.assertEqual(False, my_config.signature_needed())
1267
1122
 
1268
 
    def test_gpg_signing_key(self):
1269
 
        my_config = self._get_sample_config()
1270
 
        self.assertEqual("DD4D5088", my_config.gpg_signing_key())
1271
 
 
1272
1123
    def _get_empty_config(self):
1273
1124
        my_config = config.GlobalConfig()
1274
1125
        return my_config
1294
1145
        my_config = self._get_sample_config()
1295
1146
        self.assertEqual("short", my_config.log_format())
1296
1147
 
1297
 
    def test_configured_acceptable_keys(self):
1298
 
        my_config = self._get_sample_config()
1299
 
        self.assertEqual("amy", my_config.acceptable_keys())
1300
 
 
1301
 
    def test_configured_validate_signatures_in_log(self):
1302
 
        my_config = self._get_sample_config()
1303
 
        self.assertEqual(True, my_config.validate_signatures_in_log())
1304
 
 
1305
1148
    def test_get_alias(self):
1306
1149
        my_config = self._get_sample_config()
1307
1150
        self.assertEqual('help', my_config.get_alias('h'))
1340
1183
        self.log(repr(tools))
1341
1184
        self.assertEqual(
1342
1185
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
1343
 
            u'sometool' : u'sometool {base} {this} {other} -o {result}',
1344
 
            u'newtool' : u'"newtool with spaces" {this_temp}'},
 
1186
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
1345
1187
            tools)
1346
1188
 
1347
1189
    def test_get_merge_tools_empty(self):
1411
1253
            parser = my_config._get_parser()
1412
1254
        finally:
1413
1255
            config.ConfigObj = oldparserclass
1414
 
        self.assertIsInstance(parser, InstrumentedConfigObj)
 
1256
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1415
1257
        self.assertEqual(parser._calls,
1416
1258
                         [('__init__', config.locations_config_filename(),
1417
1259
                           'utf-8')])
1419
1261
    def test_get_global_config(self):
1420
1262
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
1421
1263
        global_config = my_config._get_global_config()
1422
 
        self.assertIsInstance(global_config, config.GlobalConfig)
1423
 
        self.assertIs(global_config, my_config._get_global_config())
1424
 
 
1425
 
    def assertLocationMatching(self, expected):
1426
 
        self.assertEqual(expected,
1427
 
                         list(self.my_location_config._get_matching_sections()))
 
1264
        self.failUnless(isinstance(global_config, config.GlobalConfig))
 
1265
        self.failUnless(global_config is my_config._get_global_config())
1428
1266
 
1429
1267
    def test__get_matching_sections_no_match(self):
1430
1268
        self.get_branch_config('/')
1431
 
        self.assertLocationMatching([])
 
1269
        self.assertEqual([], self.my_location_config._get_matching_sections())
1432
1270
 
1433
1271
    def test__get_matching_sections_exact(self):
1434
1272
        self.get_branch_config('http://www.example.com')
1435
 
        self.assertLocationMatching([('http://www.example.com', '')])
 
1273
        self.assertEqual([('http://www.example.com', '')],
 
1274
                         self.my_location_config._get_matching_sections())
1436
1275
 
1437
1276
    def test__get_matching_sections_suffix_does_not(self):
1438
1277
        self.get_branch_config('http://www.example.com-com')
1439
 
        self.assertLocationMatching([])
 
1278
        self.assertEqual([], self.my_location_config._get_matching_sections())
1440
1279
 
1441
1280
    def test__get_matching_sections_subdir_recursive(self):
1442
1281
        self.get_branch_config('http://www.example.com/com')
1443
 
        self.assertLocationMatching([('http://www.example.com', 'com')])
 
1282
        self.assertEqual([('http://www.example.com', 'com')],
 
1283
                         self.my_location_config._get_matching_sections())
1444
1284
 
1445
1285
    def test__get_matching_sections_ignoreparent(self):
1446
1286
        self.get_branch_config('http://www.example.com/ignoreparent')
1447
 
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1448
 
                                      '')])
 
1287
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
 
1288
                         self.my_location_config._get_matching_sections())
1449
1289
 
1450
1290
    def test__get_matching_sections_ignoreparent_subdir(self):
1451
1291
        self.get_branch_config(
1452
1292
            'http://www.example.com/ignoreparent/childbranch')
1453
 
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1454
 
                                      'childbranch')])
 
1293
        self.assertEqual([('http://www.example.com/ignoreparent',
 
1294
                           'childbranch')],
 
1295
                         self.my_location_config._get_matching_sections())
1455
1296
 
1456
1297
    def test__get_matching_sections_subdir_trailing_slash(self):
1457
1298
        self.get_branch_config('/b')
1458
 
        self.assertLocationMatching([('/b/', '')])
 
1299
        self.assertEqual([('/b/', '')],
 
1300
                         self.my_location_config._get_matching_sections())
1459
1301
 
1460
1302
    def test__get_matching_sections_subdir_child(self):
1461
1303
        self.get_branch_config('/a/foo')
1462
 
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
 
1304
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
 
1305
                         self.my_location_config._get_matching_sections())
1463
1306
 
1464
1307
    def test__get_matching_sections_subdir_child_child(self):
1465
1308
        self.get_branch_config('/a/foo/bar')
1466
 
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
 
1309
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
 
1310
                         self.my_location_config._get_matching_sections())
1467
1311
 
1468
1312
    def test__get_matching_sections_trailing_slash_with_children(self):
1469
1313
        self.get_branch_config('/a/')
1470
 
        self.assertLocationMatching([('/a/', '')])
 
1314
        self.assertEqual([('/a/', '')],
 
1315
                         self.my_location_config._get_matching_sections())
1471
1316
 
1472
1317
    def test__get_matching_sections_explicit_over_glob(self):
1473
1318
        # XXX: 2006-09-08 jamesh
1475
1320
        # was a config section for '/a/?', it would get precedence
1476
1321
        # over '/a/c'.
1477
1322
        self.get_branch_config('/a/c')
1478
 
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
 
1323
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
 
1324
                         self.my_location_config._get_matching_sections())
1479
1325
 
1480
1326
    def test__get_option_policy_normal(self):
1481
1327
        self.get_branch_config('http://www.example.com')
1565
1411
        self.get_branch_config('/a')
1566
1412
        self.assertEqual("false", self.my_config.gpg_signing_command())
1567
1413
 
1568
 
    def test_gpg_signing_key(self):
1569
 
        self.get_branch_config('/b')
1570
 
        self.assertEqual("DD4D5088", self.my_config.gpg_signing_key())
1571
 
 
1572
 
    def test_gpg_signing_key_default(self):
1573
 
        self.get_branch_config('/a')
1574
 
        self.assertEqual("erik@bagfors.nu", self.my_config.gpg_signing_key())
1575
 
 
1576
1414
    def test_get_user_option_global(self):
1577
1415
        self.get_branch_config('/a')
1578
1416
        self.assertEqual('something',
1942
1780
 
1943
1781
class TestTransportConfig(tests.TestCaseWithTransport):
1944
1782
 
1945
 
    def test_load_utf8(self):
1946
 
        """Ensure we can load an utf8-encoded file."""
1947
 
        t = self.get_transport()
1948
 
        unicode_user = u'b\N{Euro Sign}ar'
1949
 
        unicode_content = u'user=%s' % (unicode_user,)
1950
 
        utf8_content = unicode_content.encode('utf8')
1951
 
        # Store the raw content in the config file
1952
 
        t.put_bytes('foo.conf', utf8_content)
1953
 
        conf = config.TransportConfig(t, 'foo.conf')
1954
 
        self.assertEquals(unicode_user, conf.get_option('user'))
1955
 
 
1956
 
    def test_load_non_ascii(self):
1957
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
1958
 
        t = self.get_transport()
1959
 
        t.put_bytes('foo.conf', 'user=foo\n#\xff\n')
1960
 
        conf = config.TransportConfig(t, 'foo.conf')
1961
 
        self.assertRaises(errors.ConfigContentError, conf._get_configobj)
1962
 
 
1963
 
    def test_load_erroneous_content(self):
1964
 
        """Ensure we display a proper error on content that can't be parsed."""
1965
 
        t = self.get_transport()
1966
 
        t.put_bytes('foo.conf', '[open_section\n')
1967
 
        conf = config.TransportConfig(t, 'foo.conf')
1968
 
        self.assertRaises(errors.ParseConfigError, conf._get_configobj)
1969
 
 
1970
 
    def test_load_permission_denied(self):
1971
 
        """Ensure we get an empty config file if the file is inaccessible."""
1972
 
        warnings = []
1973
 
        def warning(*args):
1974
 
            warnings.append(args[0] % args[1:])
1975
 
        self.overrideAttr(trace, 'warning', warning)
1976
 
 
1977
 
        class DenyingTransport(object):
1978
 
 
1979
 
            def __init__(self, base):
1980
 
                self.base = base
1981
 
 
1982
 
            def get_bytes(self, relpath):
1983
 
                raise errors.PermissionDenied(relpath, "")
1984
 
 
1985
 
        cfg = config.TransportConfig(
1986
 
            DenyingTransport("nonexisting://"), 'control.conf')
1987
 
        self.assertIs(None, cfg.get_option('non-existant', 'SECTION'))
1988
 
        self.assertEquals(
1989
 
            warnings,
1990
 
            [u'Permission denied while trying to open configuration file '
1991
 
             u'nonexisting:///control.conf.'])
1992
 
 
1993
1783
    def test_get_value(self):
1994
1784
        """Test that retreiving a value from a section is possible"""
1995
 
        bzrdir_config = config.TransportConfig(self.get_transport('.'),
 
1785
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1996
1786
                                               'control.conf')
1997
1787
        bzrdir_config.set_option('value', 'key', 'SECTION')
1998
1788
        bzrdir_config.set_option('value2', 'key2')
2028
1818
        self.assertIs(None, bzrdir_config.get_default_stack_on())
2029
1819
 
2030
1820
 
2031
 
class TestOldConfigHooks(tests.TestCaseWithTransport):
2032
 
 
2033
 
    def setUp(self):
2034
 
        super(TestOldConfigHooks, self).setUp()
2035
 
        create_configs_with_file_option(self)
2036
 
 
2037
 
    def assertGetHook(self, conf, name, value):
2038
 
        calls = []
2039
 
        def hook(*args):
2040
 
            calls.append(args)
2041
 
        config.OldConfigHooks.install_named_hook('get', hook, None)
2042
 
        self.addCleanup(
2043
 
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
2044
 
        self.assertLength(0, calls)
2045
 
        actual_value = conf.get_user_option(name)
2046
 
        self.assertEquals(value, actual_value)
2047
 
        self.assertLength(1, calls)
2048
 
        self.assertEquals((conf, name, value), calls[0])
2049
 
 
2050
 
    def test_get_hook_bazaar(self):
2051
 
        self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
2052
 
 
2053
 
    def test_get_hook_locations(self):
2054
 
        self.assertGetHook(self.locations_config, 'file', 'locations')
2055
 
 
2056
 
    def test_get_hook_branch(self):
2057
 
        # Since locations masks branch, we define a different option
2058
 
        self.branch_config.set_user_option('file2', 'branch')
2059
 
        self.assertGetHook(self.branch_config, 'file2', 'branch')
2060
 
 
2061
 
    def assertSetHook(self, conf, name, value):
2062
 
        calls = []
2063
 
        def hook(*args):
2064
 
            calls.append(args)
2065
 
        config.OldConfigHooks.install_named_hook('set', hook, None)
2066
 
        self.addCleanup(
2067
 
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
2068
 
        self.assertLength(0, calls)
2069
 
        conf.set_user_option(name, value)
2070
 
        self.assertLength(1, calls)
2071
 
        # We can't assert the conf object below as different configs use
2072
 
        # different means to implement set_user_option and we care only about
2073
 
        # coverage here.
2074
 
        self.assertEquals((name, value), calls[0][1:])
2075
 
 
2076
 
    def test_set_hook_bazaar(self):
2077
 
        self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
2078
 
 
2079
 
    def test_set_hook_locations(self):
2080
 
        self.assertSetHook(self.locations_config, 'foo', 'locations')
2081
 
 
2082
 
    def test_set_hook_branch(self):
2083
 
        self.assertSetHook(self.branch_config, 'foo', 'branch')
2084
 
 
2085
 
    def assertRemoveHook(self, conf, name, section_name=None):
2086
 
        calls = []
2087
 
        def hook(*args):
2088
 
            calls.append(args)
2089
 
        config.OldConfigHooks.install_named_hook('remove', hook, None)
2090
 
        self.addCleanup(
2091
 
            config.OldConfigHooks.uninstall_named_hook, 'remove', None)
2092
 
        self.assertLength(0, calls)
2093
 
        conf.remove_user_option(name, section_name)
2094
 
        self.assertLength(1, calls)
2095
 
        # We can't assert the conf object below as different configs use
2096
 
        # different means to implement remove_user_option and we care only about
2097
 
        # coverage here.
2098
 
        self.assertEquals((name,), calls[0][1:])
2099
 
 
2100
 
    def test_remove_hook_bazaar(self):
2101
 
        self.assertRemoveHook(self.bazaar_config, 'file')
2102
 
 
2103
 
    def test_remove_hook_locations(self):
2104
 
        self.assertRemoveHook(self.locations_config, 'file',
2105
 
                              self.locations_config.location)
2106
 
 
2107
 
    def test_remove_hook_branch(self):
2108
 
        self.assertRemoveHook(self.branch_config, 'file')
2109
 
 
2110
 
    def assertLoadHook(self, name, conf_class, *conf_args):
2111
 
        calls = []
2112
 
        def hook(*args):
2113
 
            calls.append(args)
2114
 
        config.OldConfigHooks.install_named_hook('load', hook, None)
2115
 
        self.addCleanup(
2116
 
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
2117
 
        self.assertLength(0, calls)
2118
 
        # Build a config
2119
 
        conf = conf_class(*conf_args)
2120
 
        # Access an option to trigger a load
2121
 
        conf.get_user_option(name)
2122
 
        self.assertLength(1, calls)
2123
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2124
 
 
2125
 
    def test_load_hook_bazaar(self):
2126
 
        self.assertLoadHook('file', config.GlobalConfig)
2127
 
 
2128
 
    def test_load_hook_locations(self):
2129
 
        self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
2130
 
 
2131
 
    def test_load_hook_branch(self):
2132
 
        self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
2133
 
 
2134
 
    def assertSaveHook(self, conf):
2135
 
        calls = []
2136
 
        def hook(*args):
2137
 
            calls.append(args)
2138
 
        config.OldConfigHooks.install_named_hook('save', hook, None)
2139
 
        self.addCleanup(
2140
 
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
2141
 
        self.assertLength(0, calls)
2142
 
        # Setting an option triggers a save
2143
 
        conf.set_user_option('foo', 'bar')
2144
 
        self.assertLength(1, calls)
2145
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2146
 
 
2147
 
    def test_save_hook_bazaar(self):
2148
 
        self.assertSaveHook(self.bazaar_config)
2149
 
 
2150
 
    def test_save_hook_locations(self):
2151
 
        self.assertSaveHook(self.locations_config)
2152
 
 
2153
 
    def test_save_hook_branch(self):
2154
 
        self.assertSaveHook(self.branch_config)
2155
 
 
2156
 
 
2157
 
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
2158
 
    """Tests config hooks for remote configs.
2159
 
 
2160
 
    No tests for the remove hook as this is not implemented there.
2161
 
    """
2162
 
 
2163
 
    def setUp(self):
2164
 
        super(TestOldConfigHooksForRemote, self).setUp()
2165
 
        self.transport_server = test_server.SmartTCPServer_for_testing
2166
 
        create_configs_with_file_option(self)
2167
 
 
2168
 
    def assertGetHook(self, conf, name, value):
2169
 
        calls = []
2170
 
        def hook(*args):
2171
 
            calls.append(args)
2172
 
        config.OldConfigHooks.install_named_hook('get', hook, None)
2173
 
        self.addCleanup(
2174
 
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
2175
 
        self.assertLength(0, calls)
2176
 
        actual_value = conf.get_option(name)
2177
 
        self.assertEquals(value, actual_value)
2178
 
        self.assertLength(1, calls)
2179
 
        self.assertEquals((conf, name, value), calls[0])
2180
 
 
2181
 
    def test_get_hook_remote_branch(self):
2182
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2183
 
        self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2184
 
 
2185
 
    def test_get_hook_remote_bzrdir(self):
2186
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2187
 
        conf = remote_bzrdir._get_config()
2188
 
        conf.set_option('remotedir', 'file')
2189
 
        self.assertGetHook(conf, 'file', 'remotedir')
2190
 
 
2191
 
    def assertSetHook(self, conf, name, value):
2192
 
        calls = []
2193
 
        def hook(*args):
2194
 
            calls.append(args)
2195
 
        config.OldConfigHooks.install_named_hook('set', hook, None)
2196
 
        self.addCleanup(
2197
 
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
2198
 
        self.assertLength(0, calls)
2199
 
        conf.set_option(value, name)
2200
 
        self.assertLength(1, calls)
2201
 
        # We can't assert the conf object below as different configs use
2202
 
        # different means to implement set_user_option and we care only about
2203
 
        # coverage here.
2204
 
        self.assertEquals((name, value), calls[0][1:])
2205
 
 
2206
 
    def test_set_hook_remote_branch(self):
2207
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2208
 
        self.addCleanup(remote_branch.lock_write().unlock)
2209
 
        self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
2210
 
 
2211
 
    def test_set_hook_remote_bzrdir(self):
2212
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2213
 
        self.addCleanup(remote_branch.lock_write().unlock)
2214
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2215
 
        self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2216
 
 
2217
 
    def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2218
 
        calls = []
2219
 
        def hook(*args):
2220
 
            calls.append(args)
2221
 
        config.OldConfigHooks.install_named_hook('load', hook, None)
2222
 
        self.addCleanup(
2223
 
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
2224
 
        self.assertLength(0, calls)
2225
 
        # Build a config
2226
 
        conf = conf_class(*conf_args)
2227
 
        # Access an option to trigger a load
2228
 
        conf.get_option(name)
2229
 
        self.assertLength(expected_nb_calls, calls)
2230
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2231
 
 
2232
 
    def test_load_hook_remote_branch(self):
2233
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2234
 
        self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2235
 
 
2236
 
    def test_load_hook_remote_bzrdir(self):
2237
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2238
 
        # The config file doesn't exist, set an option to force its creation
2239
 
        conf = remote_bzrdir._get_config()
2240
 
        conf.set_option('remotedir', 'file')
2241
 
        # We get one call for the server and one call for the client, this is
2242
 
        # caused by the differences in implementations betwen
2243
 
        # SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
2244
 
        # SmartServerBranchGetConfigFile (in smart/branch.py)
2245
 
        self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
2246
 
 
2247
 
    def assertSaveHook(self, conf):
2248
 
        calls = []
2249
 
        def hook(*args):
2250
 
            calls.append(args)
2251
 
        config.OldConfigHooks.install_named_hook('save', hook, None)
2252
 
        self.addCleanup(
2253
 
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
2254
 
        self.assertLength(0, calls)
2255
 
        # Setting an option triggers a save
2256
 
        conf.set_option('foo', 'bar')
2257
 
        self.assertLength(1, calls)
2258
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2259
 
 
2260
 
    def test_save_hook_remote_branch(self):
2261
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2262
 
        self.addCleanup(remote_branch.lock_write().unlock)
2263
 
        self.assertSaveHook(remote_branch._get_config())
2264
 
 
2265
 
    def test_save_hook_remote_bzrdir(self):
2266
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2267
 
        self.addCleanup(remote_branch.lock_write().unlock)
2268
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2269
 
        self.assertSaveHook(remote_bzrdir._get_config())
2270
 
 
2271
 
 
2272
 
class TestOption(tests.TestCase):
2273
 
 
2274
 
    def test_default_value(self):
2275
 
        opt = config.Option('foo', default='bar')
2276
 
        self.assertEquals('bar', opt.get_default())
2277
 
 
2278
 
    def test_default_value_from_env(self):
2279
 
        opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2280
 
        self.overrideEnv('FOO', 'quux')
2281
 
        # Env variable provides a default taking over the option one
2282
 
        self.assertEquals('quux', opt.get_default())
2283
 
 
2284
 
    def test_first_default_value_from_env_wins(self):
2285
 
        opt = config.Option('foo', default='bar',
2286
 
                            default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2287
 
        self.overrideEnv('FOO', 'foo')
2288
 
        self.overrideEnv('BAZ', 'baz')
2289
 
        # The first env var set wins
2290
 
        self.assertEquals('foo', opt.get_default())
2291
 
 
2292
 
    def test_not_supported_list_default_value(self):
2293
 
        self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2294
 
 
2295
 
    def test_not_supported_object_default_value(self):
2296
 
        self.assertRaises(AssertionError, config.Option, 'foo',
2297
 
                          default=object())
2298
 
 
2299
 
 
2300
 
class TestOptionConverterMixin(object):
2301
 
 
2302
 
    def assertConverted(self, expected, opt, value):
2303
 
        self.assertEquals(expected, opt.convert_from_unicode(value))
2304
 
 
2305
 
    def assertWarns(self, opt, value):
2306
 
        warnings = []
2307
 
        def warning(*args):
2308
 
            warnings.append(args[0] % args[1:])
2309
 
        self.overrideAttr(trace, 'warning', warning)
2310
 
        self.assertEquals(None, opt.convert_from_unicode(value))
2311
 
        self.assertLength(1, warnings)
2312
 
        self.assertEquals(
2313
 
            'Value "%s" is not valid for "%s"' % (value, opt.name),
2314
 
            warnings[0])
2315
 
 
2316
 
    def assertErrors(self, opt, value):
2317
 
        self.assertRaises(errors.ConfigOptionValueError,
2318
 
                          opt.convert_from_unicode, value)
2319
 
 
2320
 
    def assertConvertInvalid(self, opt, invalid_value):
2321
 
        opt.invalid = None
2322
 
        self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2323
 
        opt.invalid = 'warning'
2324
 
        self.assertWarns(opt, invalid_value)
2325
 
        opt.invalid = 'error'
2326
 
        self.assertErrors(opt, invalid_value)
2327
 
 
2328
 
 
2329
 
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2330
 
 
2331
 
    def get_option(self):
2332
 
        return config.Option('foo', help='A boolean.',
2333
 
                             from_unicode=config.bool_from_store)
2334
 
 
2335
 
    def test_convert_invalid(self):
2336
 
        opt = self.get_option()
2337
 
        # A string that is not recognized as a boolean
2338
 
        self.assertConvertInvalid(opt, u'invalid-boolean')
2339
 
        # A list of strings is never recognized as a boolean
2340
 
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2341
 
 
2342
 
    def test_convert_valid(self):
2343
 
        opt = self.get_option()
2344
 
        self.assertConverted(True, opt, u'True')
2345
 
        self.assertConverted(True, opt, u'1')
2346
 
        self.assertConverted(False, opt, u'False')
2347
 
 
2348
 
 
2349
 
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2350
 
 
2351
 
    def get_option(self):
2352
 
        return config.Option('foo', help='An integer.',
2353
 
                             from_unicode=config.int_from_store)
2354
 
 
2355
 
    def test_convert_invalid(self):
2356
 
        opt = self.get_option()
2357
 
        # A string that is not recognized as an integer
2358
 
        self.assertConvertInvalid(opt, u'forty-two')
2359
 
        # A list of strings is never recognized as an integer
2360
 
        self.assertConvertInvalid(opt, [u'a', u'list'])
2361
 
 
2362
 
    def test_convert_valid(self):
2363
 
        opt = self.get_option()
2364
 
        self.assertConverted(16, opt, u'16')
2365
 
 
2366
 
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2367
 
 
2368
 
    def get_option(self):
2369
 
        return config.Option('foo', help='A list.',
2370
 
                             from_unicode=config.list_from_store)
2371
 
 
2372
 
    def test_convert_invalid(self):
2373
 
        # No string is invalid as all forms can be converted to a list
2374
 
        pass
2375
 
 
2376
 
    def test_convert_valid(self):
2377
 
        opt = self.get_option()
2378
 
        # An empty string is an empty list
2379
 
        self.assertConverted([], opt, '') # Using a bare str() just in case
2380
 
        self.assertConverted([], opt, u'')
2381
 
        # A boolean
2382
 
        self.assertConverted([u'True'], opt, u'True')
2383
 
        # An integer
2384
 
        self.assertConverted([u'42'], opt, u'42')
2385
 
        # A single string
2386
 
        self.assertConverted([u'bar'], opt, u'bar')
2387
 
        # A list remains a list (configObj will turn a string containing commas
2388
 
        # into a list, but that's not what we're testing here)
2389
 
        self.assertConverted([u'foo', u'1', u'True'],
2390
 
                             opt, [u'foo', u'1', u'True'])
2391
 
 
2392
 
 
2393
 
class TestOptionConverterMixin(object):
2394
 
 
2395
 
    def assertConverted(self, expected, opt, value):
2396
 
        self.assertEquals(expected, opt.convert_from_unicode(value))
2397
 
 
2398
 
    def assertWarns(self, opt, value):
2399
 
        warnings = []
2400
 
        def warning(*args):
2401
 
            warnings.append(args[0] % args[1:])
2402
 
        self.overrideAttr(trace, 'warning', warning)
2403
 
        self.assertEquals(None, opt.convert_from_unicode(value))
2404
 
        self.assertLength(1, warnings)
2405
 
        self.assertEquals(
2406
 
            'Value "%s" is not valid for "%s"' % (value, opt.name),
2407
 
            warnings[0])
2408
 
 
2409
 
    def assertErrors(self, opt, value):
2410
 
        self.assertRaises(errors.ConfigOptionValueError,
2411
 
                          opt.convert_from_unicode, value)
2412
 
 
2413
 
    def assertConvertInvalid(self, opt, invalid_value):
2414
 
        opt.invalid = None
2415
 
        self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2416
 
        opt.invalid = 'warning'
2417
 
        self.assertWarns(opt, invalid_value)
2418
 
        opt.invalid = 'error'
2419
 
        self.assertErrors(opt, invalid_value)
2420
 
 
2421
 
 
2422
 
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2423
 
 
2424
 
    def get_option(self):
2425
 
        return config.Option('foo', help='A boolean.',
2426
 
                             from_unicode=config.bool_from_store)
2427
 
 
2428
 
    def test_convert_invalid(self):
2429
 
        opt = self.get_option()
2430
 
        # A string that is not recognized as a boolean
2431
 
        self.assertConvertInvalid(opt, u'invalid-boolean')
2432
 
        # A list of strings is never recognized as a boolean
2433
 
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2434
 
 
2435
 
    def test_convert_valid(self):
2436
 
        opt = self.get_option()
2437
 
        self.assertConverted(True, opt, u'True')
2438
 
        self.assertConverted(True, opt, u'1')
2439
 
        self.assertConverted(False, opt, u'False')
2440
 
 
2441
 
 
2442
 
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2443
 
 
2444
 
    def get_option(self):
2445
 
        return config.Option('foo', help='An integer.',
2446
 
                             from_unicode=config.int_from_store)
2447
 
 
2448
 
    def test_convert_invalid(self):
2449
 
        opt = self.get_option()
2450
 
        # A string that is not recognized as an integer
2451
 
        self.assertConvertInvalid(opt, u'forty-two')
2452
 
        # A list of strings is never recognized as an integer
2453
 
        self.assertConvertInvalid(opt, [u'a', u'list'])
2454
 
 
2455
 
    def test_convert_valid(self):
2456
 
        opt = self.get_option()
2457
 
        self.assertConverted(16, opt, u'16')
2458
 
 
2459
 
 
2460
 
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2461
 
 
2462
 
    def get_option(self):
2463
 
        return config.Option('foo', help='A list.',
2464
 
                             from_unicode=config.list_from_store)
2465
 
 
2466
 
    def test_convert_invalid(self):
2467
 
        opt = self.get_option()
2468
 
        # We don't even try to convert a list into a list, we only expect
2469
 
        # strings
2470
 
        self.assertConvertInvalid(opt, [1])
2471
 
        # No string is invalid as all forms can be converted to a list
2472
 
 
2473
 
    def test_convert_valid(self):
2474
 
        opt = self.get_option()
2475
 
        # An empty string is an empty list
2476
 
        self.assertConverted([], opt, '') # Using a bare str() just in case
2477
 
        self.assertConverted([], opt, u'')
2478
 
        # A boolean
2479
 
        self.assertConverted([u'True'], opt, u'True')
2480
 
        # An integer
2481
 
        self.assertConverted([u'42'], opt, u'42')
2482
 
        # A single string
2483
 
        self.assertConverted([u'bar'], opt, u'bar')
2484
 
 
2485
 
 
2486
 
class TestOptionRegistry(tests.TestCase):
2487
 
 
2488
 
    def setUp(self):
2489
 
        super(TestOptionRegistry, self).setUp()
2490
 
        # Always start with an empty registry
2491
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2492
 
        self.registry = config.option_registry
2493
 
 
2494
 
    def test_register(self):
2495
 
        opt = config.Option('foo')
2496
 
        self.registry.register(opt)
2497
 
        self.assertIs(opt, self.registry.get('foo'))
2498
 
 
2499
 
    def test_registered_help(self):
2500
 
        opt = config.Option('foo', help='A simple option')
2501
 
        self.registry.register(opt)
2502
 
        self.assertEquals('A simple option', self.registry.get_help('foo'))
2503
 
 
2504
 
    lazy_option = config.Option('lazy_foo', help='Lazy help')
2505
 
 
2506
 
    def test_register_lazy(self):
2507
 
        self.registry.register_lazy('lazy_foo', self.__module__,
2508
 
                                    'TestOptionRegistry.lazy_option')
2509
 
        self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2510
 
 
2511
 
    def test_registered_lazy_help(self):
2512
 
        self.registry.register_lazy('lazy_foo', self.__module__,
2513
 
                                    'TestOptionRegistry.lazy_option')
2514
 
        self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2515
 
 
2516
 
 
2517
 
class TestRegisteredOptions(tests.TestCase):
2518
 
    """All registered options should verify some constraints."""
2519
 
 
2520
 
    scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2521
 
                 in config.option_registry.iteritems()]
2522
 
 
2523
 
    def setUp(self):
2524
 
        super(TestRegisteredOptions, self).setUp()
2525
 
        self.registry = config.option_registry
2526
 
 
2527
 
    def test_proper_name(self):
2528
 
        # An option should be registered under its own name, this can't be
2529
 
        # checked at registration time for the lazy ones.
2530
 
        self.assertEquals(self.option_name, self.option.name)
2531
 
 
2532
 
    def test_help_is_set(self):
2533
 
        option_help = self.registry.get_help(self.option_name)
2534
 
        self.assertNotEquals(None, option_help)
2535
 
        # Come on, think about the user, he really wants to know what the
2536
 
        # option is about
2537
 
        self.assertIsNot(None, option_help)
2538
 
        self.assertNotEquals('', option_help)
2539
 
 
2540
 
 
2541
 
class TestSection(tests.TestCase):
2542
 
 
2543
 
    # FIXME: Parametrize so that all sections produced by Stores run these
2544
 
    # tests -- vila 2011-04-01
2545
 
 
2546
 
    def test_get_a_value(self):
2547
 
        a_dict = dict(foo='bar')
2548
 
        section = config.Section('myID', a_dict)
2549
 
        self.assertEquals('bar', section.get('foo'))
2550
 
 
2551
 
    def test_get_unknown_option(self):
2552
 
        a_dict = dict()
2553
 
        section = config.Section(None, a_dict)
2554
 
        self.assertEquals('out of thin air',
2555
 
                          section.get('foo', 'out of thin air'))
2556
 
 
2557
 
    def test_options_is_shared(self):
2558
 
        a_dict = dict()
2559
 
        section = config.Section(None, a_dict)
2560
 
        self.assertIs(a_dict, section.options)
2561
 
 
2562
 
 
2563
 
class TestMutableSection(tests.TestCase):
2564
 
 
2565
 
    # FIXME: Parametrize so that all sections (including os.environ and the
2566
 
    # ones produced by Stores) run these tests -- vila 2011-04-01
2567
 
 
2568
 
    def test_set(self):
2569
 
        a_dict = dict(foo='bar')
2570
 
        section = config.MutableSection('myID', a_dict)
2571
 
        section.set('foo', 'new_value')
2572
 
        self.assertEquals('new_value', section.get('foo'))
2573
 
        # The change appears in the shared section
2574
 
        self.assertEquals('new_value', a_dict.get('foo'))
2575
 
        # We keep track of the change
2576
 
        self.assertTrue('foo' in section.orig)
2577
 
        self.assertEquals('bar', section.orig.get('foo'))
2578
 
 
2579
 
    def test_set_preserve_original_once(self):
2580
 
        a_dict = dict(foo='bar')
2581
 
        section = config.MutableSection('myID', a_dict)
2582
 
        section.set('foo', 'first_value')
2583
 
        section.set('foo', 'second_value')
2584
 
        # We keep track of the original value
2585
 
        self.assertTrue('foo' in section.orig)
2586
 
        self.assertEquals('bar', section.orig.get('foo'))
2587
 
 
2588
 
    def test_remove(self):
2589
 
        a_dict = dict(foo='bar')
2590
 
        section = config.MutableSection('myID', a_dict)
2591
 
        section.remove('foo')
2592
 
        # We get None for unknown options via the default value
2593
 
        self.assertEquals(None, section.get('foo'))
2594
 
        # Or we just get the default value
2595
 
        self.assertEquals('unknown', section.get('foo', 'unknown'))
2596
 
        self.assertFalse('foo' in section.options)
2597
 
        # We keep track of the deletion
2598
 
        self.assertTrue('foo' in section.orig)
2599
 
        self.assertEquals('bar', section.orig.get('foo'))
2600
 
 
2601
 
    def test_remove_new_option(self):
2602
 
        a_dict = dict()
2603
 
        section = config.MutableSection('myID', a_dict)
2604
 
        section.set('foo', 'bar')
2605
 
        section.remove('foo')
2606
 
        self.assertFalse('foo' in section.options)
2607
 
        # The option didn't exist initially so it we need to keep track of it
2608
 
        # with a special value
2609
 
        self.assertTrue('foo' in section.orig)
2610
 
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2611
 
 
2612
 
 
2613
 
class TestStore(tests.TestCaseWithTransport):
2614
 
 
2615
 
    def assertSectionContent(self, expected, section):
2616
 
        """Assert that some options have the proper values in a section."""
2617
 
        expected_name, expected_options = expected
2618
 
        self.assertEquals(expected_name, section.id)
2619
 
        self.assertEquals(
2620
 
            expected_options,
2621
 
            dict([(k, section.get(k)) for k in expected_options.keys()]))
2622
 
 
2623
 
 
2624
 
class TestReadonlyStore(TestStore):
2625
 
 
2626
 
    scenarios = [(key, {'get_store': builder}) for key, builder
2627
 
                 in config.test_store_builder_registry.iteritems()]
2628
 
 
2629
 
    def test_building_delays_load(self):
2630
 
        store = self.get_store(self)
2631
 
        self.assertEquals(False, store.is_loaded())
2632
 
        store._load_from_string('')
2633
 
        self.assertEquals(True, store.is_loaded())
2634
 
 
2635
 
    def test_get_no_sections_for_empty(self):
2636
 
        store = self.get_store(self)
2637
 
        store._load_from_string('')
2638
 
        self.assertEquals([], list(store.get_sections()))
2639
 
 
2640
 
    def test_get_default_section(self):
2641
 
        store = self.get_store(self)
2642
 
        store._load_from_string('foo=bar')
2643
 
        sections = list(store.get_sections())
2644
 
        self.assertLength(1, sections)
2645
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2646
 
 
2647
 
    def test_get_named_section(self):
2648
 
        store = self.get_store(self)
2649
 
        store._load_from_string('[baz]\nfoo=bar')
2650
 
        sections = list(store.get_sections())
2651
 
        self.assertLength(1, sections)
2652
 
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2653
 
 
2654
 
    def test_load_from_string_fails_for_non_empty_store(self):
2655
 
        store = self.get_store(self)
2656
 
        store._load_from_string('foo=bar')
2657
 
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2658
 
 
2659
 
 
2660
 
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2661
 
    """Simulate loading a config store with content of various encodings.
2662
 
 
2663
 
    All files produced by bzr are in utf8 content.
2664
 
 
2665
 
    Users may modify them manually and end up with a file that can't be
2666
 
    loaded. We need to issue proper error messages in this case.
2667
 
    """
2668
 
 
2669
 
    invalid_utf8_char = '\xff'
2670
 
 
2671
 
    def test_load_utf8(self):
2672
 
        """Ensure we can load an utf8-encoded file."""
2673
 
        t = self.get_transport()
2674
 
        # From http://pad.lv/799212
2675
 
        unicode_user = u'b\N{Euro Sign}ar'
2676
 
        unicode_content = u'user=%s' % (unicode_user,)
2677
 
        utf8_content = unicode_content.encode('utf8')
2678
 
        # Store the raw content in the config file
2679
 
        t.put_bytes('foo.conf', utf8_content)
2680
 
        store = config.IniFileStore(t, 'foo.conf')
2681
 
        store.load()
2682
 
        stack = config.Stack([store.get_sections], store)
2683
 
        self.assertEquals(unicode_user, stack.get('user'))
2684
 
 
2685
 
    def test_load_non_ascii(self):
2686
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2687
 
        t = self.get_transport()
2688
 
        t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2689
 
        store = config.IniFileStore(t, 'foo.conf')
2690
 
        self.assertRaises(errors.ConfigContentError, store.load)
2691
 
 
2692
 
    def test_load_erroneous_content(self):
2693
 
        """Ensure we display a proper error on content that can't be parsed."""
2694
 
        t = self.get_transport()
2695
 
        t.put_bytes('foo.conf', '[open_section\n')
2696
 
        store = config.IniFileStore(t, 'foo.conf')
2697
 
        self.assertRaises(errors.ParseConfigError, store.load)
2698
 
 
2699
 
    def test_load_permission_denied(self):
2700
 
        """Ensure we get warned when trying to load an inaccessible file."""
2701
 
        warnings = []
2702
 
        def warning(*args):
2703
 
            warnings.append(args[0] % args[1:])
2704
 
        self.overrideAttr(trace, 'warning', warning)
2705
 
 
2706
 
        t = self.get_transport()
2707
 
 
2708
 
        def get_bytes(relpath):
2709
 
            raise errors.PermissionDenied(relpath, "")
2710
 
        t.get_bytes = get_bytes
2711
 
        store = config.IniFileStore(t, 'foo.conf')
2712
 
        self.assertRaises(errors.PermissionDenied, store.load)
2713
 
        self.assertEquals(
2714
 
            warnings,
2715
 
            [u'Permission denied while trying to load configuration store %s.'
2716
 
             % store.external_url()])
2717
 
 
2718
 
 
2719
 
class TestIniConfigContent(tests.TestCaseWithTransport):
2720
 
    """Simulate loading a IniBasedConfig with content of various encodings.
2721
 
 
2722
 
    All files produced by bzr are in utf8 content.
2723
 
 
2724
 
    Users may modify them manually and end up with a file that can't be
2725
 
    loaded. We need to issue proper error messages in this case.
2726
 
    """
2727
 
 
2728
 
    invalid_utf8_char = '\xff'
2729
 
 
2730
 
    def test_load_utf8(self):
2731
 
        """Ensure we can load an utf8-encoded file."""
2732
 
        # From http://pad.lv/799212
2733
 
        unicode_user = u'b\N{Euro Sign}ar'
2734
 
        unicode_content = u'user=%s' % (unicode_user,)
2735
 
        utf8_content = unicode_content.encode('utf8')
2736
 
        # Store the raw content in the config file
2737
 
        with open('foo.conf', 'wb') as f:
2738
 
            f.write(utf8_content)
2739
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2740
 
        self.assertEquals(unicode_user, conf.get_user_option('user'))
2741
 
 
2742
 
    def test_load_badly_encoded_content(self):
2743
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2744
 
        with open('foo.conf', 'wb') as f:
2745
 
            f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2746
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2747
 
        self.assertRaises(errors.ConfigContentError, conf._get_parser)
2748
 
 
2749
 
    def test_load_erroneous_content(self):
2750
 
        """Ensure we display a proper error on content that can't be parsed."""
2751
 
        with open('foo.conf', 'wb') as f:
2752
 
            f.write('[open_section\n')
2753
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2754
 
        self.assertRaises(errors.ParseConfigError, conf._get_parser)
2755
 
 
2756
 
 
2757
 
class TestMutableStore(TestStore):
2758
 
 
2759
 
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2760
 
                 in config.test_store_builder_registry.iteritems()]
2761
 
 
2762
 
    def setUp(self):
2763
 
        super(TestMutableStore, self).setUp()
2764
 
        self.transport = self.get_transport()
2765
 
 
2766
 
    def has_store(self, store):
2767
 
        store_basename = urlutils.relative_url(self.transport.external_url(),
2768
 
                                               store.external_url())
2769
 
        return self.transport.has(store_basename)
2770
 
 
2771
 
    def test_save_empty_creates_no_file(self):
2772
 
        # FIXME: There should be a better way than relying on the test
2773
 
        # parametrization to identify branch.conf -- vila 2011-0526
2774
 
        if self.store_id in ('branch', 'remote_branch'):
2775
 
            raise tests.TestNotApplicable(
2776
 
                'branch.conf is *always* created when a branch is initialized')
2777
 
        store = self.get_store(self)
2778
 
        store.save()
2779
 
        self.assertEquals(False, self.has_store(store))
2780
 
 
2781
 
    def test_save_emptied_succeeds(self):
2782
 
        store = self.get_store(self)
2783
 
        store._load_from_string('foo=bar\n')
2784
 
        section = store.get_mutable_section(None)
2785
 
        section.remove('foo')
2786
 
        store.save()
2787
 
        self.assertEquals(True, self.has_store(store))
2788
 
        modified_store = self.get_store(self)
2789
 
        sections = list(modified_store.get_sections())
2790
 
        self.assertLength(0, sections)
2791
 
 
2792
 
    def test_save_with_content_succeeds(self):
2793
 
        # FIXME: There should be a better way than relying on the test
2794
 
        # parametrization to identify branch.conf -- vila 2011-0526
2795
 
        if self.store_id in ('branch', 'remote_branch'):
2796
 
            raise tests.TestNotApplicable(
2797
 
                'branch.conf is *always* created when a branch is initialized')
2798
 
        store = self.get_store(self)
2799
 
        store._load_from_string('foo=bar\n')
2800
 
        self.assertEquals(False, self.has_store(store))
2801
 
        store.save()
2802
 
        self.assertEquals(True, self.has_store(store))
2803
 
        modified_store = self.get_store(self)
2804
 
        sections = list(modified_store.get_sections())
2805
 
        self.assertLength(1, sections)
2806
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2807
 
 
2808
 
    def test_set_option_in_empty_store(self):
2809
 
        store = self.get_store(self)
2810
 
        section = store.get_mutable_section(None)
2811
 
        section.set('foo', 'bar')
2812
 
        store.save()
2813
 
        modified_store = self.get_store(self)
2814
 
        sections = list(modified_store.get_sections())
2815
 
        self.assertLength(1, sections)
2816
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2817
 
 
2818
 
    def test_set_option_in_default_section(self):
2819
 
        store = self.get_store(self)
2820
 
        store._load_from_string('')
2821
 
        section = store.get_mutable_section(None)
2822
 
        section.set('foo', 'bar')
2823
 
        store.save()
2824
 
        modified_store = self.get_store(self)
2825
 
        sections = list(modified_store.get_sections())
2826
 
        self.assertLength(1, sections)
2827
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2828
 
 
2829
 
    def test_set_option_in_named_section(self):
2830
 
        store = self.get_store(self)
2831
 
        store._load_from_string('')
2832
 
        section = store.get_mutable_section('baz')
2833
 
        section.set('foo', 'bar')
2834
 
        store.save()
2835
 
        modified_store = self.get_store(self)
2836
 
        sections = list(modified_store.get_sections())
2837
 
        self.assertLength(1, sections)
2838
 
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2839
 
 
2840
 
    def test_load_hook(self):
2841
 
        # We first needs to ensure that the store exists
2842
 
        store = self.get_store(self)
2843
 
        section = store.get_mutable_section('baz')
2844
 
        section.set('foo', 'bar')
2845
 
        store.save()
2846
 
        # Now we can try to load it
2847
 
        store = self.get_store(self)
2848
 
        calls = []
2849
 
        def hook(*args):
2850
 
            calls.append(args)
2851
 
        config.ConfigHooks.install_named_hook('load', hook, None)
2852
 
        self.assertLength(0, calls)
2853
 
        store.load()
2854
 
        self.assertLength(1, calls)
2855
 
        self.assertEquals((store,), calls[0])
2856
 
 
2857
 
    def test_save_hook(self):
2858
 
        calls = []
2859
 
        def hook(*args):
2860
 
            calls.append(args)
2861
 
        config.ConfigHooks.install_named_hook('save', hook, None)
2862
 
        self.assertLength(0, calls)
2863
 
        store = self.get_store(self)
2864
 
        section = store.get_mutable_section('baz')
2865
 
        section.set('foo', 'bar')
2866
 
        store.save()
2867
 
        self.assertLength(1, calls)
2868
 
        self.assertEquals((store,), calls[0])
2869
 
 
2870
 
 
2871
 
class TestIniFileStore(TestStore):
2872
 
 
2873
 
    def test_loading_unknown_file_fails(self):
2874
 
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
2875
 
        self.assertRaises(errors.NoSuchFile, store.load)
2876
 
 
2877
 
    def test_invalid_content(self):
2878
 
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2879
 
        self.assertEquals(False, store.is_loaded())
2880
 
        exc = self.assertRaises(
2881
 
            errors.ParseConfigError, store._load_from_string,
2882
 
            'this is invalid !')
2883
 
        self.assertEndsWith(exc.filename, 'foo.conf')
2884
 
        # And the load failed
2885
 
        self.assertEquals(False, store.is_loaded())
2886
 
 
2887
 
    def test_get_embedded_sections(self):
2888
 
        # A more complicated example (which also shows that section names and
2889
 
        # option names share the same name space...)
2890
 
        # FIXME: This should be fixed by forbidding dicts as values ?
2891
 
        # -- vila 2011-04-05
2892
 
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2893
 
        store._load_from_string('''
2894
 
foo=bar
2895
 
l=1,2
2896
 
[DEFAULT]
2897
 
foo_in_DEFAULT=foo_DEFAULT
2898
 
[bar]
2899
 
foo_in_bar=barbar
2900
 
[baz]
2901
 
foo_in_baz=barbaz
2902
 
[[qux]]
2903
 
foo_in_qux=quux
2904
 
''')
2905
 
        sections = list(store.get_sections())
2906
 
        self.assertLength(4, sections)
2907
 
        # The default section has no name.
2908
 
        # List values are provided as strings and need to be explicitly
2909
 
        # converted by specifying from_unicode=list_from_store at option
2910
 
        # registration
2911
 
        self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
2912
 
                                  sections[0])
2913
 
        self.assertSectionContent(
2914
 
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2915
 
        self.assertSectionContent(
2916
 
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
2917
 
        # sub sections are provided as embedded dicts.
2918
 
        self.assertSectionContent(
2919
 
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2920
 
            sections[3])
2921
 
 
2922
 
 
2923
 
class TestLockableIniFileStore(TestStore):
2924
 
 
2925
 
    def test_create_store_in_created_dir(self):
2926
 
        self.assertPathDoesNotExist('dir')
2927
 
        t = self.get_transport('dir/subdir')
2928
 
        store = config.LockableIniFileStore(t, 'foo.conf')
2929
 
        store.get_mutable_section(None).set('foo', 'bar')
2930
 
        store.save()
2931
 
        self.assertPathExists('dir/subdir')
2932
 
 
2933
 
 
2934
 
class TestConcurrentStoreUpdates(TestStore):
2935
 
    """Test that Stores properly handle conccurent updates.
2936
 
 
2937
 
    New Store implementation may fail some of these tests but until such
2938
 
    implementations exist it's hard to properly filter them from the scenarios
2939
 
    applied here. If you encounter such a case, contact the bzr devs.
2940
 
    """
2941
 
 
2942
 
    scenarios = [(key, {'get_stack': builder}) for key, builder
2943
 
                 in config.test_stack_builder_registry.iteritems()]
2944
 
 
2945
 
    def setUp(self):
2946
 
        super(TestConcurrentStoreUpdates, self).setUp()
2947
 
        self._content = 'one=1\ntwo=2\n'
2948
 
        self.stack = self.get_stack(self)
2949
 
        if not isinstance(self.stack, config._CompatibleStack):
2950
 
            raise tests.TestNotApplicable(
2951
 
                '%s is not meant to be compatible with the old config design'
2952
 
                % (self.stack,))
2953
 
        self.stack.store._load_from_string(self._content)
2954
 
        # Flush the store
2955
 
        self.stack.store.save()
2956
 
 
2957
 
    def test_simple_read_access(self):
2958
 
        self.assertEquals('1', self.stack.get('one'))
2959
 
 
2960
 
    def test_simple_write_access(self):
2961
 
        self.stack.set('one', 'one')
2962
 
        self.assertEquals('one', self.stack.get('one'))
2963
 
 
2964
 
    def test_listen_to_the_last_speaker(self):
2965
 
        c1 = self.stack
2966
 
        c2 = self.get_stack(self)
2967
 
        c1.set('one', 'ONE')
2968
 
        c2.set('two', 'TWO')
2969
 
        self.assertEquals('ONE', c1.get('one'))
2970
 
        self.assertEquals('TWO', c2.get('two'))
2971
 
        # The second update respect the first one
2972
 
        self.assertEquals('ONE', c2.get('one'))
2973
 
 
2974
 
    def test_last_speaker_wins(self):
2975
 
        # If the same config is not shared, the same variable modified twice
2976
 
        # can only see a single result.
2977
 
        c1 = self.stack
2978
 
        c2 = self.get_stack(self)
2979
 
        c1.set('one', 'c1')
2980
 
        c2.set('one', 'c2')
2981
 
        self.assertEquals('c2', c2.get('one'))
2982
 
        # The first modification is still available until another refresh
2983
 
        # occur
2984
 
        self.assertEquals('c1', c1.get('one'))
2985
 
        c1.set('two', 'done')
2986
 
        self.assertEquals('c2', c1.get('one'))
2987
 
 
2988
 
    def test_writes_are_serialized(self):
2989
 
        c1 = self.stack
2990
 
        c2 = self.get_stack(self)
2991
 
 
2992
 
        # We spawn a thread that will pause *during* the config saving.
2993
 
        before_writing = threading.Event()
2994
 
        after_writing = threading.Event()
2995
 
        writing_done = threading.Event()
2996
 
        c1_save_without_locking_orig = c1.store.save_without_locking
2997
 
        def c1_save_without_locking():
2998
 
            before_writing.set()
2999
 
            c1_save_without_locking_orig()
3000
 
            # The lock is held. We wait for the main thread to decide when to
3001
 
            # continue
3002
 
            after_writing.wait()
3003
 
        c1.store.save_without_locking = c1_save_without_locking
3004
 
        def c1_set():
3005
 
            c1.set('one', 'c1')
3006
 
            writing_done.set()
3007
 
        t1 = threading.Thread(target=c1_set)
3008
 
        # Collect the thread after the test
3009
 
        self.addCleanup(t1.join)
3010
 
        # Be ready to unblock the thread if the test goes wrong
3011
 
        self.addCleanup(after_writing.set)
3012
 
        t1.start()
3013
 
        before_writing.wait()
3014
 
        self.assertRaises(errors.LockContention,
3015
 
                          c2.set, 'one', 'c2')
3016
 
        self.assertEquals('c1', c1.get('one'))
3017
 
        # Let the lock be released
3018
 
        after_writing.set()
3019
 
        writing_done.wait()
3020
 
        c2.set('one', 'c2')
3021
 
        self.assertEquals('c2', c2.get('one'))
3022
 
 
3023
 
    def test_read_while_writing(self):
3024
 
       c1 = self.stack
3025
 
       # We spawn a thread that will pause *during* the write
3026
 
       ready_to_write = threading.Event()
3027
 
       do_writing = threading.Event()
3028
 
       writing_done = threading.Event()
3029
 
       # We override the _save implementation so we know the store is locked
3030
 
       c1_save_without_locking_orig = c1.store.save_without_locking
3031
 
       def c1_save_without_locking():
3032
 
           ready_to_write.set()
3033
 
           # The lock is held. We wait for the main thread to decide when to
3034
 
           # continue
3035
 
           do_writing.wait()
3036
 
           c1_save_without_locking_orig()
3037
 
           writing_done.set()
3038
 
       c1.store.save_without_locking = c1_save_without_locking
3039
 
       def c1_set():
3040
 
           c1.set('one', 'c1')
3041
 
       t1 = threading.Thread(target=c1_set)
3042
 
       # Collect the thread after the test
3043
 
       self.addCleanup(t1.join)
3044
 
       # Be ready to unblock the thread if the test goes wrong
3045
 
       self.addCleanup(do_writing.set)
3046
 
       t1.start()
3047
 
       # Ensure the thread is ready to write
3048
 
       ready_to_write.wait()
3049
 
       self.assertEquals('c1', c1.get('one'))
3050
 
       # If we read during the write, we get the old value
3051
 
       c2 = self.get_stack(self)
3052
 
       self.assertEquals('1', c2.get('one'))
3053
 
       # Let the writing occur and ensure it occurred
3054
 
       do_writing.set()
3055
 
       writing_done.wait()
3056
 
       # Now we get the updated value
3057
 
       c3 = self.get_stack(self)
3058
 
       self.assertEquals('c1', c3.get('one'))
3059
 
 
3060
 
    # FIXME: It may be worth looking into removing the lock dir when it's not
3061
 
    # needed anymore and look at possible fallouts for concurrent lockers. This
3062
 
    # will matter if/when we use config files outside of bazaar directories
3063
 
    # (.bazaar or .bzr) -- vila 20110-04-111
3064
 
 
3065
 
 
3066
 
class TestSectionMatcher(TestStore):
3067
 
 
3068
 
    scenarios = [('location', {'matcher': config.LocationMatcher}),
3069
 
                 ('id', {'matcher': config.NameMatcher}),]
3070
 
 
3071
 
    def get_store(self, file_name):
3072
 
        return config.IniFileStore(self.get_readonly_transport(), file_name)
3073
 
 
3074
 
    def test_no_matches_for_empty_stores(self):
3075
 
        store = self.get_store('foo.conf')
3076
 
        store._load_from_string('')
3077
 
        matcher = self.matcher(store, '/bar')
3078
 
        self.assertEquals([], list(matcher.get_sections()))
3079
 
 
3080
 
    def test_build_doesnt_load_store(self):
3081
 
        store = self.get_store('foo.conf')
3082
 
        matcher = self.matcher(store, '/bar')
3083
 
        self.assertFalse(store.is_loaded())
3084
 
 
3085
 
 
3086
 
class TestLocationSection(tests.TestCase):
3087
 
 
3088
 
    def get_section(self, options, extra_path):
3089
 
        section = config.Section('foo', options)
3090
 
        # We don't care about the length so we use '0'
3091
 
        return config.LocationSection(section, 0, extra_path)
3092
 
 
3093
 
    def test_simple_option(self):
3094
 
        section = self.get_section({'foo': 'bar'}, '')
3095
 
        self.assertEquals('bar', section.get('foo'))
3096
 
 
3097
 
    def test_option_with_extra_path(self):
3098
 
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
3099
 
                                   'baz')
3100
 
        self.assertEquals('bar/baz', section.get('foo'))
3101
 
 
3102
 
    def test_invalid_policy(self):
3103
 
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
3104
 
                                   'baz')
3105
 
        # invalid policies are ignored
3106
 
        self.assertEquals('bar', section.get('foo'))
3107
 
 
3108
 
 
3109
 
class TestLocationMatcher(TestStore):
3110
 
 
3111
 
    def get_store(self, file_name):
3112
 
        return config.IniFileStore(self.get_readonly_transport(), file_name)
3113
 
 
3114
 
    def test_unrelated_section_excluded(self):
3115
 
        store = self.get_store('foo.conf')
3116
 
        store._load_from_string('''
3117
 
[/foo]
3118
 
section=/foo
3119
 
[/foo/baz]
3120
 
section=/foo/baz
3121
 
[/foo/bar]
3122
 
section=/foo/bar
3123
 
[/foo/bar/baz]
3124
 
section=/foo/bar/baz
3125
 
[/quux/quux]
3126
 
section=/quux/quux
3127
 
''')
3128
 
        self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3129
 
                           '/quux/quux'],
3130
 
                          [section.id for section in store.get_sections()])
3131
 
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
3132
 
        sections = list(matcher.get_sections())
3133
 
        self.assertEquals([3, 2],
3134
 
                          [section.length for section in sections])
3135
 
        self.assertEquals(['/foo/bar', '/foo'],
3136
 
                          [section.id for section in sections])
3137
 
        self.assertEquals(['quux', 'bar/quux'],
3138
 
                          [section.extra_path for section in sections])
3139
 
 
3140
 
    def test_more_specific_sections_first(self):
3141
 
        store = self.get_store('foo.conf')
3142
 
        store._load_from_string('''
3143
 
[/foo]
3144
 
section=/foo
3145
 
[/foo/bar]
3146
 
section=/foo/bar
3147
 
''')
3148
 
        self.assertEquals(['/foo', '/foo/bar'],
3149
 
                          [section.id for section in store.get_sections()])
3150
 
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
3151
 
        sections = list(matcher.get_sections())
3152
 
        self.assertEquals([3, 2],
3153
 
                          [section.length for section in sections])
3154
 
        self.assertEquals(['/foo/bar', '/foo'],
3155
 
                          [section.id for section in sections])
3156
 
        self.assertEquals(['baz', 'bar/baz'],
3157
 
                          [section.extra_path for section in sections])
3158
 
 
3159
 
    def test_appendpath_in_no_name_section(self):
3160
 
        # It's a bit weird to allow appendpath in a no-name section, but
3161
 
        # someone may found a use for it
3162
 
        store = self.get_store('foo.conf')
3163
 
        store._load_from_string('''
3164
 
foo=bar
3165
 
foo:policy = appendpath
3166
 
''')
3167
 
        matcher = config.LocationMatcher(store, 'dir/subdir')
3168
 
        sections = list(matcher.get_sections())
3169
 
        self.assertLength(1, sections)
3170
 
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
3171
 
 
3172
 
    def test_file_urls_are_normalized(self):
3173
 
        store = self.get_store('foo.conf')
3174
 
        if sys.platform == 'win32':
3175
 
            expected_url = 'file:///C:/dir/subdir'
3176
 
            expected_location = 'C:/dir/subdir'
3177
 
        else:
3178
 
            expected_url = 'file:///dir/subdir'
3179
 
            expected_location = '/dir/subdir'
3180
 
        matcher = config.LocationMatcher(store, expected_url)
3181
 
        self.assertEquals(expected_location, matcher.location)
3182
 
 
3183
 
 
3184
 
class TestNameMatcher(TestStore):
3185
 
 
3186
 
    def setUp(self):
3187
 
        super(TestNameMatcher, self).setUp()
3188
 
        self.store = config.IniFileStore(self.get_readonly_transport(),
3189
 
                                         'foo.conf')
3190
 
        self.store._load_from_string('''
3191
 
[foo]
3192
 
option=foo
3193
 
[foo/baz]
3194
 
option=foo/baz
3195
 
[bar]
3196
 
option=bar
3197
 
''')
3198
 
 
3199
 
    def get_matching_sections(self, name):
3200
 
        matcher = config.NameMatcher(self.store, name)
3201
 
        return list(matcher.get_sections())
3202
 
 
3203
 
    def test_matching(self):
3204
 
        sections = self.get_matching_sections('foo')
3205
 
        self.assertLength(1, sections)
3206
 
        self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3207
 
 
3208
 
    def test_not_matching(self):
3209
 
        sections = self.get_matching_sections('baz')
3210
 
        self.assertLength(0, sections)
3211
 
 
3212
 
 
3213
 
class TestStackGet(tests.TestCase):
3214
 
 
3215
 
    # FIXME: This should be parametrized for all known Stack or dedicated
3216
 
    # paramerized tests created to avoid bloating -- vila 2011-03-31
3217
 
 
3218
 
    def overrideOptionRegistry(self):
3219
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3220
 
 
3221
 
    def test_single_config_get(self):
3222
 
        conf = dict(foo='bar')
3223
 
        conf_stack = config.Stack([conf])
3224
 
        self.assertEquals('bar', conf_stack.get('foo'))
3225
 
 
3226
 
    def test_get_with_registered_default_value(self):
3227
 
        conf_stack = config.Stack([dict()])
3228
 
        opt = config.Option('foo', default='bar')
3229
 
        self.overrideOptionRegistry()
3230
 
        config.option_registry.register('foo', opt)
3231
 
        self.assertEquals('bar', conf_stack.get('foo'))
3232
 
 
3233
 
    def test_get_without_registered_default_value(self):
3234
 
        conf_stack = config.Stack([dict()])
3235
 
        opt = config.Option('foo')
3236
 
        self.overrideOptionRegistry()
3237
 
        config.option_registry.register('foo', opt)
3238
 
        self.assertEquals(None, conf_stack.get('foo'))
3239
 
 
3240
 
    def test_get_without_default_value_for_not_registered(self):
3241
 
        conf_stack = config.Stack([dict()])
3242
 
        opt = config.Option('foo')
3243
 
        self.overrideOptionRegistry()
3244
 
        self.assertEquals(None, conf_stack.get('foo'))
3245
 
 
3246
 
    def test_get_first_definition(self):
3247
 
        conf1 = dict(foo='bar')
3248
 
        conf2 = dict(foo='baz')
3249
 
        conf_stack = config.Stack([conf1, conf2])
3250
 
        self.assertEquals('bar', conf_stack.get('foo'))
3251
 
 
3252
 
    def test_get_embedded_definition(self):
3253
 
        conf1 = dict(yy='12')
3254
 
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
3255
 
        conf_stack = config.Stack([conf1, conf2])
3256
 
        self.assertEquals('baz', conf_stack.get('foo'))
3257
 
 
3258
 
    def test_get_for_empty_section_callable(self):
3259
 
        conf_stack = config.Stack([lambda : []])
3260
 
        self.assertEquals(None, conf_stack.get('foo'))
3261
 
 
3262
 
    def test_get_for_broken_callable(self):
3263
 
        # Trying to use and invalid callable raises an exception on first use
3264
 
        conf_stack = config.Stack([lambda : object()])
3265
 
        self.assertRaises(TypeError, conf_stack.get, 'foo')
3266
 
 
3267
 
 
3268
 
class TestStackWithTransport(tests.TestCaseWithTransport):
3269
 
 
3270
 
    scenarios = [(key, {'get_stack': builder}) for key, builder
3271
 
                 in config.test_stack_builder_registry.iteritems()]
3272
 
 
3273
 
 
3274
 
class TestConcreteStacks(TestStackWithTransport):
3275
 
 
3276
 
    def test_build_stack(self):
3277
 
        # Just a smoke test to help debug builders
3278
 
        stack = self.get_stack(self)
3279
 
 
3280
 
 
3281
 
class TestStackGet(TestStackWithTransport):
3282
 
 
3283
 
    def setUp(self):
3284
 
        super(TestStackGet, self).setUp()
3285
 
        self.conf = self.get_stack(self)
3286
 
 
3287
 
    def test_get_for_empty_stack(self):
3288
 
        self.assertEquals(None, self.conf.get('foo'))
3289
 
 
3290
 
    def test_get_hook(self):
3291
 
        self.conf.store._load_from_string('foo=bar')
3292
 
        calls = []
3293
 
        def hook(*args):
3294
 
            calls.append(args)
3295
 
        config.ConfigHooks.install_named_hook('get', hook, None)
3296
 
        self.assertLength(0, calls)
3297
 
        value = self.conf.get('foo')
3298
 
        self.assertEquals('bar', value)
3299
 
        self.assertLength(1, calls)
3300
 
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3301
 
 
3302
 
 
3303
 
class TestStackGetWithConverter(TestStackGet):
3304
 
 
3305
 
    def setUp(self):
3306
 
        super(TestStackGetWithConverter, self).setUp()
3307
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3308
 
        self.registry = config.option_registry
3309
 
 
3310
 
    def register_bool_option(self, name, default=None, default_from_env=None):
3311
 
        b = config.Option(name, help='A boolean.',
3312
 
                          default=default, default_from_env=default_from_env,
3313
 
                          from_unicode=config.bool_from_store)
3314
 
        self.registry.register(b)
3315
 
 
3316
 
    def test_get_default_bool_None(self):
3317
 
        self.register_bool_option('foo')
3318
 
        self.assertEquals(None, self.conf.get('foo'))
3319
 
 
3320
 
    def test_get_default_bool_True(self):
3321
 
        self.register_bool_option('foo', u'True')
3322
 
        self.assertEquals(True, self.conf.get('foo'))
3323
 
 
3324
 
    def test_get_default_bool_False(self):
3325
 
        self.register_bool_option('foo', False)
3326
 
        self.assertEquals(False, self.conf.get('foo'))
3327
 
 
3328
 
    def test_get_default_bool_False_as_string(self):
3329
 
        self.register_bool_option('foo', u'False')
3330
 
        self.assertEquals(False, self.conf.get('foo'))
3331
 
 
3332
 
    def test_get_default_bool_from_env_converted(self):
3333
 
        self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3334
 
        self.overrideEnv('FOO', 'False')
3335
 
        self.assertEquals(False, self.conf.get('foo'))
3336
 
 
3337
 
    def test_get_default_bool_when_conversion_fails(self):
3338
 
        self.register_bool_option('foo', default='True')
3339
 
        self.conf.store._load_from_string('foo=invalid boolean')
3340
 
        self.assertEquals(True, self.conf.get('foo'))
3341
 
 
3342
 
    def register_integer_option(self, name,
3343
 
                                default=None, default_from_env=None):
3344
 
        i = config.Option(name, help='An integer.',
3345
 
                          default=default, default_from_env=default_from_env,
3346
 
                          from_unicode=config.int_from_store)
3347
 
        self.registry.register(i)
3348
 
 
3349
 
    def test_get_default_integer_None(self):
3350
 
        self.register_integer_option('foo')
3351
 
        self.assertEquals(None, self.conf.get('foo'))
3352
 
 
3353
 
    def test_get_default_integer(self):
3354
 
        self.register_integer_option('foo', 42)
3355
 
        self.assertEquals(42, self.conf.get('foo'))
3356
 
 
3357
 
    def test_get_default_integer_as_string(self):
3358
 
        self.register_integer_option('foo', u'42')
3359
 
        self.assertEquals(42, self.conf.get('foo'))
3360
 
 
3361
 
    def test_get_default_integer_from_env(self):
3362
 
        self.register_integer_option('foo', default_from_env=['FOO'])
3363
 
        self.overrideEnv('FOO', '18')
3364
 
        self.assertEquals(18, self.conf.get('foo'))
3365
 
 
3366
 
    def test_get_default_integer_when_conversion_fails(self):
3367
 
        self.register_integer_option('foo', default='12')
3368
 
        self.conf.store._load_from_string('foo=invalid integer')
3369
 
        self.assertEquals(12, self.conf.get('foo'))
3370
 
 
3371
 
    def register_list_option(self, name, default=None, default_from_env=None):
3372
 
        l = config.Option(name, help='A list.',
3373
 
                          default=default, default_from_env=default_from_env,
3374
 
                          from_unicode=config.list_from_store)
3375
 
        self.registry.register(l)
3376
 
 
3377
 
    def test_get_default_list_None(self):
3378
 
        self.register_list_option('foo')
3379
 
        self.assertEquals(None, self.conf.get('foo'))
3380
 
 
3381
 
    def test_get_default_list_empty(self):
3382
 
        self.register_list_option('foo', '')
3383
 
        self.assertEquals([], self.conf.get('foo'))
3384
 
 
3385
 
    def test_get_default_list_from_env(self):
3386
 
        self.register_list_option('foo', default_from_env=['FOO'])
3387
 
        self.overrideEnv('FOO', '')
3388
 
        self.assertEquals([], self.conf.get('foo'))
3389
 
 
3390
 
    def test_get_with_list_converter_no_item(self):
3391
 
        self.register_list_option('foo', None)
3392
 
        self.conf.store._load_from_string('foo=,')
3393
 
        self.assertEquals([], self.conf.get('foo'))
3394
 
 
3395
 
    def test_get_with_list_converter_many_items(self):
3396
 
        self.register_list_option('foo', None)
3397
 
        self.conf.store._load_from_string('foo=m,o,r,e')
3398
 
        self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
3399
 
 
3400
 
    def test_get_with_list_converter_embedded_spaces_many_items(self):
3401
 
        self.register_list_option('foo', None)
3402
 
        self.conf.store._load_from_string('foo=" bar", "baz "')
3403
 
        self.assertEquals([' bar', 'baz '], self.conf.get('foo'))
3404
 
 
3405
 
    def test_get_with_list_converter_stripped_spaces_many_items(self):
3406
 
        self.register_list_option('foo', None)
3407
 
        self.conf.store._load_from_string('foo= bar ,  baz ')
3408
 
        self.assertEquals(['bar', 'baz'], self.conf.get('foo'))
3409
 
 
3410
 
 
3411
 
class TestStackExpandOptions(tests.TestCaseWithTransport):
3412
 
 
3413
 
    def setUp(self):
3414
 
        super(TestStackExpandOptions, self).setUp()
3415
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3416
 
        self.registry = config.option_registry
3417
 
        self.conf = build_branch_stack(self)
3418
 
 
3419
 
    def assertExpansion(self, expected, string, env=None):
3420
 
        self.assertEquals(expected, self.conf.expand_options(string, env))
3421
 
 
3422
 
    def test_no_expansion(self):
3423
 
        self.assertExpansion('foo', 'foo')
3424
 
 
3425
 
    def test_expand_default_value(self):
3426
 
        self.conf.store._load_from_string('bar=baz')
3427
 
        self.registry.register(config.Option('foo', default=u'{bar}'))
3428
 
        self.assertEquals('baz', self.conf.get('foo', expand=True))
3429
 
 
3430
 
    def test_expand_default_from_env(self):
3431
 
        self.conf.store._load_from_string('bar=baz')
3432
 
        self.registry.register(config.Option('foo', default_from_env=['FOO']))
3433
 
        self.overrideEnv('FOO', '{bar}')
3434
 
        self.assertEquals('baz', self.conf.get('foo', expand=True))
3435
 
 
3436
 
    def test_expand_default_on_failed_conversion(self):
3437
 
        self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
3438
 
        self.registry.register(
3439
 
            config.Option('foo', default=u'{bar}',
3440
 
                          from_unicode=config.int_from_store))
3441
 
        self.assertEquals(42, self.conf.get('foo', expand=True))
3442
 
 
3443
 
    def test_env_adding_options(self):
3444
 
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3445
 
 
3446
 
    def test_env_overriding_options(self):
3447
 
        self.conf.store._load_from_string('foo=baz')
3448
 
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3449
 
 
3450
 
    def test_simple_ref(self):
3451
 
        self.conf.store._load_from_string('foo=xxx')
3452
 
        self.assertExpansion('xxx', '{foo}')
3453
 
 
3454
 
    def test_unknown_ref(self):
3455
 
        self.assertRaises(errors.ExpandingUnknownOption,
3456
 
                          self.conf.expand_options, '{foo}')
3457
 
 
3458
 
    def test_indirect_ref(self):
3459
 
        self.conf.store._load_from_string('''
3460
 
foo=xxx
3461
 
bar={foo}
3462
 
''')
3463
 
        self.assertExpansion('xxx', '{bar}')
3464
 
 
3465
 
    def test_embedded_ref(self):
3466
 
        self.conf.store._load_from_string('''
3467
 
foo=xxx
3468
 
bar=foo
3469
 
''')
3470
 
        self.assertExpansion('xxx', '{{bar}}')
3471
 
 
3472
 
    def test_simple_loop(self):
3473
 
        self.conf.store._load_from_string('foo={foo}')
3474
 
        self.assertRaises(errors.OptionExpansionLoop,
3475
 
                          self.conf.expand_options, '{foo}')
3476
 
 
3477
 
    def test_indirect_loop(self):
3478
 
        self.conf.store._load_from_string('''
3479
 
foo={bar}
3480
 
bar={baz}
3481
 
baz={foo}''')
3482
 
        e = self.assertRaises(errors.OptionExpansionLoop,
3483
 
                              self.conf.expand_options, '{foo}')
3484
 
        self.assertEquals('foo->bar->baz', e.refs)
3485
 
        self.assertEquals('{foo}', e.string)
3486
 
 
3487
 
    def test_list(self):
3488
 
        self.conf.store._load_from_string('''
3489
 
foo=start
3490
 
bar=middle
3491
 
baz=end
3492
 
list={foo},{bar},{baz}
3493
 
''')
3494
 
        self.registry.register(
3495
 
            config.Option('list', from_unicode=config.list_from_store))
3496
 
        self.assertEquals(['start', 'middle', 'end'],
3497
 
                           self.conf.get('list', expand=True))
3498
 
 
3499
 
    def test_cascading_list(self):
3500
 
        self.conf.store._load_from_string('''
3501
 
foo=start,{bar}
3502
 
bar=middle,{baz}
3503
 
baz=end
3504
 
list={foo}
3505
 
''')
3506
 
        self.registry.register(
3507
 
            config.Option('list', from_unicode=config.list_from_store))
3508
 
        self.assertEquals(['start', 'middle', 'end'],
3509
 
                           self.conf.get('list', expand=True))
3510
 
 
3511
 
    def test_pathologically_hidden_list(self):
3512
 
        self.conf.store._load_from_string('''
3513
 
foo=bin
3514
 
bar=go
3515
 
start={foo
3516
 
middle=},{
3517
 
end=bar}
3518
 
hidden={start}{middle}{end}
3519
 
''')
3520
 
        # What matters is what the registration says, the conversion happens
3521
 
        # only after all expansions have been performed
3522
 
        self.registry.register(
3523
 
            config.Option('hidden', from_unicode=config.list_from_store))
3524
 
        self.assertEquals(['bin', 'go'],
3525
 
                          self.conf.get('hidden', expand=True))
3526
 
 
3527
 
 
3528
 
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3529
 
 
3530
 
    def setUp(self):
3531
 
        super(TestStackCrossSectionsExpand, self).setUp()
3532
 
 
3533
 
    def get_config(self, location, string):
3534
 
        if string is None:
3535
 
            string = ''
3536
 
        # Since we don't save the config we won't strictly require to inherit
3537
 
        # from TestCaseInTempDir, but an error occurs so quickly...
3538
 
        c = config.LocationStack(location)
3539
 
        c.store._load_from_string(string)
3540
 
        return c
3541
 
 
3542
 
    def test_dont_cross_unrelated_section(self):
3543
 
        c = self.get_config('/another/branch/path','''
3544
 
[/one/branch/path]
3545
 
foo = hello
3546
 
bar = {foo}/2
3547
 
 
3548
 
[/another/branch/path]
3549
 
bar = {foo}/2
3550
 
''')
3551
 
        self.assertRaises(errors.ExpandingUnknownOption,
3552
 
                          c.get, 'bar', expand=True)
3553
 
 
3554
 
    def test_cross_related_sections(self):
3555
 
        c = self.get_config('/project/branch/path','''
3556
 
[/project]
3557
 
foo = qu
3558
 
 
3559
 
[/project/branch/path]
3560
 
bar = {foo}ux
3561
 
''')
3562
 
        self.assertEquals('quux', c.get('bar', expand=True))
3563
 
 
3564
 
 
3565
 
class TestStackSet(TestStackWithTransport):
3566
 
 
3567
 
    def test_simple_set(self):
3568
 
        conf = self.get_stack(self)
3569
 
        conf.store._load_from_string('foo=bar')
3570
 
        self.assertEquals('bar', conf.get('foo'))
3571
 
        conf.set('foo', 'baz')
3572
 
        # Did we get it back ?
3573
 
        self.assertEquals('baz', conf.get('foo'))
3574
 
 
3575
 
    def test_set_creates_a_new_section(self):
3576
 
        conf = self.get_stack(self)
3577
 
        conf.set('foo', 'baz')
3578
 
        self.assertEquals, 'baz', conf.get('foo')
3579
 
 
3580
 
    def test_set_hook(self):
3581
 
        calls = []
3582
 
        def hook(*args):
3583
 
            calls.append(args)
3584
 
        config.ConfigHooks.install_named_hook('set', hook, None)
3585
 
        self.assertLength(0, calls)
3586
 
        conf = self.get_stack(self)
3587
 
        conf.set('foo', 'bar')
3588
 
        self.assertLength(1, calls)
3589
 
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
3590
 
 
3591
 
 
3592
 
class TestStackRemove(TestStackWithTransport):
3593
 
 
3594
 
    def test_remove_existing(self):
3595
 
        conf = self.get_stack(self)
3596
 
        conf.store._load_from_string('foo=bar')
3597
 
        self.assertEquals('bar', conf.get('foo'))
3598
 
        conf.remove('foo')
3599
 
        # Did we get it back ?
3600
 
        self.assertEquals(None, conf.get('foo'))
3601
 
 
3602
 
    def test_remove_unknown(self):
3603
 
        conf = self.get_stack(self)
3604
 
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3605
 
 
3606
 
    def test_remove_hook(self):
3607
 
        calls = []
3608
 
        def hook(*args):
3609
 
            calls.append(args)
3610
 
        config.ConfigHooks.install_named_hook('remove', hook, None)
3611
 
        self.assertLength(0, calls)
3612
 
        conf = self.get_stack(self)
3613
 
        conf.store._load_from_string('foo=bar')
3614
 
        conf.remove('foo')
3615
 
        self.assertLength(1, calls)
3616
 
        self.assertEquals((conf, 'foo'), calls[0])
3617
 
 
3618
 
 
3619
1821
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3620
1822
 
3621
1823
    def setUp(self):
3622
1824
        super(TestConfigGetOptions, self).setUp()
3623
1825
        create_configs(self)
3624
1826
 
 
1827
    # One variable in none of the above
3625
1828
    def test_no_variable(self):
3626
1829
        # Using branch should query branch, locations and bazaar
3627
1830
        self.assertOptions([], self.branch_config)
3787
1990
        self.assertEquals({}, conf._get_config())
3788
1991
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
3789
1992
 
3790
 
    def test_non_utf8_config(self):
3791
 
        conf = config.AuthenticationConfig(_file=StringIO(
3792
 
                'foo = bar\xff'))
3793
 
        self.assertRaises(errors.ConfigContentError, conf._get_config)
3794
 
 
3795
1993
    def test_missing_auth_section_header(self):
3796
1994
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
3797
1995
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
4055
2253
 
4056
2254
    def test_username_defaults_prompts(self):
4057
2255
        # HTTP prompts can't be tested here, see test_http.py
4058
 
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
4059
 
        self._check_default_username_prompt(
4060
 
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
4061
 
        self._check_default_username_prompt(
4062
 
            u'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
 
2256
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
 
2257
        self._check_default_username_prompt(
 
2258
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
 
2259
        self._check_default_username_prompt(
 
2260
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
4063
2261
 
4064
2262
    def test_username_default_no_prompt(self):
4065
2263
        conf = config.AuthenticationConfig()
4071
2269
    def test_password_default_prompts(self):
4072
2270
        # HTTP prompts can't be tested here, see test_http.py
4073
2271
        self._check_default_password_prompt(
4074
 
            u'FTP %(user)s@%(host)s password: ', 'ftp')
4075
 
        self._check_default_password_prompt(
4076
 
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
4077
 
        self._check_default_password_prompt(
4078
 
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
 
2272
            'FTP %(user)s@%(host)s password: ', 'ftp')
 
2273
        self._check_default_password_prompt(
 
2274
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
 
2275
        self._check_default_password_prompt(
 
2276
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
4079
2277
        # SMTP port handling is a bit special (it's handled if embedded in the
4080
2278
        # host too)
4081
2279
        # FIXME: should we: forbid that, extend it to other schemes, leave
4082
2280
        # things as they are that's fine thank you ?
4083
 
        self._check_default_password_prompt(
4084
 
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
4085
 
        self._check_default_password_prompt(
4086
 
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
4087
 
        self._check_default_password_prompt(
4088
 
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
 
2281
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
 
2282
                                            'smtp')
 
2283
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
 
2284
                                            'smtp', host='bar.org:10025')
 
2285
        self._check_default_password_prompt(
 
2286
            'SMTP %(user)s@%(host)s:%(port)d password: ',
 
2287
            'smtp', port=10025)
4089
2288
 
4090
2289
    def test_ssh_password_emits_warning(self):
4091
2290
        conf = config.AuthenticationConfig(_file=StringIO(
4285
2484
        to be able to choose a user name with no configuration.
4286
2485
        """
4287
2486
        if sys.platform == 'win32':
4288
 
            raise tests.TestSkipped(
4289
 
                "User name inference not implemented on win32")
 
2487
            raise TestSkipped("User name inference not implemented on win32")
4290
2488
        realname, address = config._auto_user_id()
4291
2489
        if os.path.exists('/etc/mailname'):
4292
 
            self.assertIsNot(None, realname)
4293
 
            self.assertIsNot(None, address)
 
2490
            self.assertTrue(realname)
 
2491
            self.assertTrue(address)
4294
2492
        else:
4295
2493
            self.assertEquals((None, None), (realname, address))
4296
2494