~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Jelmer Vernooij
  • Date: 2011-10-04 22:20:49 UTC
  • mto: This revision was merged to the branch mainline in revision 6190.
  • Revision ID: jelmer@samba.org-20111004222049-d9glniyleu0pppzd
Add a load_plugin_translations method.

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 (
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/*]
817
836
        self.assertEquals(['{foo', '}', '{', 'bar}'],
818
837
                          conf.get_user_option('hidden', expand=True))
819
838
 
 
839
 
820
840
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
821
841
 
822
842
    def get_config(self, location, string=None):
1033
1053
        # automatically cast to list
1034
1054
        self.assertEqual(['x'], get_list('one_item'))
1035
1055
 
 
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))
1036
1076
 
1037
1077
class TestSupressWarning(TestIniConfig):
1038
1078
 
1225
1265
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
1226
1266
        self.assertEqual(False, my_config.signature_needed())
1227
1267
 
 
1268
    def test_gpg_signing_key(self):
 
1269
        my_config = self._get_sample_config()
 
1270
        self.assertEqual("DD4D5088", my_config.gpg_signing_key())
 
1271
 
1228
1272
    def _get_empty_config(self):
1229
1273
        my_config = config.GlobalConfig()
1230
1274
        return my_config
1296
1340
        self.log(repr(tools))
1297
1341
        self.assertEqual(
1298
1342
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
1299
 
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
 
1343
            u'sometool' : u'sometool {base} {this} {other} -o {result}',
 
1344
            u'newtool' : u'"newtool with spaces" {this_temp}'},
1300
1345
            tools)
1301
1346
 
1302
1347
    def test_get_merge_tools_empty(self):
1520
1565
        self.get_branch_config('/a')
1521
1566
        self.assertEqual("false", self.my_config.gpg_signing_command())
1522
1567
 
 
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
 
1523
1576
    def test_get_user_option_global(self):
1524
1577
        self.get_branch_config('/a')
1525
1578
        self.assertEqual('something',
1914
1967
        conf = config.TransportConfig(t, 'foo.conf')
1915
1968
        self.assertRaises(errors.ParseConfigError, conf._get_configobj)
1916
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
 
1917
1993
    def test_get_value(self):
1918
1994
        """Test that retreiving a value from a section is possible"""
1919
1995
        bzrdir_config = config.TransportConfig(self.get_transport('.'),
2199
2275
        opt = config.Option('foo', default='bar')
2200
2276
        self.assertEquals('bar', opt.get_default())
2201
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
 
2202
2485
 
2203
2486
class TestOptionRegistry(tests.TestCase):
2204
2487
 
2205
2488
    def setUp(self):
2206
2489
        super(TestOptionRegistry, self).setUp()
2207
2490
        # Always start with an empty registry
2208
 
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
2491
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2209
2492
        self.registry = config.option_registry
2210
2493
 
2211
2494
    def test_register(self):
2212
2495
        opt = config.Option('foo')
2213
 
        self.registry.register('foo', opt)
 
2496
        self.registry.register(opt)
2214
2497
        self.assertIs(opt, self.registry.get('foo'))
2215
2498
 
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
2499
    def test_registered_help(self):
2224
 
        opt = config.Option('foo')
2225
 
        self.registry.register('foo', opt, help='A simple option')
 
2500
        opt = config.Option('foo', help='A simple option')
 
2501
        self.registry.register(opt)
2226
2502
        self.assertEquals('A simple option', self.registry.get_help('foo'))
2227
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
 
2228
2516
 
2229
2517
class TestRegisteredOptions(tests.TestCase):
2230
2518
    """All registered options should verify some constraints."""
2244
2532
    def test_help_is_set(self):
2245
2533
        option_help = self.registry.get_help(self.option_name)
2246
2534
        self.assertNotEquals(None, option_help)
2247
 
        # Come on, think about the user, he really wants to know whst the
 
2535
        # Come on, think about the user, he really wants to know what the
2248
2536
        # option is about
 
2537
        self.assertIsNot(None, option_help)
2249
2538
        self.assertNotEquals('', option_help)
2250
2539
 
2251
2540
 
2273
2562
 
2274
2563
class TestMutableSection(tests.TestCase):
2275
2564
 
2276
 
    # FIXME: Parametrize so that all sections (including os.environ and the
2277
 
    # ones produced by Stores) run these tests -- vila 2011-04-01
 
2565
    scenarios = [('mutable',
 
2566
                  {'get_section':
 
2567
                       lambda opts: config.MutableSection('myID', opts)},),
 
2568
                 ('cmdline',
 
2569
                  {'get_section':
 
2570
                       lambda opts: config.CommandLineSection(opts)},),
 
2571
        ]
2278
2572
 
2279
2573
    def test_set(self):
2280
2574
        a_dict = dict(foo='bar')
2281
 
        section = config.MutableSection('myID', a_dict)
 
2575
        section = self.get_section(a_dict)
2282
2576
        section.set('foo', 'new_value')
2283
2577
        self.assertEquals('new_value', section.get('foo'))
2284
2578
        # The change appears in the shared section
2289
2583
 
2290
2584
    def test_set_preserve_original_once(self):
2291
2585
        a_dict = dict(foo='bar')
2292
 
        section = config.MutableSection('myID', a_dict)
 
2586
        section = self.get_section(a_dict)
2293
2587
        section.set('foo', 'first_value')
2294
2588
        section.set('foo', 'second_value')
2295
2589
        # We keep track of the original value
2298
2592
 
2299
2593
    def test_remove(self):
2300
2594
        a_dict = dict(foo='bar')
2301
 
        section = config.MutableSection('myID', a_dict)
 
2595
        section = self.get_section(a_dict)
2302
2596
        section.remove('foo')
2303
2597
        # We get None for unknown options via the default value
2304
2598
        self.assertEquals(None, section.get('foo'))
2311
2605
 
2312
2606
    def test_remove_new_option(self):
2313
2607
        a_dict = dict()
2314
 
        section = config.MutableSection('myID', a_dict)
 
2608
        section = self.get_section(a_dict)
2315
2609
        section.set('foo', 'bar')
2316
2610
        section.remove('foo')
2317
2611
        self.assertFalse('foo' in section.options)
2321
2615
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2322
2616
 
2323
2617
 
 
2618
class TestCommandLineSection(tests.TestCase):
 
2619
 
 
2620
    def setUp(self):
 
2621
        super(TestCommandLineSection, self).setUp()
 
2622
        self.section = config.CommandLineSection()
 
2623
 
 
2624
    def test_no_override(self):
 
2625
        self.section._from_cmdline([])
 
2626
        # FIXME: we want some iterator over all options, failing that, we peek
 
2627
        # under the cover -- vila 2011-09026
 
2628
        self.assertLength(0, self.section.options)
 
2629
 
 
2630
    def test_simple_override(self):
 
2631
        self.section._from_cmdline(['a=b'])
 
2632
        self.assertEqual('b', self.section.get('a'))
 
2633
 
 
2634
    def test_list_override(self):
 
2635
        self.section._from_cmdline(['l=1,2,3'])
 
2636
        val = self.section.get('l')
 
2637
        self.assertEqual('1,2,3', val)
 
2638
        # Reminder: lists should registered as such explicitely, otherwise the
 
2639
        # conversion needs to be done afterwards.
 
2640
        self.assertEqual(['1', '2', '3'], config.list_from_store(val))
 
2641
 
 
2642
    def test_multiple_overrides(self):
 
2643
        self.section._from_cmdline(['a=b', 'x=y'])
 
2644
        self.assertEquals('b', self.section.get('a'))
 
2645
        self.assertEquals('y', self.section.get('x'))
 
2646
 
 
2647
    def test_wrong_syntax(self):
 
2648
        self.assertRaises(errors.BzrCommandError,
 
2649
                          self.section._from_cmdline, ['a=b', 'c'])
 
2650
 
 
2651
 
2324
2652
class TestStore(tests.TestCaseWithTransport):
2325
2653
 
2326
2654
    def assertSectionContent(self, expected, section):
2337
2665
    scenarios = [(key, {'get_store': builder}) for key, builder
2338
2666
                 in config.test_store_builder_registry.iteritems()]
2339
2667
 
2340
 
    def setUp(self):
2341
 
        super(TestReadonlyStore, self).setUp()
2342
 
 
2343
2668
    def test_building_delays_load(self):
2344
2669
        store = self.get_store(self)
2345
2670
        self.assertEquals(False, store.is_loaded())
2372
2697
 
2373
2698
 
2374
2699
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2375
 
    """Simulate loading a config store without content of various encodings.
 
2700
    """Simulate loading a config store with content of various encodings.
2376
2701
 
2377
2702
    All files produced by bzr are in utf8 content.
2378
2703
 
2410
2735
        store = config.IniFileStore(t, 'foo.conf')
2411
2736
        self.assertRaises(errors.ParseConfigError, store.load)
2412
2737
 
 
2738
    def test_load_permission_denied(self):
 
2739
        """Ensure we get warned when trying to load an inaccessible file."""
 
2740
        warnings = []
 
2741
        def warning(*args):
 
2742
            warnings.append(args[0] % args[1:])
 
2743
        self.overrideAttr(trace, 'warning', warning)
 
2744
 
 
2745
        t = self.get_transport()
 
2746
 
 
2747
        def get_bytes(relpath):
 
2748
            raise errors.PermissionDenied(relpath, "")
 
2749
        t.get_bytes = get_bytes
 
2750
        store = config.IniFileStore(t, 'foo.conf')
 
2751
        self.assertRaises(errors.PermissionDenied, store.load)
 
2752
        self.assertEquals(
 
2753
            warnings,
 
2754
            [u'Permission denied while trying to load configuration store %s.'
 
2755
             % store.external_url()])
 
2756
 
2413
2757
 
2414
2758
class TestIniConfigContent(tests.TestCaseWithTransport):
2415
 
    """Simulate loading a IniBasedConfig without content of various encodings.
 
2759
    """Simulate loading a IniBasedConfig with content of various encodings.
2416
2760
 
2417
2761
    All files produced by bzr are in utf8 content.
2418
2762
 
2600
2944
        sections = list(store.get_sections())
2601
2945
        self.assertLength(4, sections)
2602
2946
        # The default section has no name.
2603
 
        # List values are provided as lists
2604
 
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
 
2947
        # List values are provided as strings and need to be explicitly
 
2948
        # converted by specifying from_unicode=list_from_store at option
 
2949
        # registration
 
2950
        self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
2605
2951
                                  sections[0])
2606
2952
        self.assertSectionContent(
2607
2953
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2753
3099
    # FIXME: It may be worth looking into removing the lock dir when it's not
2754
3100
    # needed anymore and look at possible fallouts for concurrent lockers. This
2755
3101
    # will matter if/when we use config files outside of bazaar directories
2756
 
    # (.bazaar or .bzr) -- vila 20110-04-11
 
3102
    # (.bazaar or .bzr) -- vila 20110-04-111
2757
3103
 
2758
3104
 
2759
3105
class TestSectionMatcher(TestStore):
2760
3106
 
2761
 
    scenarios = [('location', {'matcher': config.LocationMatcher})]
 
3107
    scenarios = [('location', {'matcher': config.LocationMatcher}),
 
3108
                 ('id', {'matcher': config.NameMatcher}),]
2762
3109
 
2763
3110
    def get_store(self, file_name):
2764
3111
        return config.IniFileStore(self.get_readonly_transport(), file_name)
2803
3150
    def get_store(self, file_name):
2804
3151
        return config.IniFileStore(self.get_readonly_transport(), file_name)
2805
3152
 
 
3153
    def test_unrelated_section_excluded(self):
 
3154
        store = self.get_store('foo.conf')
 
3155
        store._load_from_string('''
 
3156
[/foo]
 
3157
section=/foo
 
3158
[/foo/baz]
 
3159
section=/foo/baz
 
3160
[/foo/bar]
 
3161
section=/foo/bar
 
3162
[/foo/bar/baz]
 
3163
section=/foo/bar/baz
 
3164
[/quux/quux]
 
3165
section=/quux/quux
 
3166
''')
 
3167
        self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
 
3168
                           '/quux/quux'],
 
3169
                          [section.id for section in store.get_sections()])
 
3170
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
 
3171
        sections = list(matcher.get_sections())
 
3172
        self.assertEquals([3, 2],
 
3173
                          [section.length for section in sections])
 
3174
        self.assertEquals(['/foo/bar', '/foo'],
 
3175
                          [section.id for section in sections])
 
3176
        self.assertEquals(['quux', 'bar/quux'],
 
3177
                          [section.extra_path for section in sections])
 
3178
 
2806
3179
    def test_more_specific_sections_first(self):
2807
3180
        store = self.get_store('foo.conf')
2808
3181
        store._load_from_string('''
2847
3220
        self.assertEquals(expected_location, matcher.location)
2848
3221
 
2849
3222
 
 
3223
class TestNameMatcher(TestStore):
 
3224
 
 
3225
    def setUp(self):
 
3226
        super(TestNameMatcher, self).setUp()
 
3227
        self.store = config.IniFileStore(self.get_readonly_transport(),
 
3228
                                         'foo.conf')
 
3229
        self.store._load_from_string('''
 
3230
[foo]
 
3231
option=foo
 
3232
[foo/baz]
 
3233
option=foo/baz
 
3234
[bar]
 
3235
option=bar
 
3236
''')
 
3237
 
 
3238
    def get_matching_sections(self, name):
 
3239
        matcher = config.NameMatcher(self.store, name)
 
3240
        return list(matcher.get_sections())
 
3241
 
 
3242
    def test_matching(self):
 
3243
        sections = self.get_matching_sections('foo')
 
3244
        self.assertLength(1, sections)
 
3245
        self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
 
3246
 
 
3247
    def test_not_matching(self):
 
3248
        sections = self.get_matching_sections('baz')
 
3249
        self.assertLength(0, sections)
 
3250
 
 
3251
 
2850
3252
class TestStackGet(tests.TestCase):
2851
3253
 
2852
3254
    # FIXME: This should be parametrized for all known Stack or dedicated
2853
3255
    # paramerized tests created to avoid bloating -- vila 2011-03-31
2854
3256
 
 
3257
    def overrideOptionRegistry(self):
 
3258
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3259
 
2855
3260
    def test_single_config_get(self):
2856
3261
        conf = dict(foo='bar')
2857
3262
        conf_stack = config.Stack([conf])
2860
3265
    def test_get_with_registered_default_value(self):
2861
3266
        conf_stack = config.Stack([dict()])
2862
3267
        opt = config.Option('foo', default='bar')
2863
 
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
3268
        self.overrideOptionRegistry()
2864
3269
        config.option_registry.register('foo', opt)
2865
3270
        self.assertEquals('bar', conf_stack.get('foo'))
2866
3271
 
2867
3272
    def test_get_without_registered_default_value(self):
2868
3273
        conf_stack = config.Stack([dict()])
2869
3274
        opt = config.Option('foo')
2870
 
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
3275
        self.overrideOptionRegistry()
2871
3276
        config.option_registry.register('foo', opt)
2872
3277
        self.assertEquals(None, conf_stack.get('foo'))
2873
3278
 
2874
3279
    def test_get_without_default_value_for_not_registered(self):
2875
3280
        conf_stack = config.Stack([dict()])
2876
3281
        opt = config.Option('foo')
2877
 
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
3282
        self.overrideOptionRegistry()
2878
3283
        self.assertEquals(None, conf_stack.get('foo'))
2879
3284
 
2880
3285
    def test_get_first_definition(self):
2914
3319
 
2915
3320
class TestStackGet(TestStackWithTransport):
2916
3321
 
 
3322
    def setUp(self):
 
3323
        super(TestStackGet, self).setUp()
 
3324
        self.conf = self.get_stack(self)
 
3325
 
2917
3326
    def test_get_for_empty_stack(self):
2918
 
        conf = self.get_stack(self)
2919
 
        self.assertEquals(None, conf.get('foo'))
 
3327
        self.assertEquals(None, self.conf.get('foo'))
2920
3328
 
2921
3329
    def test_get_hook(self):
2922
 
        conf = self.get_stack(self)
2923
 
        conf.store._load_from_string('foo=bar')
 
3330
        self.conf.store._load_from_string('foo=bar')
2924
3331
        calls = []
2925
3332
        def hook(*args):
2926
3333
            calls.append(args)
2927
3334
        config.ConfigHooks.install_named_hook('get', hook, None)
2928
3335
        self.assertLength(0, calls)
2929
 
        value = conf.get('foo')
 
3336
        value = self.conf.get('foo')
2930
3337
        self.assertEquals('bar', value)
2931
3338
        self.assertLength(1, calls)
2932
 
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
 
3339
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
 
3340
 
 
3341
 
 
3342
class TestStackGetWithConverter(TestStackGet):
 
3343
 
 
3344
    def setUp(self):
 
3345
        super(TestStackGetWithConverter, self).setUp()
 
3346
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3347
        self.registry = config.option_registry
 
3348
 
 
3349
    def register_bool_option(self, name, default=None, default_from_env=None):
 
3350
        b = config.Option(name, help='A boolean.',
 
3351
                          default=default, default_from_env=default_from_env,
 
3352
                          from_unicode=config.bool_from_store)
 
3353
        self.registry.register(b)
 
3354
 
 
3355
    def test_get_default_bool_None(self):
 
3356
        self.register_bool_option('foo')
 
3357
        self.assertEquals(None, self.conf.get('foo'))
 
3358
 
 
3359
    def test_get_default_bool_True(self):
 
3360
        self.register_bool_option('foo', u'True')
 
3361
        self.assertEquals(True, self.conf.get('foo'))
 
3362
 
 
3363
    def test_get_default_bool_False(self):
 
3364
        self.register_bool_option('foo', False)
 
3365
        self.assertEquals(False, self.conf.get('foo'))
 
3366
 
 
3367
    def test_get_default_bool_False_as_string(self):
 
3368
        self.register_bool_option('foo', u'False')
 
3369
        self.assertEquals(False, self.conf.get('foo'))
 
3370
 
 
3371
    def test_get_default_bool_from_env_converted(self):
 
3372
        self.register_bool_option('foo', u'True', default_from_env=['FOO'])
 
3373
        self.overrideEnv('FOO', 'False')
 
3374
        self.assertEquals(False, self.conf.get('foo'))
 
3375
 
 
3376
    def test_get_default_bool_when_conversion_fails(self):
 
3377
        self.register_bool_option('foo', default='True')
 
3378
        self.conf.store._load_from_string('foo=invalid boolean')
 
3379
        self.assertEquals(True, self.conf.get('foo'))
 
3380
 
 
3381
    def register_integer_option(self, name,
 
3382
                                default=None, default_from_env=None):
 
3383
        i = config.Option(name, help='An integer.',
 
3384
                          default=default, default_from_env=default_from_env,
 
3385
                          from_unicode=config.int_from_store)
 
3386
        self.registry.register(i)
 
3387
 
 
3388
    def test_get_default_integer_None(self):
 
3389
        self.register_integer_option('foo')
 
3390
        self.assertEquals(None, self.conf.get('foo'))
 
3391
 
 
3392
    def test_get_default_integer(self):
 
3393
        self.register_integer_option('foo', 42)
 
3394
        self.assertEquals(42, self.conf.get('foo'))
 
3395
 
 
3396
    def test_get_default_integer_as_string(self):
 
3397
        self.register_integer_option('foo', u'42')
 
3398
        self.assertEquals(42, self.conf.get('foo'))
 
3399
 
 
3400
    def test_get_default_integer_from_env(self):
 
3401
        self.register_integer_option('foo', default_from_env=['FOO'])
 
3402
        self.overrideEnv('FOO', '18')
 
3403
        self.assertEquals(18, self.conf.get('foo'))
 
3404
 
 
3405
    def test_get_default_integer_when_conversion_fails(self):
 
3406
        self.register_integer_option('foo', default='12')
 
3407
        self.conf.store._load_from_string('foo=invalid integer')
 
3408
        self.assertEquals(12, self.conf.get('foo'))
 
3409
 
 
3410
    def register_list_option(self, name, default=None, default_from_env=None):
 
3411
        l = config.Option(name, help='A list.',
 
3412
                          default=default, default_from_env=default_from_env,
 
3413
                          from_unicode=config.list_from_store)
 
3414
        self.registry.register(l)
 
3415
 
 
3416
    def test_get_default_list_None(self):
 
3417
        self.register_list_option('foo')
 
3418
        self.assertEquals(None, self.conf.get('foo'))
 
3419
 
 
3420
    def test_get_default_list_empty(self):
 
3421
        self.register_list_option('foo', '')
 
3422
        self.assertEquals([], self.conf.get('foo'))
 
3423
 
 
3424
    def test_get_default_list_from_env(self):
 
3425
        self.register_list_option('foo', default_from_env=['FOO'])
 
3426
        self.overrideEnv('FOO', '')
 
3427
        self.assertEquals([], self.conf.get('foo'))
 
3428
 
 
3429
    def test_get_with_list_converter_no_item(self):
 
3430
        self.register_list_option('foo', None)
 
3431
        self.conf.store._load_from_string('foo=,')
 
3432
        self.assertEquals([], self.conf.get('foo'))
 
3433
 
 
3434
    def test_get_with_list_converter_many_items(self):
 
3435
        self.register_list_option('foo', None)
 
3436
        self.conf.store._load_from_string('foo=m,o,r,e')
 
3437
        self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
 
3438
 
 
3439
    def test_get_with_list_converter_embedded_spaces_many_items(self):
 
3440
        self.register_list_option('foo', None)
 
3441
        self.conf.store._load_from_string('foo=" bar", "baz "')
 
3442
        self.assertEquals([' bar', 'baz '], self.conf.get('foo'))
 
3443
 
 
3444
    def test_get_with_list_converter_stripped_spaces_many_items(self):
 
3445
        self.register_list_option('foo', None)
 
3446
        self.conf.store._load_from_string('foo= bar ,  baz ')
 
3447
        self.assertEquals(['bar', 'baz'], self.conf.get('foo'))
 
3448
 
 
3449
 
 
3450
class TestStackExpandOptions(tests.TestCaseWithTransport):
 
3451
 
 
3452
    def setUp(self):
 
3453
        super(TestStackExpandOptions, self).setUp()
 
3454
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3455
        self.registry = config.option_registry
 
3456
        self.conf = build_branch_stack(self)
 
3457
 
 
3458
    def assertExpansion(self, expected, string, env=None):
 
3459
        self.assertEquals(expected, self.conf.expand_options(string, env))
 
3460
 
 
3461
    def test_no_expansion(self):
 
3462
        self.assertExpansion('foo', 'foo')
 
3463
 
 
3464
    def test_expand_default_value(self):
 
3465
        self.conf.store._load_from_string('bar=baz')
 
3466
        self.registry.register(config.Option('foo', default=u'{bar}'))
 
3467
        self.assertEquals('baz', self.conf.get('foo', expand=True))
 
3468
 
 
3469
    def test_expand_default_from_env(self):
 
3470
        self.conf.store._load_from_string('bar=baz')
 
3471
        self.registry.register(config.Option('foo', default_from_env=['FOO']))
 
3472
        self.overrideEnv('FOO', '{bar}')
 
3473
        self.assertEquals('baz', self.conf.get('foo', expand=True))
 
3474
 
 
3475
    def test_expand_default_on_failed_conversion(self):
 
3476
        self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
 
3477
        self.registry.register(
 
3478
            config.Option('foo', default=u'{bar}',
 
3479
                          from_unicode=config.int_from_store))
 
3480
        self.assertEquals(42, self.conf.get('foo', expand=True))
 
3481
 
 
3482
    def test_env_adding_options(self):
 
3483
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
 
3484
 
 
3485
    def test_env_overriding_options(self):
 
3486
        self.conf.store._load_from_string('foo=baz')
 
3487
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
 
3488
 
 
3489
    def test_simple_ref(self):
 
3490
        self.conf.store._load_from_string('foo=xxx')
 
3491
        self.assertExpansion('xxx', '{foo}')
 
3492
 
 
3493
    def test_unknown_ref(self):
 
3494
        self.assertRaises(errors.ExpandingUnknownOption,
 
3495
                          self.conf.expand_options, '{foo}')
 
3496
 
 
3497
    def test_indirect_ref(self):
 
3498
        self.conf.store._load_from_string('''
 
3499
foo=xxx
 
3500
bar={foo}
 
3501
''')
 
3502
        self.assertExpansion('xxx', '{bar}')
 
3503
 
 
3504
    def test_embedded_ref(self):
 
3505
        self.conf.store._load_from_string('''
 
3506
foo=xxx
 
3507
bar=foo
 
3508
''')
 
3509
        self.assertExpansion('xxx', '{{bar}}')
 
3510
 
 
3511
    def test_simple_loop(self):
 
3512
        self.conf.store._load_from_string('foo={foo}')
 
3513
        self.assertRaises(errors.OptionExpansionLoop,
 
3514
                          self.conf.expand_options, '{foo}')
 
3515
 
 
3516
    def test_indirect_loop(self):
 
3517
        self.conf.store._load_from_string('''
 
3518
foo={bar}
 
3519
bar={baz}
 
3520
baz={foo}''')
 
3521
        e = self.assertRaises(errors.OptionExpansionLoop,
 
3522
                              self.conf.expand_options, '{foo}')
 
3523
        self.assertEquals('foo->bar->baz', e.refs)
 
3524
        self.assertEquals('{foo}', e.string)
 
3525
 
 
3526
    def test_list(self):
 
3527
        self.conf.store._load_from_string('''
 
3528
foo=start
 
3529
bar=middle
 
3530
baz=end
 
3531
list={foo},{bar},{baz}
 
3532
''')
 
3533
        self.registry.register(
 
3534
            config.Option('list', from_unicode=config.list_from_store))
 
3535
        self.assertEquals(['start', 'middle', 'end'],
 
3536
                           self.conf.get('list', expand=True))
 
3537
 
 
3538
    def test_cascading_list(self):
 
3539
        self.conf.store._load_from_string('''
 
3540
foo=start,{bar}
 
3541
bar=middle,{baz}
 
3542
baz=end
 
3543
list={foo}
 
3544
''')
 
3545
        self.registry.register(
 
3546
            config.Option('list', from_unicode=config.list_from_store))
 
3547
        self.assertEquals(['start', 'middle', 'end'],
 
3548
                           self.conf.get('list', expand=True))
 
3549
 
 
3550
    def test_pathologically_hidden_list(self):
 
3551
        self.conf.store._load_from_string('''
 
3552
foo=bin
 
3553
bar=go
 
3554
start={foo
 
3555
middle=},{
 
3556
end=bar}
 
3557
hidden={start}{middle}{end}
 
3558
''')
 
3559
        # What matters is what the registration says, the conversion happens
 
3560
        # only after all expansions have been performed
 
3561
        self.registry.register(
 
3562
            config.Option('hidden', from_unicode=config.list_from_store))
 
3563
        self.assertEquals(['bin', 'go'],
 
3564
                          self.conf.get('hidden', expand=True))
 
3565
 
 
3566
 
 
3567
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
 
3568
 
 
3569
    def setUp(self):
 
3570
        super(TestStackCrossSectionsExpand, self).setUp()
 
3571
 
 
3572
    def get_config(self, location, string):
 
3573
        if string is None:
 
3574
            string = ''
 
3575
        # Since we don't save the config we won't strictly require to inherit
 
3576
        # from TestCaseInTempDir, but an error occurs so quickly...
 
3577
        c = config.LocationStack(location)
 
3578
        c.store._load_from_string(string)
 
3579
        return c
 
3580
 
 
3581
    def test_dont_cross_unrelated_section(self):
 
3582
        c = self.get_config('/another/branch/path','''
 
3583
[/one/branch/path]
 
3584
foo = hello
 
3585
bar = {foo}/2
 
3586
 
 
3587
[/another/branch/path]
 
3588
bar = {foo}/2
 
3589
''')
 
3590
        self.assertRaises(errors.ExpandingUnknownOption,
 
3591
                          c.get, 'bar', expand=True)
 
3592
 
 
3593
    def test_cross_related_sections(self):
 
3594
        c = self.get_config('/project/branch/path','''
 
3595
[/project]
 
3596
foo = qu
 
3597
 
 
3598
[/project/branch/path]
 
3599
bar = {foo}ux
 
3600
''')
 
3601
        self.assertEquals('quux', c.get('bar', expand=True))
2933
3602
 
2934
3603
 
2935
3604
class TestStackSet(TestStackWithTransport):
3161
3830
        conf = config.AuthenticationConfig(_file=StringIO(
3162
3831
                'foo = bar\xff'))
3163
3832
        self.assertRaises(errors.ConfigContentError, conf._get_config)
3164
 
        
 
3833
 
3165
3834
    def test_missing_auth_section_header(self):
3166
3835
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
3167
3836
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')