~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Martin Packman
  • Date: 2012-01-05 10:37:58 UTC
  • mto: This revision was merged to the branch mainline in revision 6427.
  • Revision ID: martin.packman@canonical.com-20120105103758-wzftnmsip5iv9n2g
Revert addition of get_message_encoding function

Show diffs side-by-side

added added

removed removed

Lines of Context:
33
33
    errors,
34
34
    osutils,
35
35
    mail_client,
36
 
    mergetools,
37
36
    ui,
38
37
    urlutils,
39
 
    registry,
40
38
    remote,
41
39
    tests,
42
40
    trace,
43
 
    transport,
44
41
    )
45
42
from bzrlib.symbol_versioning import (
46
43
    deprecated_in,
47
 
    deprecated_method,
48
44
    )
49
45
from bzrlib.transport import remote as transport_remote
50
46
from bzrlib.tests import (
71
67
 
72
68
# Register helpers to build stores
73
69
config.test_store_builder_registry.register(
74
 
    'configobj', lambda test: config.IniFileStore(test.get_transport(),
75
 
                                                  'configobj.conf'))
 
70
    'configobj', lambda test: config.TransportIniFileStore(
 
71
        test.get_transport(), 'configobj.conf'))
76
72
config.test_store_builder_registry.register(
77
73
    'bazaar', lambda test: config.GlobalStore())
78
74
config.test_store_builder_registry.register(
116
112
config.test_store_builder_registry.register('branch', build_branch_store)
117
113
 
118
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
 
119
122
def build_remote_branch_store(test):
120
123
    # There is only one permutation (but we won't be able to handle more with
121
124
    # this design anyway)
148
151
     server_class) = transport_remote.get_test_permutations()[0]
149
152
    build_backing_branch(test, 'branch', transport_class, server_class)
150
153
    b = branch.Branch.open(test.get_url('branch'))
151
 
    return config.BranchStack(b)
 
154
    return config.RemoteBranchStack(b)
152
155
config.test_stack_builder_registry.register('remote_branch',
153
156
                                            build_remote_branch_stack)
154
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
 
155
171
 
156
172
sample_long_alias="log -r-15..-1 --line"
157
173
sample_config_text = u"""
160
176
editor=vim
161
177
change_editor=vimdiff -of @new_path @old_path
162
178
gpg_signing_command=gnome-gpg
 
179
gpg_signing_key=DD4D5088
163
180
log_format=short
164
181
validate_signatures_in_log=true
165
182
acceptable_keys=amy
166
183
user_global_option=something
167
184
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
168
185
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
 
186
bzr.mergetool.newtool='"newtool with spaces" {this_temp}'
169
187
bzr.default_mergetool=sometool
170
188
[ALIASES]
171
189
h=help
214
232
[/a/]
215
233
check_signatures=check-available
216
234
gpg_signing_command=false
 
235
gpg_signing_key=default
217
236
user_local_option=local
218
237
# test trailing / matching
219
238
[/a/*]
309
328
 
310
329
class FakeBranch(object):
311
330
 
312
 
    def __init__(self, base=None, user_id=None):
 
331
    def __init__(self, base=None):
313
332
        if base is None:
314
333
            self.base = "http://example.com/branches/demo"
315
334
        else:
316
335
            self.base = base
317
336
        self._transport = self.control_files = \
318
 
            FakeControlFilesAndTransport(user_id=user_id)
 
337
            FakeControlFilesAndTransport()
319
338
 
320
339
    def _get_config(self):
321
340
        return config.TransportConfig(self._transport, 'branch.conf')
329
348
 
330
349
class FakeControlFilesAndTransport(object):
331
350
 
332
 
    def __init__(self, user_id=None):
 
351
    def __init__(self):
333
352
        self.files = {}
334
 
        if user_id:
335
 
            self.files['email'] = user_id
336
353
        self._transport = self
337
354
 
338
 
    def get_utf8(self, filename):
339
 
        # from LockableFiles
340
 
        raise AssertionError("get_utf8 should no longer be used")
341
 
 
342
355
    def get(self, filename):
343
356
        # from Transport
344
357
        try:
481
494
 
482
495
    def test_signatures_default(self):
483
496
        my_config = config.Config()
484
 
        self.assertFalse(my_config.signature_needed())
 
497
        self.assertFalse(
 
498
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
499
                my_config.signature_needed))
485
500
        self.assertEqual(config.CHECK_IF_POSSIBLE,
486
 
                         my_config.signature_checking())
 
501
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
502
                my_config.signature_checking))
487
503
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
488
 
                         my_config.signing_policy())
 
504
                self.applyDeprecated(deprecated_in((2, 5, 0)),
 
505
                    my_config.signing_policy))
489
506
 
490
507
    def test_signatures_template_method(self):
491
508
        my_config = InstrumentedConfig()
492
 
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
509
        self.assertEqual(config.CHECK_NEVER,
 
510
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
511
                my_config.signature_checking))
493
512
        self.assertEqual(['_get_signature_checking'], my_config._calls)
494
513
 
495
514
    def test_signatures_template_method_none(self):
496
515
        my_config = InstrumentedConfig()
497
516
        my_config._signatures = None
498
517
        self.assertEqual(config.CHECK_IF_POSSIBLE,
499
 
                         my_config.signature_checking())
 
518
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
519
                             my_config.signature_checking))
500
520
        self.assertEqual(['_get_signature_checking'], my_config._calls)
501
521
 
502
522
    def test_gpg_signing_command_default(self):
503
523
        my_config = config.Config()
504
 
        self.assertEqual('gpg', my_config.gpg_signing_command())
 
524
        self.assertEqual('gpg',
 
525
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
526
                my_config.gpg_signing_command))
505
527
 
506
528
    def test_get_user_option_default(self):
507
529
        my_config = config.Config()
509
531
 
510
532
    def test_post_commit_default(self):
511
533
        my_config = config.Config()
512
 
        self.assertEqual(None, my_config.post_commit())
 
534
        self.assertEqual(None, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
535
                                                    my_config.post_commit))
 
536
 
513
537
 
514
538
    def test_log_format_default(self):
515
539
        my_config = config.Config()
517
541
 
518
542
    def test_acceptable_keys_default(self):
519
543
        my_config = config.Config()
520
 
        self.assertEqual(None, my_config.acceptable_keys())
 
544
        self.assertEqual(None, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
545
            my_config.acceptable_keys))
521
546
 
522
547
    def test_validate_signatures_in_log_default(self):
523
548
        my_config = config.Config()
817
842
        self.assertEquals(['{foo', '}', '{', 'bar}'],
818
843
                          conf.get_user_option('hidden', expand=True))
819
844
 
 
845
 
820
846
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
821
847
 
822
848
    def get_config(self, location, string=None):
1033
1059
        # automatically cast to list
1034
1060
        self.assertEqual(['x'], get_list('one_item'))
1035
1061
 
 
1062
    def test_get_user_option_as_int_from_SI(self):
 
1063
        conf, parser = self.make_config_parser("""
 
1064
plain = 100
 
1065
si_k = 5k,
 
1066
si_kb = 5kb,
 
1067
si_m = 5M,
 
1068
si_mb = 5MB,
 
1069
si_g = 5g,
 
1070
si_gb = 5gB,
 
1071
""")
 
1072
        get_si = conf.get_user_option_as_int_from_SI
 
1073
        self.assertEqual(100, get_si('plain'))
 
1074
        self.assertEqual(5000, get_si('si_k'))
 
1075
        self.assertEqual(5000, get_si('si_kb'))
 
1076
        self.assertEqual(5000000, get_si('si_m'))
 
1077
        self.assertEqual(5000000, get_si('si_mb'))
 
1078
        self.assertEqual(5000000000, get_si('si_g'))
 
1079
        self.assertEqual(5000000000, get_si('si_gb'))
 
1080
        self.assertEqual(None, get_si('non-exist'))
 
1081
        self.assertEqual(42, get_si('non-exist-with-default',  42))
1036
1082
 
1037
1083
class TestSupressWarning(TestIniConfig):
1038
1084
 
1195
1241
    def test_signatures_always(self):
1196
1242
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
1197
1243
        self.assertEqual(config.CHECK_NEVER,
1198
 
                         my_config.signature_checking())
 
1244
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1245
                             my_config.signature_checking))
1199
1246
        self.assertEqual(config.SIGN_ALWAYS,
1200
 
                         my_config.signing_policy())
1201
 
        self.assertEqual(True, my_config.signature_needed())
 
1247
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1248
                             my_config.signing_policy))
 
1249
        self.assertEqual(True,
 
1250
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1251
                my_config.signature_needed))
1202
1252
 
1203
1253
    def test_signatures_if_possible(self):
1204
1254
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
1205
1255
        self.assertEqual(config.CHECK_NEVER,
1206
 
                         my_config.signature_checking())
 
1256
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1257
                             my_config.signature_checking))
1207
1258
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
1208
 
                         my_config.signing_policy())
1209
 
        self.assertEqual(False, my_config.signature_needed())
 
1259
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1260
                             my_config.signing_policy))
 
1261
        self.assertEqual(False, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1262
            my_config.signature_needed))
1210
1263
 
1211
1264
    def test_signatures_ignore(self):
1212
1265
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
1213
1266
        self.assertEqual(config.CHECK_ALWAYS,
1214
 
                         my_config.signature_checking())
 
1267
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1268
                             my_config.signature_checking))
1215
1269
        self.assertEqual(config.SIGN_NEVER,
1216
 
                         my_config.signing_policy())
1217
 
        self.assertEqual(False, my_config.signature_needed())
 
1270
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1271
                             my_config.signing_policy))
 
1272
        self.assertEqual(False, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1273
            my_config.signature_needed))
1218
1274
 
1219
1275
    def _get_sample_config(self):
1220
1276
        my_config = config.GlobalConfig.from_string(sample_config_text)
1222
1278
 
1223
1279
    def test_gpg_signing_command(self):
1224
1280
        my_config = self._get_sample_config()
1225
 
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
1226
 
        self.assertEqual(False, my_config.signature_needed())
 
1281
        self.assertEqual("gnome-gpg",
 
1282
            self.applyDeprecated(
 
1283
                deprecated_in((2, 5, 0)), my_config.gpg_signing_command))
 
1284
        self.assertEqual(False, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1285
            my_config.signature_needed))
 
1286
 
 
1287
    def test_gpg_signing_key(self):
 
1288
        my_config = self._get_sample_config()
 
1289
        self.assertEqual("DD4D5088",
 
1290
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1291
                my_config.gpg_signing_key))
1227
1292
 
1228
1293
    def _get_empty_config(self):
1229
1294
        my_config = config.GlobalConfig()
1231
1296
 
1232
1297
    def test_gpg_signing_command_unset(self):
1233
1298
        my_config = self._get_empty_config()
1234
 
        self.assertEqual("gpg", my_config.gpg_signing_command())
 
1299
        self.assertEqual("gpg",
 
1300
            self.applyDeprecated(
 
1301
                deprecated_in((2, 5, 0)), my_config.gpg_signing_command))
1235
1302
 
1236
1303
    def test_get_user_option_default(self):
1237
1304
        my_config = self._get_empty_config()
1244
1311
 
1245
1312
    def test_post_commit_default(self):
1246
1313
        my_config = self._get_sample_config()
1247
 
        self.assertEqual(None, my_config.post_commit())
 
1314
        self.assertEqual(None,
 
1315
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1316
                                              my_config.post_commit))
1248
1317
 
1249
1318
    def test_configured_logformat(self):
1250
1319
        my_config = self._get_sample_config()
1252
1321
 
1253
1322
    def test_configured_acceptable_keys(self):
1254
1323
        my_config = self._get_sample_config()
1255
 
        self.assertEqual("amy", my_config.acceptable_keys())
 
1324
        self.assertEqual("amy",
 
1325
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1326
                my_config.acceptable_keys))
1256
1327
 
1257
1328
    def test_configured_validate_signatures_in_log(self):
1258
1329
        my_config = self._get_sample_config()
1296
1367
        self.log(repr(tools))
1297
1368
        self.assertEqual(
1298
1369
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
1299
 
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
 
1370
            u'sometool' : u'sometool {base} {this} {other} -o {result}',
 
1371
            u'newtool' : u'"newtool with spaces" {this_temp}'},
1300
1372
            tools)
1301
1373
 
1302
1374
    def test_get_merge_tools_empty(self):
1493
1565
        self.get_branch_config('http://www.example.com',
1494
1566
                                 global_config=sample_ignore_signatures)
1495
1567
        self.assertEqual(config.CHECK_ALWAYS,
1496
 
                         self.my_config.signature_checking())
 
1568
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1569
                             self.my_config.signature_checking))
1497
1570
        self.assertEqual(config.SIGN_NEVER,
1498
 
                         self.my_config.signing_policy())
 
1571
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1572
                             self.my_config.signing_policy))
1499
1573
 
1500
1574
    def test_signatures_never(self):
1501
1575
        self.get_branch_config('/a/c')
1502
1576
        self.assertEqual(config.CHECK_NEVER,
1503
 
                         self.my_config.signature_checking())
 
1577
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1578
                             self.my_config.signature_checking))
1504
1579
 
1505
1580
    def test_signatures_when_available(self):
1506
1581
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
1507
1582
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1508
 
                         self.my_config.signature_checking())
 
1583
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1584
                             self.my_config.signature_checking))
1509
1585
 
1510
1586
    def test_signatures_always(self):
1511
1587
        self.get_branch_config('/b')
1512
1588
        self.assertEqual(config.CHECK_ALWAYS,
1513
 
                         self.my_config.signature_checking())
 
1589
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1590
                         self.my_config.signature_checking))
1514
1591
 
1515
1592
    def test_gpg_signing_command(self):
1516
1593
        self.get_branch_config('/b')
1517
 
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
 
1594
        self.assertEqual("gnome-gpg",
 
1595
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1596
                self.my_config.gpg_signing_command))
1518
1597
 
1519
1598
    def test_gpg_signing_command_missing(self):
1520
1599
        self.get_branch_config('/a')
1521
 
        self.assertEqual("false", self.my_config.gpg_signing_command())
 
1600
        self.assertEqual("false",
 
1601
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1602
                self.my_config.gpg_signing_command))
 
1603
 
 
1604
    def test_gpg_signing_key(self):
 
1605
        self.get_branch_config('/b')
 
1606
        self.assertEqual("DD4D5088", self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1607
            self.my_config.gpg_signing_key))
 
1608
 
 
1609
    def test_gpg_signing_key_default(self):
 
1610
        self.get_branch_config('/a')
 
1611
        self.assertEqual("erik@bagfors.nu",
 
1612
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1613
                self.my_config.gpg_signing_key))
1522
1614
 
1523
1615
    def test_get_user_option_global(self):
1524
1616
        self.get_branch_config('/a')
1612
1704
    def test_post_commit_default(self):
1613
1705
        self.get_branch_config('/a/c')
1614
1706
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1615
 
                         self.my_config.post_commit())
 
1707
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1708
                                              self.my_config.post_commit))
1616
1709
 
1617
1710
    def get_branch_config(self, location, global_config=None,
1618
1711
                          location_config=None):
1708
1801
        return my_config
1709
1802
 
1710
1803
    def test_user_id(self):
1711
 
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
 
1804
        branch = FakeBranch()
1712
1805
        my_config = config.BranchConfig(branch)
1713
 
        self.assertEqual("Robert Collins <robertc@example.net>",
1714
 
                         my_config.username())
 
1806
        self.assertIsNot(None, my_config.username())
1715
1807
        my_config.branch.control_files.files['email'] = "John"
1716
1808
        my_config.set_user_option('email',
1717
1809
                                  "Robert Collins <robertc@example.org>")
1718
 
        self.assertEqual("John", my_config.username())
1719
 
        del my_config.branch.control_files.files['email']
1720
1810
        self.assertEqual("Robert Collins <robertc@example.org>",
1721
 
                         my_config.username())
1722
 
 
1723
 
    def test_not_set_in_branch(self):
1724
 
        my_config = self.get_branch_config(global_config=sample_config_text)
1725
 
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1726
 
                         my_config._get_user_id())
1727
 
        my_config.branch.control_files.files['email'] = "John"
1728
 
        self.assertEqual("John", my_config._get_user_id())
 
1811
                        my_config.username())
1729
1812
 
1730
1813
    def test_BZR_EMAIL_OVERRIDES(self):
1731
1814
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1737
1820
    def test_signatures_forced(self):
1738
1821
        my_config = self.get_branch_config(
1739
1822
            global_config=sample_always_signatures)
1740
 
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1741
 
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1742
 
        self.assertTrue(my_config.signature_needed())
 
1823
        self.assertEqual(config.CHECK_NEVER,
 
1824
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1825
                my_config.signature_checking))
 
1826
        self.assertEqual(config.SIGN_ALWAYS,
 
1827
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1828
                my_config.signing_policy))
 
1829
        self.assertTrue(self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1830
            my_config.signature_needed))
1743
1831
 
1744
1832
    def test_signatures_forced_branch(self):
1745
1833
        my_config = self.get_branch_config(
1746
1834
            global_config=sample_ignore_signatures,
1747
1835
            branch_data_config=sample_always_signatures)
1748
 
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1749
 
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1750
 
        self.assertTrue(my_config.signature_needed())
 
1836
        self.assertEqual(config.CHECK_NEVER,
 
1837
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1838
                my_config.signature_checking))
 
1839
        self.assertEqual(config.SIGN_ALWAYS,
 
1840
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1841
                my_config.signing_policy))
 
1842
        self.assertTrue(self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1843
            my_config.signature_needed))
1751
1844
 
1752
1845
    def test_gpg_signing_command(self):
1753
1846
        my_config = self.get_branch_config(
1754
1847
            global_config=sample_config_text,
1755
1848
            # branch data cannot set gpg_signing_command
1756
1849
            branch_data_config="gpg_signing_command=pgp")
1757
 
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
 
1850
        self.assertEqual('gnome-gpg',
 
1851
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1852
                my_config.gpg_signing_command))
1758
1853
 
1759
1854
    def test_get_user_option_global(self):
1760
1855
        my_config = self.get_branch_config(global_config=sample_config_text)
1767
1862
                                      location_config=sample_branches_text)
1768
1863
        self.assertEqual(my_config.branch.base, '/a/c')
1769
1864
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1770
 
                         my_config.post_commit())
 
1865
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1866
                                              my_config.post_commit))
1771
1867
        my_config.set_user_option('post_commit', 'rmtree_root')
1772
1868
        # post-commit is ignored when present in branch data
1773
1869
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1774
 
                         my_config.post_commit())
 
1870
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1871
                                              my_config.post_commit))
1775
1872
        my_config.set_user_option('post_commit', 'rmtree_root',
1776
1873
                                  store=config.STORE_LOCATION)
1777
 
        self.assertEqual('rmtree_root', my_config.post_commit())
 
1874
        self.assertEqual('rmtree_root',
 
1875
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1876
                                              my_config.post_commit))
1778
1877
 
1779
1878
    def test_config_precedence(self):
1780
1879
        # FIXME: eager test, luckily no persitent config file makes it fail
1914
2013
        conf = config.TransportConfig(t, 'foo.conf')
1915
2014
        self.assertRaises(errors.ParseConfigError, conf._get_configobj)
1916
2015
 
 
2016
    def test_load_permission_denied(self):
 
2017
        """Ensure we get an empty config file if the file is inaccessible."""
 
2018
        warnings = []
 
2019
        def warning(*args):
 
2020
            warnings.append(args[0] % args[1:])
 
2021
        self.overrideAttr(trace, 'warning', warning)
 
2022
 
 
2023
        class DenyingTransport(object):
 
2024
 
 
2025
            def __init__(self, base):
 
2026
                self.base = base
 
2027
 
 
2028
            def get_bytes(self, relpath):
 
2029
                raise errors.PermissionDenied(relpath, "")
 
2030
 
 
2031
        cfg = config.TransportConfig(
 
2032
            DenyingTransport("nonexisting://"), 'control.conf')
 
2033
        self.assertIs(None, cfg.get_option('non-existant', 'SECTION'))
 
2034
        self.assertEquals(
 
2035
            warnings,
 
2036
            [u'Permission denied while trying to open configuration file '
 
2037
             u'nonexisting:///control.conf.'])
 
2038
 
1917
2039
    def test_get_value(self):
1918
2040
        """Test that retreiving a value from a section is possible"""
1919
2041
        bzrdir_config = config.TransportConfig(self.get_transport('.'),
2199
2321
        opt = config.Option('foo', default='bar')
2200
2322
        self.assertEquals('bar', opt.get_default())
2201
2323
 
 
2324
    def test_callable_default_value(self):
 
2325
        def bar_as_unicode():
 
2326
            return u'bar'
 
2327
        opt = config.Option('foo', default=bar_as_unicode)
 
2328
        self.assertEquals('bar', opt.get_default())
 
2329
 
 
2330
    def test_default_value_from_env(self):
 
2331
        opt = config.Option('foo', default='bar', default_from_env=['FOO'])
 
2332
        self.overrideEnv('FOO', 'quux')
 
2333
        # Env variable provides a default taking over the option one
 
2334
        self.assertEquals('quux', opt.get_default())
 
2335
 
 
2336
    def test_first_default_value_from_env_wins(self):
 
2337
        opt = config.Option('foo', default='bar',
 
2338
                            default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
 
2339
        self.overrideEnv('FOO', 'foo')
 
2340
        self.overrideEnv('BAZ', 'baz')
 
2341
        # The first env var set wins
 
2342
        self.assertEquals('foo', opt.get_default())
 
2343
 
 
2344
    def test_not_supported_list_default_value(self):
 
2345
        self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
 
2346
 
 
2347
    def test_not_supported_object_default_value(self):
 
2348
        self.assertRaises(AssertionError, config.Option, 'foo',
 
2349
                          default=object())
 
2350
 
 
2351
    def test_not_supported_callable_default_value_not_unicode(self):
 
2352
        def bar_not_unicode():
 
2353
            return 'bar'
 
2354
        opt = config.Option('foo', default=bar_not_unicode)
 
2355
        self.assertRaises(AssertionError, opt.get_default)
 
2356
 
 
2357
 
 
2358
class TestOptionConverterMixin(object):
 
2359
 
 
2360
    def assertConverted(self, expected, opt, value):
 
2361
        self.assertEquals(expected, opt.convert_from_unicode(value))
 
2362
 
 
2363
    def assertWarns(self, opt, value):
 
2364
        warnings = []
 
2365
        def warning(*args):
 
2366
            warnings.append(args[0] % args[1:])
 
2367
        self.overrideAttr(trace, 'warning', warning)
 
2368
        self.assertEquals(None, opt.convert_from_unicode(value))
 
2369
        self.assertLength(1, warnings)
 
2370
        self.assertEquals(
 
2371
            'Value "%s" is not valid for "%s"' % (value, opt.name),
 
2372
            warnings[0])
 
2373
 
 
2374
    def assertErrors(self, opt, value):
 
2375
        self.assertRaises(errors.ConfigOptionValueError,
 
2376
                          opt.convert_from_unicode, value)
 
2377
 
 
2378
    def assertConvertInvalid(self, opt, invalid_value):
 
2379
        opt.invalid = None
 
2380
        self.assertEquals(None, opt.convert_from_unicode(invalid_value))
 
2381
        opt.invalid = 'warning'
 
2382
        self.assertWarns(opt, invalid_value)
 
2383
        opt.invalid = 'error'
 
2384
        self.assertErrors(opt, invalid_value)
 
2385
 
 
2386
 
 
2387
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
 
2388
 
 
2389
    def get_option(self):
 
2390
        return config.Option('foo', help='A boolean.',
 
2391
                             from_unicode=config.bool_from_store)
 
2392
 
 
2393
    def test_convert_invalid(self):
 
2394
        opt = self.get_option()
 
2395
        # A string that is not recognized as a boolean
 
2396
        self.assertConvertInvalid(opt, u'invalid-boolean')
 
2397
        # A list of strings is never recognized as a boolean
 
2398
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
 
2399
 
 
2400
    def test_convert_valid(self):
 
2401
        opt = self.get_option()
 
2402
        self.assertConverted(True, opt, u'True')
 
2403
        self.assertConverted(True, opt, u'1')
 
2404
        self.assertConverted(False, opt, u'False')
 
2405
 
 
2406
 
 
2407
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
 
2408
 
 
2409
    def get_option(self):
 
2410
        return config.Option('foo', help='An integer.',
 
2411
                             from_unicode=config.int_from_store)
 
2412
 
 
2413
    def test_convert_invalid(self):
 
2414
        opt = self.get_option()
 
2415
        # A string that is not recognized as an integer
 
2416
        self.assertConvertInvalid(opt, u'forty-two')
 
2417
        # A list of strings is never recognized as an integer
 
2418
        self.assertConvertInvalid(opt, [u'a', u'list'])
 
2419
 
 
2420
    def test_convert_valid(self):
 
2421
        opt = self.get_option()
 
2422
        self.assertConverted(16, opt, u'16')
 
2423
 
 
2424
 
 
2425
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
 
2426
 
 
2427
    def get_option(self):
 
2428
        return config.Option('foo', help='A list.',
 
2429
                             from_unicode=config.list_from_store)
 
2430
 
 
2431
    def test_convert_invalid(self):
 
2432
        # No string is invalid as all forms can be converted to a list
 
2433
        pass
 
2434
 
 
2435
    def test_convert_valid(self):
 
2436
        opt = self.get_option()
 
2437
        # An empty string is an empty list
 
2438
        self.assertConverted([], opt, '') # Using a bare str() just in case
 
2439
        self.assertConverted([], opt, u'')
 
2440
        # A boolean
 
2441
        self.assertConverted([u'True'], opt, u'True')
 
2442
        # An integer
 
2443
        self.assertConverted([u'42'], opt, u'42')
 
2444
        # A single string
 
2445
        self.assertConverted([u'bar'], opt, u'bar')
 
2446
        # A list remains a list (configObj will turn a string containing commas
 
2447
        # into a list, but that's not what we're testing here)
 
2448
        self.assertConverted([u'foo', u'1', u'True'],
 
2449
                             opt, [u'foo', u'1', u'True'])
 
2450
 
 
2451
 
 
2452
class TestOptionConverterMixin(object):
 
2453
 
 
2454
    def assertConverted(self, expected, opt, value):
 
2455
        self.assertEquals(expected, opt.convert_from_unicode(value))
 
2456
 
 
2457
    def assertWarns(self, opt, value):
 
2458
        warnings = []
 
2459
        def warning(*args):
 
2460
            warnings.append(args[0] % args[1:])
 
2461
        self.overrideAttr(trace, 'warning', warning)
 
2462
        self.assertEquals(None, opt.convert_from_unicode(value))
 
2463
        self.assertLength(1, warnings)
 
2464
        self.assertEquals(
 
2465
            'Value "%s" is not valid for "%s"' % (value, opt.name),
 
2466
            warnings[0])
 
2467
 
 
2468
    def assertErrors(self, opt, value):
 
2469
        self.assertRaises(errors.ConfigOptionValueError,
 
2470
                          opt.convert_from_unicode, value)
 
2471
 
 
2472
    def assertConvertInvalid(self, opt, invalid_value):
 
2473
        opt.invalid = None
 
2474
        self.assertEquals(None, opt.convert_from_unicode(invalid_value))
 
2475
        opt.invalid = 'warning'
 
2476
        self.assertWarns(opt, invalid_value)
 
2477
        opt.invalid = 'error'
 
2478
        self.assertErrors(opt, invalid_value)
 
2479
 
 
2480
 
 
2481
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
 
2482
 
 
2483
    def get_option(self):
 
2484
        return config.Option('foo', help='A boolean.',
 
2485
                             from_unicode=config.bool_from_store)
 
2486
 
 
2487
    def test_convert_invalid(self):
 
2488
        opt = self.get_option()
 
2489
        # A string that is not recognized as a boolean
 
2490
        self.assertConvertInvalid(opt, u'invalid-boolean')
 
2491
        # A list of strings is never recognized as a boolean
 
2492
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
 
2493
 
 
2494
    def test_convert_valid(self):
 
2495
        opt = self.get_option()
 
2496
        self.assertConverted(True, opt, u'True')
 
2497
        self.assertConverted(True, opt, u'1')
 
2498
        self.assertConverted(False, opt, u'False')
 
2499
 
 
2500
 
 
2501
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
 
2502
 
 
2503
    def get_option(self):
 
2504
        return config.Option('foo', help='An integer.',
 
2505
                             from_unicode=config.int_from_store)
 
2506
 
 
2507
    def test_convert_invalid(self):
 
2508
        opt = self.get_option()
 
2509
        # A string that is not recognized as an integer
 
2510
        self.assertConvertInvalid(opt, u'forty-two')
 
2511
        # A list of strings is never recognized as an integer
 
2512
        self.assertConvertInvalid(opt, [u'a', u'list'])
 
2513
 
 
2514
    def test_convert_valid(self):
 
2515
        opt = self.get_option()
 
2516
        self.assertConverted(16, opt, u'16')
 
2517
 
 
2518
 
 
2519
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
 
2520
 
 
2521
    def get_option(self):
 
2522
        return config.Option('foo', help='A list.',
 
2523
                             from_unicode=config.list_from_store)
 
2524
 
 
2525
    def test_convert_invalid(self):
 
2526
        opt = self.get_option()
 
2527
        # We don't even try to convert a list into a list, we only expect
 
2528
        # strings
 
2529
        self.assertConvertInvalid(opt, [1])
 
2530
        # No string is invalid as all forms can be converted to a list
 
2531
 
 
2532
    def test_convert_valid(self):
 
2533
        opt = self.get_option()
 
2534
        # An empty string is an empty list
 
2535
        self.assertConverted([], opt, '') # Using a bare str() just in case
 
2536
        self.assertConverted([], opt, u'')
 
2537
        # A boolean
 
2538
        self.assertConverted([u'True'], opt, u'True')
 
2539
        # An integer
 
2540
        self.assertConverted([u'42'], opt, u'42')
 
2541
        # A single string
 
2542
        self.assertConverted([u'bar'], opt, u'bar')
 
2543
 
2202
2544
 
2203
2545
class TestOptionRegistry(tests.TestCase):
2204
2546
 
2205
2547
    def setUp(self):
2206
2548
        super(TestOptionRegistry, self).setUp()
2207
2549
        # Always start with an empty registry
2208
 
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
2550
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2209
2551
        self.registry = config.option_registry
2210
2552
 
2211
2553
    def test_register(self):
2212
2554
        opt = config.Option('foo')
2213
 
        self.registry.register('foo', opt)
 
2555
        self.registry.register(opt)
2214
2556
        self.assertIs(opt, self.registry.get('foo'))
2215
2557
 
2216
 
    lazy_option = config.Option('lazy_foo')
2217
 
 
2218
 
    def test_register_lazy(self):
2219
 
        self.registry.register_lazy('foo', self.__module__,
2220
 
                                    'TestOptionRegistry.lazy_option')
2221
 
        self.assertIs(self.lazy_option, self.registry.get('foo'))
2222
 
 
2223
2558
    def test_registered_help(self):
2224
 
        opt = config.Option('foo')
2225
 
        self.registry.register('foo', opt, help='A simple option')
 
2559
        opt = config.Option('foo', help='A simple option')
 
2560
        self.registry.register(opt)
2226
2561
        self.assertEquals('A simple option', self.registry.get_help('foo'))
2227
2562
 
 
2563
    lazy_option = config.Option('lazy_foo', help='Lazy help')
 
2564
 
 
2565
    def test_register_lazy(self):
 
2566
        self.registry.register_lazy('lazy_foo', self.__module__,
 
2567
                                    'TestOptionRegistry.lazy_option')
 
2568
        self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
 
2569
 
 
2570
    def test_registered_lazy_help(self):
 
2571
        self.registry.register_lazy('lazy_foo', self.__module__,
 
2572
                                    'TestOptionRegistry.lazy_option')
 
2573
        self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
 
2574
 
2228
2575
 
2229
2576
class TestRegisteredOptions(tests.TestCase):
2230
2577
    """All registered options should verify some constraints."""
2244
2591
    def test_help_is_set(self):
2245
2592
        option_help = self.registry.get_help(self.option_name)
2246
2593
        self.assertNotEquals(None, option_help)
2247
 
        # Come on, think about the user, he really wants to know whst the
 
2594
        # Come on, think about the user, he really wants to know what the
2248
2595
        # option is about
 
2596
        self.assertIsNot(None, option_help)
2249
2597
        self.assertNotEquals('', option_help)
2250
2598
 
2251
2599
 
2273
2621
 
2274
2622
class TestMutableSection(tests.TestCase):
2275
2623
 
2276
 
    # FIXME: Parametrize so that all sections (including os.environ and the
2277
 
    # ones produced by Stores) run these tests -- vila 2011-04-01
 
2624
    scenarios = [('mutable',
 
2625
                  {'get_section':
 
2626
                       lambda opts: config.MutableSection('myID', opts)},),
 
2627
        ]
2278
2628
 
2279
2629
    def test_set(self):
2280
2630
        a_dict = dict(foo='bar')
2281
 
        section = config.MutableSection('myID', a_dict)
 
2631
        section = self.get_section(a_dict)
2282
2632
        section.set('foo', 'new_value')
2283
2633
        self.assertEquals('new_value', section.get('foo'))
2284
2634
        # The change appears in the shared section
2289
2639
 
2290
2640
    def test_set_preserve_original_once(self):
2291
2641
        a_dict = dict(foo='bar')
2292
 
        section = config.MutableSection('myID', a_dict)
 
2642
        section = self.get_section(a_dict)
2293
2643
        section.set('foo', 'first_value')
2294
2644
        section.set('foo', 'second_value')
2295
2645
        # We keep track of the original value
2298
2648
 
2299
2649
    def test_remove(self):
2300
2650
        a_dict = dict(foo='bar')
2301
 
        section = config.MutableSection('myID', a_dict)
 
2651
        section = self.get_section(a_dict)
2302
2652
        section.remove('foo')
2303
2653
        # We get None for unknown options via the default value
2304
2654
        self.assertEquals(None, section.get('foo'))
2311
2661
 
2312
2662
    def test_remove_new_option(self):
2313
2663
        a_dict = dict()
2314
 
        section = config.MutableSection('myID', a_dict)
 
2664
        section = self.get_section(a_dict)
2315
2665
        section.set('foo', 'bar')
2316
2666
        section.remove('foo')
2317
2667
        self.assertFalse('foo' in section.options)
2321
2671
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2322
2672
 
2323
2673
 
 
2674
class TestCommandLineStore(tests.TestCase):
 
2675
 
 
2676
    def setUp(self):
 
2677
        super(TestCommandLineStore, self).setUp()
 
2678
        self.store = config.CommandLineStore()
 
2679
 
 
2680
    def get_section(self):
 
2681
        """Get the unique section for the command line overrides."""
 
2682
        sections = list(self.store.get_sections())
 
2683
        self.assertLength(1, sections)
 
2684
        store, section = sections[0]
 
2685
        self.assertEquals(self.store, store)
 
2686
        return section
 
2687
 
 
2688
    def test_no_override(self):
 
2689
        self.store._from_cmdline([])
 
2690
        section = self.get_section()
 
2691
        self.assertLength(0, list(section.iter_option_names()))
 
2692
 
 
2693
    def test_simple_override(self):
 
2694
        self.store._from_cmdline(['a=b'])
 
2695
        section = self.get_section()
 
2696
        self.assertEqual('b', section.get('a'))
 
2697
 
 
2698
    def test_list_override(self):
 
2699
        self.store._from_cmdline(['l=1,2,3'])
 
2700
        val = self.get_section().get('l')
 
2701
        self.assertEqual('1,2,3', val)
 
2702
        # Reminder: lists should be registered as such explicitely, otherwise
 
2703
        # the conversion needs to be done afterwards.
 
2704
        self.assertEqual(['1', '2', '3'], config.list_from_store(val))
 
2705
 
 
2706
    def test_multiple_overrides(self):
 
2707
        self.store._from_cmdline(['a=b', 'x=y'])
 
2708
        section = self.get_section()
 
2709
        self.assertEquals('b', section.get('a'))
 
2710
        self.assertEquals('y', section.get('x'))
 
2711
 
 
2712
    def test_wrong_syntax(self):
 
2713
        self.assertRaises(errors.BzrCommandError,
 
2714
                          self.store._from_cmdline, ['a=b', 'c'])
 
2715
 
 
2716
 
2324
2717
class TestStore(tests.TestCaseWithTransport):
2325
2718
 
2326
 
    def assertSectionContent(self, expected, section):
 
2719
    def assertSectionContent(self, expected, (store, section)):
2327
2720
        """Assert that some options have the proper values in a section."""
2328
2721
        expected_name, expected_options = expected
2329
2722
        self.assertEquals(expected_name, section.id)
2337
2730
    scenarios = [(key, {'get_store': builder}) for key, builder
2338
2731
                 in config.test_store_builder_registry.iteritems()]
2339
2732
 
2340
 
    def setUp(self):
2341
 
        super(TestReadonlyStore, self).setUp()
2342
 
 
2343
2733
    def test_building_delays_load(self):
2344
2734
        store = self.get_store(self)
2345
2735
        self.assertEquals(False, store.is_loaded())
2372
2762
 
2373
2763
 
2374
2764
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2375
 
    """Simulate loading a config store without content of various encodings.
 
2765
    """Simulate loading a config store with content of various encodings.
2376
2766
 
2377
2767
    All files produced by bzr are in utf8 content.
2378
2768
 
2391
2781
        utf8_content = unicode_content.encode('utf8')
2392
2782
        # Store the raw content in the config file
2393
2783
        t.put_bytes('foo.conf', utf8_content)
2394
 
        store = config.IniFileStore(t, 'foo.conf')
 
2784
        store = config.TransportIniFileStore(t, 'foo.conf')
2395
2785
        store.load()
2396
2786
        stack = config.Stack([store.get_sections], store)
2397
2787
        self.assertEquals(unicode_user, stack.get('user'))
2400
2790
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2401
2791
        t = self.get_transport()
2402
2792
        t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2403
 
        store = config.IniFileStore(t, 'foo.conf')
 
2793
        store = config.TransportIniFileStore(t, 'foo.conf')
2404
2794
        self.assertRaises(errors.ConfigContentError, store.load)
2405
2795
 
2406
2796
    def test_load_erroneous_content(self):
2407
2797
        """Ensure we display a proper error on content that can't be parsed."""
2408
2798
        t = self.get_transport()
2409
2799
        t.put_bytes('foo.conf', '[open_section\n')
2410
 
        store = config.IniFileStore(t, 'foo.conf')
 
2800
        store = config.TransportIniFileStore(t, 'foo.conf')
2411
2801
        self.assertRaises(errors.ParseConfigError, store.load)
2412
2802
 
 
2803
    def test_load_permission_denied(self):
 
2804
        """Ensure we get warned when trying to load an inaccessible file."""
 
2805
        warnings = []
 
2806
        def warning(*args):
 
2807
            warnings.append(args[0] % args[1:])
 
2808
        self.overrideAttr(trace, 'warning', warning)
 
2809
 
 
2810
        t = self.get_transport()
 
2811
 
 
2812
        def get_bytes(relpath):
 
2813
            raise errors.PermissionDenied(relpath, "")
 
2814
        t.get_bytes = get_bytes
 
2815
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2816
        self.assertRaises(errors.PermissionDenied, store.load)
 
2817
        self.assertEquals(
 
2818
            warnings,
 
2819
            [u'Permission denied while trying to load configuration store %s.'
 
2820
             % store.external_url()])
 
2821
 
2413
2822
 
2414
2823
class TestIniConfigContent(tests.TestCaseWithTransport):
2415
 
    """Simulate loading a IniBasedConfig without content of various encodings.
 
2824
    """Simulate loading a IniBasedConfig with content of various encodings.
2416
2825
 
2417
2826
    All files produced by bzr are in utf8 content.
2418
2827
 
2563
2972
        self.assertEquals((store,), calls[0])
2564
2973
 
2565
2974
 
2566
 
class TestIniFileStore(TestStore):
 
2975
class TestTransportIniFileStore(TestStore):
2567
2976
 
2568
2977
    def test_loading_unknown_file_fails(self):
2569
 
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
 
2978
        store = config.TransportIniFileStore(self.get_transport(),
 
2979
            'I-do-not-exist')
2570
2980
        self.assertRaises(errors.NoSuchFile, store.load)
2571
2981
 
2572
2982
    def test_invalid_content(self):
2573
 
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
2983
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2574
2984
        self.assertEquals(False, store.is_loaded())
2575
2985
        exc = self.assertRaises(
2576
2986
            errors.ParseConfigError, store._load_from_string,
2584
2994
        # option names share the same name space...)
2585
2995
        # FIXME: This should be fixed by forbidding dicts as values ?
2586
2996
        # -- vila 2011-04-05
2587
 
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
2997
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2588
2998
        store._load_from_string('''
2589
2999
foo=bar
2590
3000
l=1,2
2600
3010
        sections = list(store.get_sections())
2601
3011
        self.assertLength(4, sections)
2602
3012
        # The default section has no name.
2603
 
        # List values are provided as lists
2604
 
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
 
3013
        # List values are provided as strings and need to be explicitly
 
3014
        # converted by specifying from_unicode=list_from_store at option
 
3015
        # registration
 
3016
        self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
2605
3017
                                  sections[0])
2606
3018
        self.assertSectionContent(
2607
3019
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2637
3049
 
2638
3050
    def setUp(self):
2639
3051
        super(TestConcurrentStoreUpdates, self).setUp()
2640
 
        self._content = 'one=1\ntwo=2\n'
2641
3052
        self.stack = self.get_stack(self)
2642
3053
        if not isinstance(self.stack, config._CompatibleStack):
2643
3054
            raise tests.TestNotApplicable(
2644
3055
                '%s is not meant to be compatible with the old config design'
2645
3056
                % (self.stack,))
2646
 
        self.stack.store._load_from_string(self._content)
 
3057
        self.stack.set('one', '1')
 
3058
        self.stack.set('two', '2')
2647
3059
        # Flush the store
2648
3060
        self.stack.store.save()
2649
3061
 
2753
3165
    # FIXME: It may be worth looking into removing the lock dir when it's not
2754
3166
    # needed anymore and look at possible fallouts for concurrent lockers. This
2755
3167
    # will matter if/when we use config files outside of bazaar directories
2756
 
    # (.bazaar or .bzr) -- vila 20110-04-11
 
3168
    # (.bazaar or .bzr) -- vila 20110-04-111
2757
3169
 
2758
3170
 
2759
3171
class TestSectionMatcher(TestStore):
2760
3172
 
2761
 
    scenarios = [('location', {'matcher': config.LocationMatcher})]
 
3173
    scenarios = [('location', {'matcher': config.LocationMatcher}),
 
3174
                 ('id', {'matcher': config.NameMatcher}),]
2762
3175
 
2763
 
    def get_store(self, file_name):
2764
 
        return config.IniFileStore(self.get_readonly_transport(), file_name)
 
3176
    def setUp(self):
 
3177
        super(TestSectionMatcher, self).setUp()
 
3178
        # Any simple store is good enough
 
3179
        self.get_store = config.test_store_builder_registry.get('configobj')
2765
3180
 
2766
3181
    def test_no_matches_for_empty_stores(self):
2767
 
        store = self.get_store('foo.conf')
 
3182
        store = self.get_store(self)
2768
3183
        store._load_from_string('')
2769
3184
        matcher = self.matcher(store, '/bar')
2770
3185
        self.assertEquals([], list(matcher.get_sections()))
2771
3186
 
2772
3187
    def test_build_doesnt_load_store(self):
2773
 
        store = self.get_store('foo.conf')
 
3188
        store = self.get_store(self)
2774
3189
        matcher = self.matcher(store, '/bar')
2775
3190
        self.assertFalse(store.is_loaded())
2776
3191
 
2800
3215
 
2801
3216
class TestLocationMatcher(TestStore):
2802
3217
 
2803
 
    def get_store(self, file_name):
2804
 
        return config.IniFileStore(self.get_readonly_transport(), file_name)
 
3218
    def setUp(self):
 
3219
        super(TestLocationMatcher, self).setUp()
 
3220
        # Any simple store is good enough
 
3221
        self.get_store = config.test_store_builder_registry.get('configobj')
 
3222
 
 
3223
    def test_unrelated_section_excluded(self):
 
3224
        store = self.get_store(self)
 
3225
        store._load_from_string('''
 
3226
[/foo]
 
3227
section=/foo
 
3228
[/foo/baz]
 
3229
section=/foo/baz
 
3230
[/foo/bar]
 
3231
section=/foo/bar
 
3232
[/foo/bar/baz]
 
3233
section=/foo/bar/baz
 
3234
[/quux/quux]
 
3235
section=/quux/quux
 
3236
''')
 
3237
        self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
 
3238
                           '/quux/quux'],
 
3239
                          [section.id for _, section in store.get_sections()])
 
3240
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
 
3241
        sections = [section for s, section in matcher.get_sections()]
 
3242
        self.assertEquals([3, 2],
 
3243
                          [section.length for section in sections])
 
3244
        self.assertEquals(['/foo/bar', '/foo'],
 
3245
                          [section.id for section in sections])
 
3246
        self.assertEquals(['quux', 'bar/quux'],
 
3247
                          [section.extra_path for section in sections])
2805
3248
 
2806
3249
    def test_more_specific_sections_first(self):
2807
 
        store = self.get_store('foo.conf')
 
3250
        store = self.get_store(self)
2808
3251
        store._load_from_string('''
2809
3252
[/foo]
2810
3253
section=/foo
2812
3255
section=/foo/bar
2813
3256
''')
2814
3257
        self.assertEquals(['/foo', '/foo/bar'],
2815
 
                          [section.id for section in store.get_sections()])
 
3258
                          [section.id for _, section in store.get_sections()])
2816
3259
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
2817
 
        sections = list(matcher.get_sections())
 
3260
        sections = [section for s, section in matcher.get_sections()]
2818
3261
        self.assertEquals([3, 2],
2819
3262
                          [section.length for section in sections])
2820
3263
        self.assertEquals(['/foo/bar', '/foo'],
2825
3268
    def test_appendpath_in_no_name_section(self):
2826
3269
        # It's a bit weird to allow appendpath in a no-name section, but
2827
3270
        # someone may found a use for it
2828
 
        store = self.get_store('foo.conf')
 
3271
        store = self.get_store(self)
2829
3272
        store._load_from_string('''
2830
3273
foo=bar
2831
3274
foo:policy = appendpath
2833
3276
        matcher = config.LocationMatcher(store, 'dir/subdir')
2834
3277
        sections = list(matcher.get_sections())
2835
3278
        self.assertLength(1, sections)
2836
 
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
 
3279
        self.assertEquals('bar/dir/subdir', sections[0][1].get('foo'))
2837
3280
 
2838
3281
    def test_file_urls_are_normalized(self):
2839
 
        store = self.get_store('foo.conf')
 
3282
        store = self.get_store(self)
2840
3283
        if sys.platform == 'win32':
2841
3284
            expected_url = 'file:///C:/dir/subdir'
2842
3285
            expected_location = 'C:/dir/subdir'
2847
3290
        self.assertEquals(expected_location, matcher.location)
2848
3291
 
2849
3292
 
 
3293
class TestNameMatcher(TestStore):
 
3294
 
 
3295
    def setUp(self):
 
3296
        super(TestNameMatcher, self).setUp()
 
3297
        self.matcher = config.NameMatcher
 
3298
        # Any simple store is good enough
 
3299
        self.get_store = config.test_store_builder_registry.get('configobj')
 
3300
 
 
3301
    def get_matching_sections(self, name):
 
3302
        store = self.get_store(self)
 
3303
        store._load_from_string('''
 
3304
[foo]
 
3305
option=foo
 
3306
[foo/baz]
 
3307
option=foo/baz
 
3308
[bar]
 
3309
option=bar
 
3310
''')
 
3311
        matcher = self.matcher(store, name)
 
3312
        return list(matcher.get_sections())
 
3313
 
 
3314
    def test_matching(self):
 
3315
        sections = self.get_matching_sections('foo')
 
3316
        self.assertLength(1, sections)
 
3317
        self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
 
3318
 
 
3319
    def test_not_matching(self):
 
3320
        sections = self.get_matching_sections('baz')
 
3321
        self.assertLength(0, sections)
 
3322
 
 
3323
 
2850
3324
class TestStackGet(tests.TestCase):
2851
3325
 
2852
3326
    # FIXME: This should be parametrized for all known Stack or dedicated
2853
3327
    # paramerized tests created to avoid bloating -- vila 2011-03-31
2854
3328
 
 
3329
    def overrideOptionRegistry(self):
 
3330
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3331
 
2855
3332
    def test_single_config_get(self):
2856
3333
        conf = dict(foo='bar')
2857
3334
        conf_stack = config.Stack([conf])
2860
3337
    def test_get_with_registered_default_value(self):
2861
3338
        conf_stack = config.Stack([dict()])
2862
3339
        opt = config.Option('foo', default='bar')
2863
 
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
3340
        self.overrideOptionRegistry()
2864
3341
        config.option_registry.register('foo', opt)
2865
3342
        self.assertEquals('bar', conf_stack.get('foo'))
2866
3343
 
2867
3344
    def test_get_without_registered_default_value(self):
2868
3345
        conf_stack = config.Stack([dict()])
2869
3346
        opt = config.Option('foo')
2870
 
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
3347
        self.overrideOptionRegistry()
2871
3348
        config.option_registry.register('foo', opt)
2872
3349
        self.assertEquals(None, conf_stack.get('foo'))
2873
3350
 
2874
3351
    def test_get_without_default_value_for_not_registered(self):
2875
3352
        conf_stack = config.Stack([dict()])
2876
3353
        opt = config.Option('foo')
2877
 
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
3354
        self.overrideOptionRegistry()
2878
3355
        self.assertEquals(None, conf_stack.get('foo'))
2879
3356
 
2880
3357
    def test_get_first_definition(self):
2914
3391
 
2915
3392
class TestStackGet(TestStackWithTransport):
2916
3393
 
 
3394
    def setUp(self):
 
3395
        super(TestStackGet, self).setUp()
 
3396
        self.conf = self.get_stack(self)
 
3397
 
2917
3398
    def test_get_for_empty_stack(self):
2918
 
        conf = self.get_stack(self)
2919
 
        self.assertEquals(None, conf.get('foo'))
 
3399
        self.assertEquals(None, self.conf.get('foo'))
2920
3400
 
2921
3401
    def test_get_hook(self):
2922
 
        conf = self.get_stack(self)
2923
 
        conf.store._load_from_string('foo=bar')
 
3402
        self.conf.set('foo', 'bar')
2924
3403
        calls = []
2925
3404
        def hook(*args):
2926
3405
            calls.append(args)
2927
3406
        config.ConfigHooks.install_named_hook('get', hook, None)
2928
3407
        self.assertLength(0, calls)
2929
 
        value = conf.get('foo')
 
3408
        value = self.conf.get('foo')
2930
3409
        self.assertEquals('bar', value)
2931
3410
        self.assertLength(1, calls)
2932
 
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
 
3411
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
 
3412
 
 
3413
 
 
3414
class TestStackGetWithConverter(tests.TestCaseWithTransport):
 
3415
 
 
3416
    def setUp(self):
 
3417
        super(TestStackGetWithConverter, self).setUp()
 
3418
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3419
        self.registry = config.option_registry
 
3420
        # We just want a simple stack with a simple store so we can inject
 
3421
        # whatever content the tests need without caring about what section
 
3422
        # names are valid for a given store/stack.
 
3423
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
3424
        self.conf = config.Stack([store.get_sections], store)
 
3425
 
 
3426
    def register_bool_option(self, name, default=None, default_from_env=None):
 
3427
        b = config.Option(name, help='A boolean.',
 
3428
                          default=default, default_from_env=default_from_env,
 
3429
                          from_unicode=config.bool_from_store)
 
3430
        self.registry.register(b)
 
3431
 
 
3432
    def test_get_default_bool_None(self):
 
3433
        self.register_bool_option('foo')
 
3434
        self.assertEquals(None, self.conf.get('foo'))
 
3435
 
 
3436
    def test_get_default_bool_True(self):
 
3437
        self.register_bool_option('foo', u'True')
 
3438
        self.assertEquals(True, self.conf.get('foo'))
 
3439
 
 
3440
    def test_get_default_bool_False(self):
 
3441
        self.register_bool_option('foo', False)
 
3442
        self.assertEquals(False, self.conf.get('foo'))
 
3443
 
 
3444
    def test_get_default_bool_False_as_string(self):
 
3445
        self.register_bool_option('foo', u'False')
 
3446
        self.assertEquals(False, self.conf.get('foo'))
 
3447
 
 
3448
    def test_get_default_bool_from_env_converted(self):
 
3449
        self.register_bool_option('foo', u'True', default_from_env=['FOO'])
 
3450
        self.overrideEnv('FOO', 'False')
 
3451
        self.assertEquals(False, self.conf.get('foo'))
 
3452
 
 
3453
    def test_get_default_bool_when_conversion_fails(self):
 
3454
        self.register_bool_option('foo', default='True')
 
3455
        self.conf.store._load_from_string('foo=invalid boolean')
 
3456
        self.assertEquals(True, self.conf.get('foo'))
 
3457
 
 
3458
    def register_integer_option(self, name,
 
3459
                                default=None, default_from_env=None):
 
3460
        i = config.Option(name, help='An integer.',
 
3461
                          default=default, default_from_env=default_from_env,
 
3462
                          from_unicode=config.int_from_store)
 
3463
        self.registry.register(i)
 
3464
 
 
3465
    def test_get_default_integer_None(self):
 
3466
        self.register_integer_option('foo')
 
3467
        self.assertEquals(None, self.conf.get('foo'))
 
3468
 
 
3469
    def test_get_default_integer(self):
 
3470
        self.register_integer_option('foo', 42)
 
3471
        self.assertEquals(42, self.conf.get('foo'))
 
3472
 
 
3473
    def test_get_default_integer_as_string(self):
 
3474
        self.register_integer_option('foo', u'42')
 
3475
        self.assertEquals(42, self.conf.get('foo'))
 
3476
 
 
3477
    def test_get_default_integer_from_env(self):
 
3478
        self.register_integer_option('foo', default_from_env=['FOO'])
 
3479
        self.overrideEnv('FOO', '18')
 
3480
        self.assertEquals(18, self.conf.get('foo'))
 
3481
 
 
3482
    def test_get_default_integer_when_conversion_fails(self):
 
3483
        self.register_integer_option('foo', default='12')
 
3484
        self.conf.store._load_from_string('foo=invalid integer')
 
3485
        self.assertEquals(12, self.conf.get('foo'))
 
3486
 
 
3487
    def register_list_option(self, name, default=None, default_from_env=None):
 
3488
        l = config.Option(name, help='A list.',
 
3489
                          default=default, default_from_env=default_from_env,
 
3490
                          from_unicode=config.list_from_store)
 
3491
        self.registry.register(l)
 
3492
 
 
3493
    def test_get_default_list_None(self):
 
3494
        self.register_list_option('foo')
 
3495
        self.assertEquals(None, self.conf.get('foo'))
 
3496
 
 
3497
    def test_get_default_list_empty(self):
 
3498
        self.register_list_option('foo', '')
 
3499
        self.assertEquals([], self.conf.get('foo'))
 
3500
 
 
3501
    def test_get_default_list_from_env(self):
 
3502
        self.register_list_option('foo', default_from_env=['FOO'])
 
3503
        self.overrideEnv('FOO', '')
 
3504
        self.assertEquals([], self.conf.get('foo'))
 
3505
 
 
3506
    def test_get_with_list_converter_no_item(self):
 
3507
        self.register_list_option('foo', None)
 
3508
        self.conf.store._load_from_string('foo=,')
 
3509
        self.assertEquals([], self.conf.get('foo'))
 
3510
 
 
3511
    def test_get_with_list_converter_many_items(self):
 
3512
        self.register_list_option('foo', None)
 
3513
        self.conf.store._load_from_string('foo=m,o,r,e')
 
3514
        self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
 
3515
 
 
3516
    def test_get_with_list_converter_embedded_spaces_many_items(self):
 
3517
        self.register_list_option('foo', None)
 
3518
        self.conf.store._load_from_string('foo=" bar", "baz "')
 
3519
        self.assertEquals([' bar', 'baz '], self.conf.get('foo'))
 
3520
 
 
3521
    def test_get_with_list_converter_stripped_spaces_many_items(self):
 
3522
        self.register_list_option('foo', None)
 
3523
        self.conf.store._load_from_string('foo= bar ,  baz ')
 
3524
        self.assertEquals(['bar', 'baz'], self.conf.get('foo'))
 
3525
 
 
3526
 
 
3527
class TestIterOptionRefs(tests.TestCase):
 
3528
    """iter_option_refs is a bit unusual, document some cases."""
 
3529
 
 
3530
    def assertRefs(self, expected, string):
 
3531
        self.assertEquals(expected, list(config.iter_option_refs(string)))
 
3532
 
 
3533
    def test_empty(self):
 
3534
        self.assertRefs([(False, '')], '')
 
3535
 
 
3536
    def test_no_refs(self):
 
3537
        self.assertRefs([(False, 'foo bar')], 'foo bar')
 
3538
 
 
3539
    def test_single_ref(self):
 
3540
        self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
 
3541
 
 
3542
    def test_broken_ref(self):
 
3543
        self.assertRefs([(False, '{foo')], '{foo')
 
3544
 
 
3545
    def test_embedded_ref(self):
 
3546
        self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
 
3547
                        '{{foo}}')
 
3548
 
 
3549
    def test_two_refs(self):
 
3550
        self.assertRefs([(False, ''), (True, '{foo}'),
 
3551
                         (False, ''), (True, '{bar}'),
 
3552
                         (False, ''),],
 
3553
                        '{foo}{bar}')
 
3554
 
 
3555
    def test_newline_in_refs_are_not_matched(self):
 
3556
        self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
 
3557
 
 
3558
 
 
3559
class TestStackExpandOptions(tests.TestCaseWithTransport):
 
3560
 
 
3561
    def setUp(self):
 
3562
        super(TestStackExpandOptions, self).setUp()
 
3563
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3564
        self.registry = config.option_registry
 
3565
        self.conf = build_branch_stack(self)
 
3566
 
 
3567
    def assertExpansion(self, expected, string, env=None):
 
3568
        self.assertEquals(expected, self.conf.expand_options(string, env))
 
3569
 
 
3570
    def test_no_expansion(self):
 
3571
        self.assertExpansion('foo', 'foo')
 
3572
 
 
3573
    def test_expand_default_value(self):
 
3574
        self.conf.store._load_from_string('bar=baz')
 
3575
        self.registry.register(config.Option('foo', default=u'{bar}'))
 
3576
        self.assertEquals('baz', self.conf.get('foo', expand=True))
 
3577
 
 
3578
    def test_expand_default_from_env(self):
 
3579
        self.conf.store._load_from_string('bar=baz')
 
3580
        self.registry.register(config.Option('foo', default_from_env=['FOO']))
 
3581
        self.overrideEnv('FOO', '{bar}')
 
3582
        self.assertEquals('baz', self.conf.get('foo', expand=True))
 
3583
 
 
3584
    def test_expand_default_on_failed_conversion(self):
 
3585
        self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
 
3586
        self.registry.register(
 
3587
            config.Option('foo', default=u'{bar}',
 
3588
                          from_unicode=config.int_from_store))
 
3589
        self.assertEquals(42, self.conf.get('foo', expand=True))
 
3590
 
 
3591
    def test_env_adding_options(self):
 
3592
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
 
3593
 
 
3594
    def test_env_overriding_options(self):
 
3595
        self.conf.store._load_from_string('foo=baz')
 
3596
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
 
3597
 
 
3598
    def test_simple_ref(self):
 
3599
        self.conf.store._load_from_string('foo=xxx')
 
3600
        self.assertExpansion('xxx', '{foo}')
 
3601
 
 
3602
    def test_unknown_ref(self):
 
3603
        self.assertRaises(errors.ExpandingUnknownOption,
 
3604
                          self.conf.expand_options, '{foo}')
 
3605
 
 
3606
    def test_indirect_ref(self):
 
3607
        self.conf.store._load_from_string('''
 
3608
foo=xxx
 
3609
bar={foo}
 
3610
''')
 
3611
        self.assertExpansion('xxx', '{bar}')
 
3612
 
 
3613
    def test_embedded_ref(self):
 
3614
        self.conf.store._load_from_string('''
 
3615
foo=xxx
 
3616
bar=foo
 
3617
''')
 
3618
        self.assertExpansion('xxx', '{{bar}}')
 
3619
 
 
3620
    def test_simple_loop(self):
 
3621
        self.conf.store._load_from_string('foo={foo}')
 
3622
        self.assertRaises(errors.OptionExpansionLoop,
 
3623
                          self.conf.expand_options, '{foo}')
 
3624
 
 
3625
    def test_indirect_loop(self):
 
3626
        self.conf.store._load_from_string('''
 
3627
foo={bar}
 
3628
bar={baz}
 
3629
baz={foo}''')
 
3630
        e = self.assertRaises(errors.OptionExpansionLoop,
 
3631
                              self.conf.expand_options, '{foo}')
 
3632
        self.assertEquals('foo->bar->baz', e.refs)
 
3633
        self.assertEquals('{foo}', e.string)
 
3634
 
 
3635
    def test_list(self):
 
3636
        self.conf.store._load_from_string('''
 
3637
foo=start
 
3638
bar=middle
 
3639
baz=end
 
3640
list={foo},{bar},{baz}
 
3641
''')
 
3642
        self.registry.register(
 
3643
            config.Option('list', from_unicode=config.list_from_store))
 
3644
        self.assertEquals(['start', 'middle', 'end'],
 
3645
                           self.conf.get('list', expand=True))
 
3646
 
 
3647
    def test_cascading_list(self):
 
3648
        self.conf.store._load_from_string('''
 
3649
foo=start,{bar}
 
3650
bar=middle,{baz}
 
3651
baz=end
 
3652
list={foo}
 
3653
''')
 
3654
        self.registry.register(
 
3655
            config.Option('list', from_unicode=config.list_from_store))
 
3656
        self.assertEquals(['start', 'middle', 'end'],
 
3657
                           self.conf.get('list', expand=True))
 
3658
 
 
3659
    def test_pathologically_hidden_list(self):
 
3660
        self.conf.store._load_from_string('''
 
3661
foo=bin
 
3662
bar=go
 
3663
start={foo
 
3664
middle=},{
 
3665
end=bar}
 
3666
hidden={start}{middle}{end}
 
3667
''')
 
3668
        # What matters is what the registration says, the conversion happens
 
3669
        # only after all expansions have been performed
 
3670
        self.registry.register(
 
3671
            config.Option('hidden', from_unicode=config.list_from_store))
 
3672
        self.assertEquals(['bin', 'go'],
 
3673
                          self.conf.get('hidden', expand=True))
 
3674
 
 
3675
 
 
3676
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
 
3677
 
 
3678
    def setUp(self):
 
3679
        super(TestStackCrossSectionsExpand, self).setUp()
 
3680
 
 
3681
    def get_config(self, location, string):
 
3682
        if string is None:
 
3683
            string = ''
 
3684
        # Since we don't save the config we won't strictly require to inherit
 
3685
        # from TestCaseInTempDir, but an error occurs so quickly...
 
3686
        c = config.LocationStack(location)
 
3687
        c.store._load_from_string(string)
 
3688
        return c
 
3689
 
 
3690
    def test_dont_cross_unrelated_section(self):
 
3691
        c = self.get_config('/another/branch/path','''
 
3692
[/one/branch/path]
 
3693
foo = hello
 
3694
bar = {foo}/2
 
3695
 
 
3696
[/another/branch/path]
 
3697
bar = {foo}/2
 
3698
''')
 
3699
        self.assertRaises(errors.ExpandingUnknownOption,
 
3700
                          c.get, 'bar', expand=True)
 
3701
 
 
3702
    def test_cross_related_sections(self):
 
3703
        c = self.get_config('/project/branch/path','''
 
3704
[/project]
 
3705
foo = qu
 
3706
 
 
3707
[/project/branch/path]
 
3708
bar = {foo}ux
 
3709
''')
 
3710
        self.assertEquals('quux', c.get('bar', expand=True))
 
3711
 
 
3712
 
 
3713
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
 
3714
 
 
3715
    def test_cross_global_locations(self):
 
3716
        l_store = config.LocationStore()
 
3717
        l_store._load_from_string('''
 
3718
[/branch]
 
3719
lfoo = loc-foo
 
3720
lbar = {gbar}
 
3721
''')
 
3722
        l_store.save()
 
3723
        g_store = config.GlobalStore()
 
3724
        g_store._load_from_string('''
 
3725
[DEFAULT]
 
3726
gfoo = {lfoo}
 
3727
gbar = glob-bar
 
3728
''')
 
3729
        g_store.save()
 
3730
        stack = config.LocationStack('/branch')
 
3731
        self.assertEquals('glob-bar', stack.get('lbar', expand=True))
 
3732
        self.assertEquals('loc-foo', stack.get('gfoo', expand=True))
 
3733
 
 
3734
 
 
3735
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
 
3736
 
 
3737
    def test_expand_locals_empty(self):
 
3738
        l_store = config.LocationStore()
 
3739
        l_store._load_from_string('''
 
3740
[/home/user/project]
 
3741
base = {basename}
 
3742
rel = {relpath}
 
3743
''')
 
3744
        l_store.save()
 
3745
        stack = config.LocationStack('/home/user/project/')
 
3746
        self.assertEquals('', stack.get('base', expand=True))
 
3747
        self.assertEquals('', stack.get('rel', expand=True))
 
3748
 
 
3749
    def test_expand_basename_locally(self):
 
3750
        l_store = config.LocationStore()
 
3751
        l_store._load_from_string('''
 
3752
[/home/user/project]
 
3753
bfoo = {basename}
 
3754
''')
 
3755
        l_store.save()
 
3756
        stack = config.LocationStack('/home/user/project/branch')
 
3757
        self.assertEquals('branch', stack.get('bfoo', expand=True))
 
3758
 
 
3759
    def test_expand_basename_locally_longer_path(self):
 
3760
        l_store = config.LocationStore()
 
3761
        l_store._load_from_string('''
 
3762
[/home/user]
 
3763
bfoo = {basename}
 
3764
''')
 
3765
        l_store.save()
 
3766
        stack = config.LocationStack('/home/user/project/dir/branch')
 
3767
        self.assertEquals('branch', stack.get('bfoo', expand=True))
 
3768
 
 
3769
    def test_expand_relpath_locally(self):
 
3770
        l_store = config.LocationStore()
 
3771
        l_store._load_from_string('''
 
3772
[/home/user/project]
 
3773
lfoo = loc-foo/{relpath}
 
3774
''')
 
3775
        l_store.save()
 
3776
        stack = config.LocationStack('/home/user/project/branch')
 
3777
        self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
 
3778
 
 
3779
    def test_expand_relpath_unknonw_in_global(self):
 
3780
        g_store = config.GlobalStore()
 
3781
        g_store._load_from_string('''
 
3782
[DEFAULT]
 
3783
gfoo = {relpath}
 
3784
''')
 
3785
        g_store.save()
 
3786
        stack = config.LocationStack('/home/user/project/branch')
 
3787
        self.assertRaises(errors.ExpandingUnknownOption,
 
3788
                          stack.get, 'gfoo', expand=True)
 
3789
 
 
3790
    def test_expand_local_option_locally(self):
 
3791
        l_store = config.LocationStore()
 
3792
        l_store._load_from_string('''
 
3793
[/home/user/project]
 
3794
lfoo = loc-foo/{relpath}
 
3795
lbar = {gbar}
 
3796
''')
 
3797
        l_store.save()
 
3798
        g_store = config.GlobalStore()
 
3799
        g_store._load_from_string('''
 
3800
[DEFAULT]
 
3801
gfoo = {lfoo}
 
3802
gbar = glob-bar
 
3803
''')
 
3804
        g_store.save()
 
3805
        stack = config.LocationStack('/home/user/project/branch')
 
3806
        self.assertEquals('glob-bar', stack.get('lbar', expand=True))
 
3807
        self.assertEquals('loc-foo/branch', stack.get('gfoo', expand=True))
 
3808
 
 
3809
    def test_locals_dont_leak(self):
 
3810
        """Make sure we chose the right local in presence of several sections.
 
3811
        """
 
3812
        l_store = config.LocationStore()
 
3813
        l_store._load_from_string('''
 
3814
[/home/user]
 
3815
lfoo = loc-foo/{relpath}
 
3816
[/home/user/project]
 
3817
lfoo = loc-foo/{relpath}
 
3818
''')
 
3819
        l_store.save()
 
3820
        stack = config.LocationStack('/home/user/project/branch')
 
3821
        self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
 
3822
        stack = config.LocationStack('/home/user/bar/baz')
 
3823
        self.assertEquals('loc-foo/bar/baz', stack.get('lfoo', expand=True))
 
3824
 
2933
3825
 
2934
3826
 
2935
3827
class TestStackSet(TestStackWithTransport):
2936
3828
 
2937
3829
    def test_simple_set(self):
2938
3830
        conf = self.get_stack(self)
2939
 
        conf.store._load_from_string('foo=bar')
2940
 
        self.assertEquals('bar', conf.get('foo'))
 
3831
        self.assertEquals(None, conf.get('foo'))
2941
3832
        conf.set('foo', 'baz')
2942
3833
        # Did we get it back ?
2943
3834
        self.assertEquals('baz', conf.get('foo'))
2963
3854
 
2964
3855
    def test_remove_existing(self):
2965
3856
        conf = self.get_stack(self)
2966
 
        conf.store._load_from_string('foo=bar')
 
3857
        conf.set('foo', 'bar')
2967
3858
        self.assertEquals('bar', conf.get('foo'))
2968
3859
        conf.remove('foo')
2969
3860
        # Did we get it back ?
2980
3871
        config.ConfigHooks.install_named_hook('remove', hook, None)
2981
3872
        self.assertLength(0, calls)
2982
3873
        conf = self.get_stack(self)
2983
 
        conf.store._load_from_string('foo=bar')
 
3874
        conf.set('foo', 'bar')
2984
3875
        conf.remove('foo')
2985
3876
        self.assertLength(1, calls)
2986
3877
        self.assertEquals((conf, 'foo'), calls[0])
3161
4052
        conf = config.AuthenticationConfig(_file=StringIO(
3162
4053
                'foo = bar\xff'))
3163
4054
        self.assertRaises(errors.ConfigContentError, conf._get_config)
3164
 
        
 
4055
 
3165
4056
    def test_missing_auth_section_header(self):
3166
4057
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
3167
4058
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3648
4539
 
3649
4540
    def test_auto_user_id(self):
3650
4541
        """Automatic inference of user name.
3651
 
        
 
4542
 
3652
4543
        This is a bit hard to test in an isolated way, because it depends on
3653
4544
        system functions that go direct to /etc or perhaps somewhere else.
3654
4545
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
3664
4555
        else:
3665
4556
            self.assertEquals((None, None), (realname, address))
3666
4557
 
 
4558
 
 
4559
class EmailOptionTests(tests.TestCase):
 
4560
 
 
4561
    def test_default_email_uses_BZR_EMAIL(self):
 
4562
        # BZR_EMAIL takes precedence over EMAIL
 
4563
        self.overrideEnv('BZR_EMAIL', 'jelmer@samba.org')
 
4564
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
 
4565
        self.assertEquals('jelmer@samba.org', config.default_email())
 
4566
 
 
4567
    def test_default_email_uses_EMAIL(self):
 
4568
        self.overrideEnv('BZR_EMAIL', None)
 
4569
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
 
4570
        self.assertEquals('jelmer@apache.org', config.default_email())
 
4571
 
 
4572
    def test_BZR_EMAIL_overrides(self):
 
4573
        self.overrideEnv('BZR_EMAIL', 'jelmer@apache.org')
 
4574
        self.assertEquals('jelmer@apache.org',
 
4575
            config.email_from_store('jelmer@debian.org'))
 
4576
        self.overrideEnv('BZR_EMAIL', None)
 
4577
        self.overrideEnv('EMAIL', 'jelmer@samba.org')
 
4578
        self.assertEquals('jelmer@debian.org',
 
4579
            config.email_from_store('jelmer@debian.org'))