1312
2044
self.assertIs(None, bzrdir_config.get_default_stack_on())
2047
class TestOldConfigHooks(tests.TestCaseWithTransport):
2050
super(TestOldConfigHooks, self).setUp()
2051
create_configs_with_file_option(self)
2053
def assertGetHook(self, conf, name, value):
2057
config.OldConfigHooks.install_named_hook('get', hook, None)
2059
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2060
self.assertLength(0, calls)
2061
actual_value = conf.get_user_option(name)
2062
self.assertEquals(value, actual_value)
2063
self.assertLength(1, calls)
2064
self.assertEquals((conf, name, value), calls[0])
2066
def test_get_hook_bazaar(self):
2067
self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
2069
def test_get_hook_locations(self):
2070
self.assertGetHook(self.locations_config, 'file', 'locations')
2072
def test_get_hook_branch(self):
2073
# Since locations masks branch, we define a different option
2074
self.branch_config.set_user_option('file2', 'branch')
2075
self.assertGetHook(self.branch_config, 'file2', 'branch')
2077
def assertSetHook(self, conf, name, value):
2081
config.OldConfigHooks.install_named_hook('set', hook, None)
2083
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2084
self.assertLength(0, calls)
2085
conf.set_user_option(name, value)
2086
self.assertLength(1, calls)
2087
# We can't assert the conf object below as different configs use
2088
# different means to implement set_user_option and we care only about
2090
self.assertEquals((name, value), calls[0][1:])
2092
def test_set_hook_bazaar(self):
2093
self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
2095
def test_set_hook_locations(self):
2096
self.assertSetHook(self.locations_config, 'foo', 'locations')
2098
def test_set_hook_branch(self):
2099
self.assertSetHook(self.branch_config, 'foo', 'branch')
2101
def assertRemoveHook(self, conf, name, section_name=None):
2105
config.OldConfigHooks.install_named_hook('remove', hook, None)
2107
config.OldConfigHooks.uninstall_named_hook, 'remove', None)
2108
self.assertLength(0, calls)
2109
conf.remove_user_option(name, section_name)
2110
self.assertLength(1, calls)
2111
# We can't assert the conf object below as different configs use
2112
# different means to implement remove_user_option and we care only about
2114
self.assertEquals((name,), calls[0][1:])
2116
def test_remove_hook_bazaar(self):
2117
self.assertRemoveHook(self.bazaar_config, 'file')
2119
def test_remove_hook_locations(self):
2120
self.assertRemoveHook(self.locations_config, 'file',
2121
self.locations_config.location)
2123
def test_remove_hook_branch(self):
2124
self.assertRemoveHook(self.branch_config, 'file')
2126
def assertLoadHook(self, name, conf_class, *conf_args):
2130
config.OldConfigHooks.install_named_hook('load', hook, None)
2132
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2133
self.assertLength(0, calls)
2135
conf = conf_class(*conf_args)
2136
# Access an option to trigger a load
2137
conf.get_user_option(name)
2138
self.assertLength(1, calls)
2139
# Since we can't assert about conf, we just use the number of calls ;-/
2141
def test_load_hook_bazaar(self):
2142
self.assertLoadHook('file', config.GlobalConfig)
2144
def test_load_hook_locations(self):
2145
self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
2147
def test_load_hook_branch(self):
2148
self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
2150
def assertSaveHook(self, conf):
2154
config.OldConfigHooks.install_named_hook('save', hook, None)
2156
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2157
self.assertLength(0, calls)
2158
# Setting an option triggers a save
2159
conf.set_user_option('foo', 'bar')
2160
self.assertLength(1, calls)
2161
# Since we can't assert about conf, we just use the number of calls ;-/
2163
def test_save_hook_bazaar(self):
2164
self.assertSaveHook(self.bazaar_config)
2166
def test_save_hook_locations(self):
2167
self.assertSaveHook(self.locations_config)
2169
def test_save_hook_branch(self):
2170
self.assertSaveHook(self.branch_config)
2173
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
2174
"""Tests config hooks for remote configs.
2176
No tests for the remove hook as this is not implemented there.
2180
super(TestOldConfigHooksForRemote, self).setUp()
2181
self.transport_server = test_server.SmartTCPServer_for_testing
2182
create_configs_with_file_option(self)
2184
def assertGetHook(self, conf, name, value):
2188
config.OldConfigHooks.install_named_hook('get', hook, None)
2190
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2191
self.assertLength(0, calls)
2192
actual_value = conf.get_option(name)
2193
self.assertEquals(value, actual_value)
2194
self.assertLength(1, calls)
2195
self.assertEquals((conf, name, value), calls[0])
2197
def test_get_hook_remote_branch(self):
2198
remote_branch = branch.Branch.open(self.get_url('tree'))
2199
self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2201
def test_get_hook_remote_bzrdir(self):
2202
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2203
conf = remote_bzrdir._get_config()
2204
conf.set_option('remotedir', 'file')
2205
self.assertGetHook(conf, 'file', 'remotedir')
2207
def assertSetHook(self, conf, name, value):
2211
config.OldConfigHooks.install_named_hook('set', hook, None)
2213
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2214
self.assertLength(0, calls)
2215
conf.set_option(value, name)
2216
self.assertLength(1, calls)
2217
# We can't assert the conf object below as different configs use
2218
# different means to implement set_user_option and we care only about
2220
self.assertEquals((name, value), calls[0][1:])
2222
def test_set_hook_remote_branch(self):
2223
remote_branch = branch.Branch.open(self.get_url('tree'))
2224
self.addCleanup(remote_branch.lock_write().unlock)
2225
self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
2227
def test_set_hook_remote_bzrdir(self):
2228
remote_branch = branch.Branch.open(self.get_url('tree'))
2229
self.addCleanup(remote_branch.lock_write().unlock)
2230
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2231
self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2233
def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2237
config.OldConfigHooks.install_named_hook('load', hook, None)
2239
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2240
self.assertLength(0, calls)
2242
conf = conf_class(*conf_args)
2243
# Access an option to trigger a load
2244
conf.get_option(name)
2245
self.assertLength(expected_nb_calls, calls)
2246
# Since we can't assert about conf, we just use the number of calls ;-/
2248
def test_load_hook_remote_branch(self):
2249
remote_branch = branch.Branch.open(self.get_url('tree'))
2250
self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2252
def test_load_hook_remote_bzrdir(self):
2253
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2254
# The config file doesn't exist, set an option to force its creation
2255
conf = remote_bzrdir._get_config()
2256
conf.set_option('remotedir', 'file')
2257
# We get one call for the server and one call for the client, this is
2258
# caused by the differences in implementations betwen
2259
# SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
2260
# SmartServerBranchGetConfigFile (in smart/branch.py)
2261
self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
2263
def assertSaveHook(self, conf):
2267
config.OldConfigHooks.install_named_hook('save', hook, None)
2269
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2270
self.assertLength(0, calls)
2271
# Setting an option triggers a save
2272
conf.set_option('foo', 'bar')
2273
self.assertLength(1, calls)
2274
# Since we can't assert about conf, we just use the number of calls ;-/
2276
def test_save_hook_remote_branch(self):
2277
remote_branch = branch.Branch.open(self.get_url('tree'))
2278
self.addCleanup(remote_branch.lock_write().unlock)
2279
self.assertSaveHook(remote_branch._get_config())
2281
def test_save_hook_remote_bzrdir(self):
2282
remote_branch = branch.Branch.open(self.get_url('tree'))
2283
self.addCleanup(remote_branch.lock_write().unlock)
2284
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2285
self.assertSaveHook(remote_bzrdir._get_config())
2288
class TestOption(tests.TestCase):
2290
def test_default_value(self):
2291
opt = config.Option('foo', default='bar')
2292
self.assertEquals('bar', opt.get_default())
2294
def test_callable_default_value(self):
2295
def bar_as_unicode():
2297
opt = config.Option('foo', default=bar_as_unicode)
2298
self.assertEquals('bar', opt.get_default())
2300
def test_default_value_from_env(self):
2301
opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2302
self.overrideEnv('FOO', 'quux')
2303
# Env variable provides a default taking over the option one
2304
self.assertEquals('quux', opt.get_default())
2306
def test_first_default_value_from_env_wins(self):
2307
opt = config.Option('foo', default='bar',
2308
default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2309
self.overrideEnv('FOO', 'foo')
2310
self.overrideEnv('BAZ', 'baz')
2311
# The first env var set wins
2312
self.assertEquals('foo', opt.get_default())
2314
def test_not_supported_list_default_value(self):
2315
self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2317
def test_not_supported_object_default_value(self):
2318
self.assertRaises(AssertionError, config.Option, 'foo',
2321
def test_not_supported_callable_default_value_not_unicode(self):
2322
def bar_not_unicode():
2324
opt = config.Option('foo', default=bar_not_unicode)
2325
self.assertRaises(AssertionError, opt.get_default)
2328
class TestOptionConverterMixin(object):
2330
def assertConverted(self, expected, opt, value):
2331
self.assertEquals(expected, opt.convert_from_unicode(None, value))
2333
def assertWarns(self, opt, value):
2336
warnings.append(args[0] % args[1:])
2337
self.overrideAttr(trace, 'warning', warning)
2338
self.assertEquals(None, opt.convert_from_unicode(None, value))
2339
self.assertLength(1, warnings)
2341
'Value "%s" is not valid for "%s"' % (value, opt.name),
2344
def assertErrors(self, opt, value):
2345
self.assertRaises(errors.ConfigOptionValueError,
2346
opt.convert_from_unicode, None, value)
2348
def assertConvertInvalid(self, opt, invalid_value):
2350
self.assertEquals(None, opt.convert_from_unicode(None, invalid_value))
2351
opt.invalid = 'warning'
2352
self.assertWarns(opt, invalid_value)
2353
opt.invalid = 'error'
2354
self.assertErrors(opt, invalid_value)
2357
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2359
def get_option(self):
2360
return config.Option('foo', help='A boolean.',
2361
from_unicode=config.bool_from_store)
2363
def test_convert_invalid(self):
2364
opt = self.get_option()
2365
# A string that is not recognized as a boolean
2366
self.assertConvertInvalid(opt, u'invalid-boolean')
2367
# A list of strings is never recognized as a boolean
2368
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2370
def test_convert_valid(self):
2371
opt = self.get_option()
2372
self.assertConverted(True, opt, u'True')
2373
self.assertConverted(True, opt, u'1')
2374
self.assertConverted(False, opt, u'False')
2377
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2379
def get_option(self):
2380
return config.Option('foo', help='An integer.',
2381
from_unicode=config.int_from_store)
2383
def test_convert_invalid(self):
2384
opt = self.get_option()
2385
# A string that is not recognized as an integer
2386
self.assertConvertInvalid(opt, u'forty-two')
2387
# A list of strings is never recognized as an integer
2388
self.assertConvertInvalid(opt, [u'a', u'list'])
2390
def test_convert_valid(self):
2391
opt = self.get_option()
2392
self.assertConverted(16, opt, u'16')
2395
class TestOptionWithSIUnitConverter(tests.TestCase, TestOptionConverterMixin):
2397
def get_option(self):
2398
return config.Option('foo', help='An integer in SI units.',
2399
from_unicode=config.int_SI_from_store)
2401
def test_convert_invalid(self):
2402
opt = self.get_option()
2403
self.assertConvertInvalid(opt, u'not-a-unit')
2404
self.assertConvertInvalid(opt, u'Gb') # Forgot the int
2405
self.assertConvertInvalid(opt, u'1b') # Forgot the unit
2406
self.assertConvertInvalid(opt, u'1GG')
2407
self.assertConvertInvalid(opt, u'1Mbb')
2408
self.assertConvertInvalid(opt, u'1MM')
2410
def test_convert_valid(self):
2411
opt = self.get_option()
2412
self.assertConverted(int(5e3), opt, u'5kb')
2413
self.assertConverted(int(5e6), opt, u'5M')
2414
self.assertConverted(int(5e6), opt, u'5MB')
2415
self.assertConverted(int(5e9), opt, u'5g')
2416
self.assertConverted(int(5e9), opt, u'5gB')
2417
self.assertConverted(100, opt, u'100')
2420
class TestListOption(tests.TestCase, TestOptionConverterMixin):
2422
def get_option(self):
2423
return config.ListOption('foo', help='A list.')
2425
def test_convert_invalid(self):
2426
opt = self.get_option()
2427
# We don't even try to convert a list into a list, we only expect
2429
self.assertConvertInvalid(opt, [1])
2430
# No string is invalid as all forms can be converted to a list
2432
def test_convert_valid(self):
2433
opt = self.get_option()
2434
# An empty string is an empty list
2435
self.assertConverted([], opt, '') # Using a bare str() just in case
2436
self.assertConverted([], opt, u'')
2438
self.assertConverted([u'True'], opt, u'True')
2440
self.assertConverted([u'42'], opt, u'42')
2442
self.assertConverted([u'bar'], opt, u'bar')
2445
class TestRegistryOption(tests.TestCase, TestOptionConverterMixin):
2447
def get_option(self, registry):
2448
return config.RegistryOption('foo', registry,
2449
help='A registry option.')
2451
def test_convert_invalid(self):
2452
registry = _mod_registry.Registry()
2453
opt = self.get_option(registry)
2454
self.assertConvertInvalid(opt, [1])
2455
self.assertConvertInvalid(opt, u"notregistered")
2457
def test_convert_valid(self):
2458
registry = _mod_registry.Registry()
2459
registry.register("someval", 1234)
2460
opt = self.get_option(registry)
2461
# Using a bare str() just in case
2462
self.assertConverted(1234, opt, "someval")
2463
self.assertConverted(1234, opt, u'someval')
2464
self.assertConverted(None, opt, None)
2466
def test_help(self):
2467
registry = _mod_registry.Registry()
2468
registry.register("someval", 1234, help="some option")
2469
registry.register("dunno", 1234, help="some other option")
2470
opt = self.get_option(registry)
2472
'A registry option.\n'
2474
'The following values are supported:\n'
2475
' dunno - some other option\n'
2476
' someval - some option\n',
2479
def test_get_help_text(self):
2480
registry = _mod_registry.Registry()
2481
registry.register("someval", 1234, help="some option")
2482
registry.register("dunno", 1234, help="some other option")
2483
opt = self.get_option(registry)
2485
'A registry option.\n'
2487
'The following values are supported:\n'
2488
' dunno - some other option\n'
2489
' someval - some option\n',
2490
opt.get_help_text())
2493
class TestOptionRegistry(tests.TestCase):
2496
super(TestOptionRegistry, self).setUp()
2497
# Always start with an empty registry
2498
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2499
self.registry = config.option_registry
2501
def test_register(self):
2502
opt = config.Option('foo')
2503
self.registry.register(opt)
2504
self.assertIs(opt, self.registry.get('foo'))
2506
def test_registered_help(self):
2507
opt = config.Option('foo', help='A simple option')
2508
self.registry.register(opt)
2509
self.assertEquals('A simple option', self.registry.get_help('foo'))
2511
lazy_option = config.Option('lazy_foo', help='Lazy help')
2513
def test_register_lazy(self):
2514
self.registry.register_lazy('lazy_foo', self.__module__,
2515
'TestOptionRegistry.lazy_option')
2516
self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2518
def test_registered_lazy_help(self):
2519
self.registry.register_lazy('lazy_foo', self.__module__,
2520
'TestOptionRegistry.lazy_option')
2521
self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2524
class TestRegisteredOptions(tests.TestCase):
2525
"""All registered options should verify some constraints."""
2527
scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2528
in config.option_registry.iteritems()]
2531
super(TestRegisteredOptions, self).setUp()
2532
self.registry = config.option_registry
2534
def test_proper_name(self):
2535
# An option should be registered under its own name, this can't be
2536
# checked at registration time for the lazy ones.
2537
self.assertEquals(self.option_name, self.option.name)
2539
def test_help_is_set(self):
2540
option_help = self.registry.get_help(self.option_name)
2541
self.assertNotEquals(None, option_help)
2542
# Come on, think about the user, he really wants to know what the
2544
self.assertIsNot(None, option_help)
2545
self.assertNotEquals('', option_help)
2548
class TestSection(tests.TestCase):
2550
# FIXME: Parametrize so that all sections produced by Stores run these
2551
# tests -- vila 2011-04-01
2553
def test_get_a_value(self):
2554
a_dict = dict(foo='bar')
2555
section = config.Section('myID', a_dict)
2556
self.assertEquals('bar', section.get('foo'))
2558
def test_get_unknown_option(self):
2560
section = config.Section(None, a_dict)
2561
self.assertEquals('out of thin air',
2562
section.get('foo', 'out of thin air'))
2564
def test_options_is_shared(self):
2566
section = config.Section(None, a_dict)
2567
self.assertIs(a_dict, section.options)
2570
class TestMutableSection(tests.TestCase):
2572
scenarios = [('mutable',
2574
lambda opts: config.MutableSection('myID', opts)},),
2578
a_dict = dict(foo='bar')
2579
section = self.get_section(a_dict)
2580
section.set('foo', 'new_value')
2581
self.assertEquals('new_value', section.get('foo'))
2582
# The change appears in the shared section
2583
self.assertEquals('new_value', a_dict.get('foo'))
2584
# We keep track of the change
2585
self.assertTrue('foo' in section.orig)
2586
self.assertEquals('bar', section.orig.get('foo'))
2588
def test_set_preserve_original_once(self):
2589
a_dict = dict(foo='bar')
2590
section = self.get_section(a_dict)
2591
section.set('foo', 'first_value')
2592
section.set('foo', 'second_value')
2593
# We keep track of the original value
2594
self.assertTrue('foo' in section.orig)
2595
self.assertEquals('bar', section.orig.get('foo'))
2597
def test_remove(self):
2598
a_dict = dict(foo='bar')
2599
section = self.get_section(a_dict)
2600
section.remove('foo')
2601
# We get None for unknown options via the default value
2602
self.assertEquals(None, section.get('foo'))
2603
# Or we just get the default value
2604
self.assertEquals('unknown', section.get('foo', 'unknown'))
2605
self.assertFalse('foo' in section.options)
2606
# We keep track of the deletion
2607
self.assertTrue('foo' in section.orig)
2608
self.assertEquals('bar', section.orig.get('foo'))
2610
def test_remove_new_option(self):
2612
section = self.get_section(a_dict)
2613
section.set('foo', 'bar')
2614
section.remove('foo')
2615
self.assertFalse('foo' in section.options)
2616
# The option didn't exist initially so it we need to keep track of it
2617
# with a special value
2618
self.assertTrue('foo' in section.orig)
2619
self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2622
class TestCommandLineStore(tests.TestCase):
2625
super(TestCommandLineStore, self).setUp()
2626
self.store = config.CommandLineStore()
2627
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2629
def get_section(self):
2630
"""Get the unique section for the command line overrides."""
2631
sections = list(self.store.get_sections())
2632
self.assertLength(1, sections)
2633
store, section = sections[0]
2634
self.assertEquals(self.store, store)
2637
def test_no_override(self):
2638
self.store._from_cmdline([])
2639
section = self.get_section()
2640
self.assertLength(0, list(section.iter_option_names()))
2642
def test_simple_override(self):
2643
self.store._from_cmdline(['a=b'])
2644
section = self.get_section()
2645
self.assertEqual('b', section.get('a'))
2647
def test_list_override(self):
2648
opt = config.ListOption('l')
2649
config.option_registry.register(opt)
2650
self.store._from_cmdline(['l=1,2,3'])
2651
val = self.get_section().get('l')
2652
self.assertEqual('1,2,3', val)
2653
# Reminder: lists should be registered as such explicitely, otherwise
2654
# the conversion needs to be done afterwards.
2655
self.assertEqual(['1', '2', '3'],
2656
opt.convert_from_unicode(self.store, val))
2658
def test_multiple_overrides(self):
2659
self.store._from_cmdline(['a=b', 'x=y'])
2660
section = self.get_section()
2661
self.assertEquals('b', section.get('a'))
2662
self.assertEquals('y', section.get('x'))
2664
def test_wrong_syntax(self):
2665
self.assertRaises(errors.BzrCommandError,
2666
self.store._from_cmdline, ['a=b', 'c'])
2668
class TestStoreMinimalAPI(tests.TestCaseWithTransport):
2670
scenarios = [(key, {'get_store': builder}) for key, builder
2671
in config.test_store_builder_registry.iteritems()] + [
2672
('cmdline', {'get_store': lambda test: config.CommandLineStore()})]
2675
store = self.get_store(self)
2676
if type(store) == config.TransportIniFileStore:
2677
raise tests.TestNotApplicable(
2678
"%s is not a concrete Store implementation"
2679
" so it doesn't need an id" % (store.__class__.__name__,))
2680
self.assertIsNot(None, store.id)
2683
class TestStore(tests.TestCaseWithTransport):
2685
def assertSectionContent(self, expected, (store, section)):
2686
"""Assert that some options have the proper values in a section."""
2687
expected_name, expected_options = expected
2688
self.assertEquals(expected_name, section.id)
2691
dict([(k, section.get(k)) for k in expected_options.keys()]))
2694
class TestReadonlyStore(TestStore):
2696
scenarios = [(key, {'get_store': builder}) for key, builder
2697
in config.test_store_builder_registry.iteritems()]
2699
def test_building_delays_load(self):
2700
store = self.get_store(self)
2701
self.assertEquals(False, store.is_loaded())
2702
store._load_from_string('')
2703
self.assertEquals(True, store.is_loaded())
2705
def test_get_no_sections_for_empty(self):
2706
store = self.get_store(self)
2707
store._load_from_string('')
2708
self.assertEquals([], list(store.get_sections()))
2710
def test_get_default_section(self):
2711
store = self.get_store(self)
2712
store._load_from_string('foo=bar')
2713
sections = list(store.get_sections())
2714
self.assertLength(1, sections)
2715
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2717
def test_get_named_section(self):
2718
store = self.get_store(self)
2719
store._load_from_string('[baz]\nfoo=bar')
2720
sections = list(store.get_sections())
2721
self.assertLength(1, sections)
2722
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2724
def test_load_from_string_fails_for_non_empty_store(self):
2725
store = self.get_store(self)
2726
store._load_from_string('foo=bar')
2727
self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2730
class TestStoreQuoting(TestStore):
2732
scenarios = [(key, {'get_store': builder}) for key, builder
2733
in config.test_store_builder_registry.iteritems()]
2736
super(TestStoreQuoting, self).setUp()
2737
self.store = self.get_store(self)
2738
# We need a loaded store but any content will do
2739
self.store._load_from_string('')
2741
def assertIdempotent(self, s):
2742
"""Assert that quoting an unquoted string is a no-op and vice-versa.
2744
What matters here is that option values, as they appear in a store, can
2745
be safely round-tripped out of the store and back.
2747
:param s: A string, quoted if required.
2749
self.assertEquals(s, self.store.quote(self.store.unquote(s)))
2750
self.assertEquals(s, self.store.unquote(self.store.quote(s)))
2752
def test_empty_string(self):
2753
if isinstance(self.store, config.IniFileStore):
2754
# configobj._quote doesn't handle empty values
2755
self.assertRaises(AssertionError,
2756
self.assertIdempotent, '')
2758
self.assertIdempotent('')
2759
# But quoted empty strings are ok
2760
self.assertIdempotent('""')
2762
def test_embedded_spaces(self):
2763
self.assertIdempotent('" a b c "')
2765
def test_embedded_commas(self):
2766
self.assertIdempotent('" a , b c "')
2768
def test_simple_comma(self):
2769
if isinstance(self.store, config.IniFileStore):
2770
# configobj requires that lists are special-cased
2771
self.assertRaises(AssertionError,
2772
self.assertIdempotent, ',')
2774
self.assertIdempotent(',')
2775
# When a single comma is required, quoting is also required
2776
self.assertIdempotent('","')
2778
def test_list(self):
2779
if isinstance(self.store, config.IniFileStore):
2780
# configobj requires that lists are special-cased
2781
self.assertRaises(AssertionError,
2782
self.assertIdempotent, 'a,b')
2784
self.assertIdempotent('a,b')
2787
class TestDictFromStore(tests.TestCase):
2789
def test_unquote_not_string(self):
2790
conf = config.MemoryStack('x=2\n[a_section]\na=1\n')
2791
value = conf.get('a_section')
2792
# Urgh, despite 'conf' asking for the no-name section, we get the
2793
# content of another section as a dict o_O
2794
self.assertEquals({'a': '1'}, value)
2795
unquoted = conf.store.unquote(value)
2796
# Which cannot be unquoted but shouldn't crash either (the use cases
2797
# are getting the value or displaying it. In the later case, '%s' will
2799
self.assertEquals({'a': '1'}, unquoted)
2800
self.assertEquals("{u'a': u'1'}", '%s' % (unquoted,))
2803
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2804
"""Simulate loading a config store with content of various encodings.
2806
All files produced by bzr are in utf8 content.
2808
Users may modify them manually and end up with a file that can't be
2809
loaded. We need to issue proper error messages in this case.
2812
invalid_utf8_char = '\xff'
2814
def test_load_utf8(self):
2815
"""Ensure we can load an utf8-encoded file."""
2816
t = self.get_transport()
2817
# From http://pad.lv/799212
2818
unicode_user = u'b\N{Euro Sign}ar'
2819
unicode_content = u'user=%s' % (unicode_user,)
2820
utf8_content = unicode_content.encode('utf8')
2821
# Store the raw content in the config file
2822
t.put_bytes('foo.conf', utf8_content)
2823
store = config.TransportIniFileStore(t, 'foo.conf')
2825
stack = config.Stack([store.get_sections], store)
2826
self.assertEquals(unicode_user, stack.get('user'))
2828
def test_load_non_ascii(self):
2829
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2830
t = self.get_transport()
2831
t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2832
store = config.TransportIniFileStore(t, 'foo.conf')
2833
self.assertRaises(errors.ConfigContentError, store.load)
2835
def test_load_erroneous_content(self):
2836
"""Ensure we display a proper error on content that can't be parsed."""
2837
t = self.get_transport()
2838
t.put_bytes('foo.conf', '[open_section\n')
2839
store = config.TransportIniFileStore(t, 'foo.conf')
2840
self.assertRaises(errors.ParseConfigError, store.load)
2842
def test_load_permission_denied(self):
2843
"""Ensure we get warned when trying to load an inaccessible file."""
2846
warnings.append(args[0] % args[1:])
2847
self.overrideAttr(trace, 'warning', warning)
2849
t = self.get_transport()
2851
def get_bytes(relpath):
2852
raise errors.PermissionDenied(relpath, "")
2853
t.get_bytes = get_bytes
2854
store = config.TransportIniFileStore(t, 'foo.conf')
2855
self.assertRaises(errors.PermissionDenied, store.load)
2858
[u'Permission denied while trying to load configuration store %s.'
2859
% store.external_url()])
2862
class TestIniConfigContent(tests.TestCaseWithTransport):
2863
"""Simulate loading a IniBasedConfig with content of various encodings.
2865
All files produced by bzr are in utf8 content.
2867
Users may modify them manually and end up with a file that can't be
2868
loaded. We need to issue proper error messages in this case.
2871
invalid_utf8_char = '\xff'
2873
def test_load_utf8(self):
2874
"""Ensure we can load an utf8-encoded file."""
2875
# From http://pad.lv/799212
2876
unicode_user = u'b\N{Euro Sign}ar'
2877
unicode_content = u'user=%s' % (unicode_user,)
2878
utf8_content = unicode_content.encode('utf8')
2879
# Store the raw content in the config file
2880
with open('foo.conf', 'wb') as f:
2881
f.write(utf8_content)
2882
conf = config.IniBasedConfig(file_name='foo.conf')
2883
self.assertEquals(unicode_user, conf.get_user_option('user'))
2885
def test_load_badly_encoded_content(self):
2886
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2887
with open('foo.conf', 'wb') as f:
2888
f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2889
conf = config.IniBasedConfig(file_name='foo.conf')
2890
self.assertRaises(errors.ConfigContentError, conf._get_parser)
2892
def test_load_erroneous_content(self):
2893
"""Ensure we display a proper error on content that can't be parsed."""
2894
with open('foo.conf', 'wb') as f:
2895
f.write('[open_section\n')
2896
conf = config.IniBasedConfig(file_name='foo.conf')
2897
self.assertRaises(errors.ParseConfigError, conf._get_parser)
2900
class TestMutableStore(TestStore):
2902
scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2903
in config.test_store_builder_registry.iteritems()]
2906
super(TestMutableStore, self).setUp()
2907
self.transport = self.get_transport()
2909
def has_store(self, store):
2910
store_basename = urlutils.relative_url(self.transport.external_url(),
2911
store.external_url())
2912
return self.transport.has(store_basename)
2914
def test_save_empty_creates_no_file(self):
2915
# FIXME: There should be a better way than relying on the test
2916
# parametrization to identify branch.conf -- vila 2011-0526
2917
if self.store_id in ('branch', 'remote_branch'):
2918
raise tests.TestNotApplicable(
2919
'branch.conf is *always* created when a branch is initialized')
2920
store = self.get_store(self)
2922
self.assertEquals(False, self.has_store(store))
2924
def test_save_emptied_succeeds(self):
2925
store = self.get_store(self)
2926
store._load_from_string('foo=bar\n')
2927
section = store.get_mutable_section(None)
2928
section.remove('foo')
2930
self.assertEquals(True, self.has_store(store))
2931
modified_store = self.get_store(self)
2932
sections = list(modified_store.get_sections())
2933
self.assertLength(0, sections)
2935
def test_save_with_content_succeeds(self):
2936
# FIXME: There should be a better way than relying on the test
2937
# parametrization to identify branch.conf -- vila 2011-0526
2938
if self.store_id in ('branch', 'remote_branch'):
2939
raise tests.TestNotApplicable(
2940
'branch.conf is *always* created when a branch is initialized')
2941
store = self.get_store(self)
2942
store._load_from_string('foo=bar\n')
2943
self.assertEquals(False, self.has_store(store))
2945
self.assertEquals(True, self.has_store(store))
2946
modified_store = self.get_store(self)
2947
sections = list(modified_store.get_sections())
2948
self.assertLength(1, sections)
2949
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2951
def test_set_option_in_empty_store(self):
2952
store = self.get_store(self)
2953
section = store.get_mutable_section(None)
2954
section.set('foo', 'bar')
2956
modified_store = self.get_store(self)
2957
sections = list(modified_store.get_sections())
2958
self.assertLength(1, sections)
2959
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2961
def test_set_option_in_default_section(self):
2962
store = self.get_store(self)
2963
store._load_from_string('')
2964
section = store.get_mutable_section(None)
2965
section.set('foo', 'bar')
2967
modified_store = self.get_store(self)
2968
sections = list(modified_store.get_sections())
2969
self.assertLength(1, sections)
2970
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2972
def test_set_option_in_named_section(self):
2973
store = self.get_store(self)
2974
store._load_from_string('')
2975
section = store.get_mutable_section('baz')
2976
section.set('foo', 'bar')
2978
modified_store = self.get_store(self)
2979
sections = list(modified_store.get_sections())
2980
self.assertLength(1, sections)
2981
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2983
def test_load_hook(self):
2984
# We first needs to ensure that the store exists
2985
store = self.get_store(self)
2986
section = store.get_mutable_section('baz')
2987
section.set('foo', 'bar')
2989
# Now we can try to load it
2990
store = self.get_store(self)
2994
config.ConfigHooks.install_named_hook('load', hook, None)
2995
self.assertLength(0, calls)
2997
self.assertLength(1, calls)
2998
self.assertEquals((store,), calls[0])
3000
def test_save_hook(self):
3004
config.ConfigHooks.install_named_hook('save', hook, None)
3005
self.assertLength(0, calls)
3006
store = self.get_store(self)
3007
section = store.get_mutable_section('baz')
3008
section.set('foo', 'bar')
3010
self.assertLength(1, calls)
3011
self.assertEquals((store,), calls[0])
3013
def test_set_mark_dirty(self):
3014
stack = config.MemoryStack('')
3015
self.assertLength(0, stack.store.dirty_sections)
3016
stack.set('foo', 'baz')
3017
self.assertLength(1, stack.store.dirty_sections)
3018
self.assertTrue(stack.store._need_saving())
3020
def test_remove_mark_dirty(self):
3021
stack = config.MemoryStack('foo=bar')
3022
self.assertLength(0, stack.store.dirty_sections)
3024
self.assertLength(1, stack.store.dirty_sections)
3025
self.assertTrue(stack.store._need_saving())
3028
class TestStoreSaveChanges(tests.TestCaseWithTransport):
3029
"""Tests that config changes are kept in memory and saved on-demand."""
3032
super(TestStoreSaveChanges, self).setUp()
3033
self.transport = self.get_transport()
3034
# Most of the tests involve two stores pointing to the same persistent
3035
# storage to observe the effects of concurrent changes
3036
self.st1 = config.TransportIniFileStore(self.transport, 'foo.conf')
3037
self.st2 = config.TransportIniFileStore(self.transport, 'foo.conf')
3040
self.warnings.append(args[0] % args[1:])
3041
self.overrideAttr(trace, 'warning', warning)
3043
def has_store(self, store):
3044
store_basename = urlutils.relative_url(self.transport.external_url(),
3045
store.external_url())
3046
return self.transport.has(store_basename)
3048
def get_stack(self, store):
3049
# Any stack will do as long as it uses the right store, just a single
3050
# no-name section is enough
3051
return config.Stack([store.get_sections], store)
3053
def test_no_changes_no_save(self):
3054
s = self.get_stack(self.st1)
3055
s.store.save_changes()
3056
self.assertEquals(False, self.has_store(self.st1))
3058
def test_unrelated_concurrent_update(self):
3059
s1 = self.get_stack(self.st1)
3060
s2 = self.get_stack(self.st2)
3061
s1.set('foo', 'bar')
3062
s2.set('baz', 'quux')
3064
# Changes don't propagate magically
3065
self.assertEquals(None, s1.get('baz'))
3066
s2.store.save_changes()
3067
self.assertEquals('quux', s2.get('baz'))
3068
# Changes are acquired when saving
3069
self.assertEquals('bar', s2.get('foo'))
3070
# Since there is no overlap, no warnings are emitted
3071
self.assertLength(0, self.warnings)
3073
def test_concurrent_update_modified(self):
3074
s1 = self.get_stack(self.st1)
3075
s2 = self.get_stack(self.st2)
3076
s1.set('foo', 'bar')
3077
s2.set('foo', 'baz')
3080
s2.store.save_changes()
3081
self.assertEquals('baz', s2.get('foo'))
3082
# But the user get a warning
3083
self.assertLength(1, self.warnings)
3084
warning = self.warnings[0]
3085
self.assertStartsWith(warning, 'Option foo in section None')
3086
self.assertEndsWith(warning, 'was changed from <CREATED> to bar.'
3087
' The baz value will be saved.')
3089
def test_concurrent_deletion(self):
3090
self.st1._load_from_string('foo=bar')
3092
s1 = self.get_stack(self.st1)
3093
s2 = self.get_stack(self.st2)
3096
s1.store.save_changes()
3098
self.assertLength(0, self.warnings)
3099
s2.store.save_changes()
3101
self.assertLength(1, self.warnings)
3102
warning = self.warnings[0]
3103
self.assertStartsWith(warning, 'Option foo in section None')
3104
self.assertEndsWith(warning, 'was changed from bar to <CREATED>.'
3105
' The <DELETED> value will be saved.')
3108
class TestQuotingIniFileStore(tests.TestCaseWithTransport):
3110
def get_store(self):
3111
return config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3113
def test_get_quoted_string(self):
3114
store = self.get_store()
3115
store._load_from_string('foo= " abc "')
3116
stack = config.Stack([store.get_sections])
3117
self.assertEquals(' abc ', stack.get('foo'))
3119
def test_set_quoted_string(self):
3120
store = self.get_store()
3121
stack = config.Stack([store.get_sections], store)
3122
stack.set('foo', ' a b c ')
3124
self.assertFileEqual('foo = " a b c "' + os.linesep, 'foo.conf')
3127
class TestTransportIniFileStore(TestStore):
3129
def test_loading_unknown_file_fails(self):
3130
store = config.TransportIniFileStore(self.get_transport(),
3132
self.assertRaises(errors.NoSuchFile, store.load)
3134
def test_invalid_content(self):
3135
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3136
self.assertEquals(False, store.is_loaded())
3137
exc = self.assertRaises(
3138
errors.ParseConfigError, store._load_from_string,
3139
'this is invalid !')
3140
self.assertEndsWith(exc.filename, 'foo.conf')
3141
# And the load failed
3142
self.assertEquals(False, store.is_loaded())
3144
def test_get_embedded_sections(self):
3145
# A more complicated example (which also shows that section names and
3146
# option names share the same name space...)
3147
# FIXME: This should be fixed by forbidding dicts as values ?
3148
# -- vila 2011-04-05
3149
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3150
store._load_from_string('''
3154
foo_in_DEFAULT=foo_DEFAULT
3162
sections = list(store.get_sections())
3163
self.assertLength(4, sections)
3164
# The default section has no name.
3165
# List values are provided as strings and need to be explicitly
3166
# converted by specifying from_unicode=list_from_store at option
3168
self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
3170
self.assertSectionContent(
3171
('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
3172
self.assertSectionContent(
3173
('bar', {'foo_in_bar': 'barbar'}), sections[2])
3174
# sub sections are provided as embedded dicts.
3175
self.assertSectionContent(
3176
('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
3180
class TestLockableIniFileStore(TestStore):
3182
def test_create_store_in_created_dir(self):
3183
self.assertPathDoesNotExist('dir')
3184
t = self.get_transport('dir/subdir')
3185
store = config.LockableIniFileStore(t, 'foo.conf')
3186
store.get_mutable_section(None).set('foo', 'bar')
3188
self.assertPathExists('dir/subdir')
3191
class TestConcurrentStoreUpdates(TestStore):
3192
"""Test that Stores properly handle conccurent updates.
3194
New Store implementation may fail some of these tests but until such
3195
implementations exist it's hard to properly filter them from the scenarios
3196
applied here. If you encounter such a case, contact the bzr devs.
3199
scenarios = [(key, {'get_stack': builder}) for key, builder
3200
in config.test_stack_builder_registry.iteritems()]
3203
super(TestConcurrentStoreUpdates, self).setUp()
3204
self.stack = self.get_stack(self)
3205
if not isinstance(self.stack, config._CompatibleStack):
3206
raise tests.TestNotApplicable(
3207
'%s is not meant to be compatible with the old config design'
3209
self.stack.set('one', '1')
3210
self.stack.set('two', '2')
3212
self.stack.store.save()
3214
def test_simple_read_access(self):
3215
self.assertEquals('1', self.stack.get('one'))
3217
def test_simple_write_access(self):
3218
self.stack.set('one', 'one')
3219
self.assertEquals('one', self.stack.get('one'))
3221
def test_listen_to_the_last_speaker(self):
3223
c2 = self.get_stack(self)
3224
c1.set('one', 'ONE')
3225
c2.set('two', 'TWO')
3226
self.assertEquals('ONE', c1.get('one'))
3227
self.assertEquals('TWO', c2.get('two'))
3228
# The second update respect the first one
3229
self.assertEquals('ONE', c2.get('one'))
3231
def test_last_speaker_wins(self):
3232
# If the same config is not shared, the same variable modified twice
3233
# can only see a single result.
3235
c2 = self.get_stack(self)
3238
self.assertEquals('c2', c2.get('one'))
3239
# The first modification is still available until another refresh
3241
self.assertEquals('c1', c1.get('one'))
3242
c1.set('two', 'done')
3243
self.assertEquals('c2', c1.get('one'))
3245
def test_writes_are_serialized(self):
3247
c2 = self.get_stack(self)
3249
# We spawn a thread that will pause *during* the config saving.
3250
before_writing = threading.Event()
3251
after_writing = threading.Event()
3252
writing_done = threading.Event()
3253
c1_save_without_locking_orig = c1.store.save_without_locking
3254
def c1_save_without_locking():
3255
before_writing.set()
3256
c1_save_without_locking_orig()
3257
# The lock is held. We wait for the main thread to decide when to
3259
after_writing.wait()
3260
c1.store.save_without_locking = c1_save_without_locking
3264
t1 = threading.Thread(target=c1_set)
3265
# Collect the thread after the test
3266
self.addCleanup(t1.join)
3267
# Be ready to unblock the thread if the test goes wrong
3268
self.addCleanup(after_writing.set)
3270
before_writing.wait()
3271
self.assertRaises(errors.LockContention,
3272
c2.set, 'one', 'c2')
3273
self.assertEquals('c1', c1.get('one'))
3274
# Let the lock be released
3278
self.assertEquals('c2', c2.get('one'))
3280
def test_read_while_writing(self):
3282
# We spawn a thread that will pause *during* the write
3283
ready_to_write = threading.Event()
3284
do_writing = threading.Event()
3285
writing_done = threading.Event()
3286
# We override the _save implementation so we know the store is locked
3287
c1_save_without_locking_orig = c1.store.save_without_locking
3288
def c1_save_without_locking():
3289
ready_to_write.set()
3290
# The lock is held. We wait for the main thread to decide when to
3293
c1_save_without_locking_orig()
3295
c1.store.save_without_locking = c1_save_without_locking
3298
t1 = threading.Thread(target=c1_set)
3299
# Collect the thread after the test
3300
self.addCleanup(t1.join)
3301
# Be ready to unblock the thread if the test goes wrong
3302
self.addCleanup(do_writing.set)
3304
# Ensure the thread is ready to write
3305
ready_to_write.wait()
3306
self.assertEquals('c1', c1.get('one'))
3307
# If we read during the write, we get the old value
3308
c2 = self.get_stack(self)
3309
self.assertEquals('1', c2.get('one'))
3310
# Let the writing occur and ensure it occurred
3313
# Now we get the updated value
3314
c3 = self.get_stack(self)
3315
self.assertEquals('c1', c3.get('one'))
3317
# FIXME: It may be worth looking into removing the lock dir when it's not
3318
# needed anymore and look at possible fallouts for concurrent lockers. This
3319
# will matter if/when we use config files outside of bazaar directories
3320
# (.bazaar or .bzr) -- vila 20110-04-111
3323
class TestSectionMatcher(TestStore):
3325
scenarios = [('location', {'matcher': config.LocationMatcher}),
3326
('id', {'matcher': config.NameMatcher}),]
3329
super(TestSectionMatcher, self).setUp()
3330
# Any simple store is good enough
3331
self.get_store = config.test_store_builder_registry.get('configobj')
3333
def test_no_matches_for_empty_stores(self):
3334
store = self.get_store(self)
3335
store._load_from_string('')
3336
matcher = self.matcher(store, '/bar')
3337
self.assertEquals([], list(matcher.get_sections()))
3339
def test_build_doesnt_load_store(self):
3340
store = self.get_store(self)
3341
matcher = self.matcher(store, '/bar')
3342
self.assertFalse(store.is_loaded())
3345
class TestLocationSection(tests.TestCase):
3347
def get_section(self, options, extra_path):
3348
section = config.Section('foo', options)
3349
return config.LocationSection(section, extra_path)
3351
def test_simple_option(self):
3352
section = self.get_section({'foo': 'bar'}, '')
3353
self.assertEquals('bar', section.get('foo'))
3355
def test_option_with_extra_path(self):
3356
section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
3358
self.assertEquals('bar/baz', section.get('foo'))
3360
def test_invalid_policy(self):
3361
section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
3363
# invalid policies are ignored
3364
self.assertEquals('bar', section.get('foo'))
3367
class TestLocationMatcher(TestStore):
3370
super(TestLocationMatcher, self).setUp()
3371
# Any simple store is good enough
3372
self.get_store = config.test_store_builder_registry.get('configobj')
3374
def test_unrelated_section_excluded(self):
3375
store = self.get_store(self)
3376
store._load_from_string('''
3384
section=/foo/bar/baz
3388
self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3390
[section.id for _, section in store.get_sections()])
3391
matcher = config.LocationMatcher(store, '/foo/bar/quux')
3392
sections = [section for _, section in matcher.get_sections()]
3393
self.assertEquals(['/foo/bar', '/foo'],
3394
[section.id for section in sections])
3395
self.assertEquals(['quux', 'bar/quux'],
3396
[section.extra_path for section in sections])
3398
def test_more_specific_sections_first(self):
3399
store = self.get_store(self)
3400
store._load_from_string('''
3406
self.assertEquals(['/foo', '/foo/bar'],
3407
[section.id for _, section in store.get_sections()])
3408
matcher = config.LocationMatcher(store, '/foo/bar/baz')
3409
sections = [section for _, section in matcher.get_sections()]
3410
self.assertEquals(['/foo/bar', '/foo'],
3411
[section.id for section in sections])
3412
self.assertEquals(['baz', 'bar/baz'],
3413
[section.extra_path for section in sections])
3415
def test_appendpath_in_no_name_section(self):
3416
# It's a bit weird to allow appendpath in a no-name section, but
3417
# someone may found a use for it
3418
store = self.get_store(self)
3419
store._load_from_string('''
3421
foo:policy = appendpath
3423
matcher = config.LocationMatcher(store, 'dir/subdir')
3424
sections = list(matcher.get_sections())
3425
self.assertLength(1, sections)
3426
self.assertEquals('bar/dir/subdir', sections[0][1].get('foo'))
3428
def test_file_urls_are_normalized(self):
3429
store = self.get_store(self)
3430
if sys.platform == 'win32':
3431
expected_url = 'file:///C:/dir/subdir'
3432
expected_location = 'C:/dir/subdir'
3434
expected_url = 'file:///dir/subdir'
3435
expected_location = '/dir/subdir'
3436
matcher = config.LocationMatcher(store, expected_url)
3437
self.assertEquals(expected_location, matcher.location)
3440
class TestStartingPathMatcher(TestStore):
3443
super(TestStartingPathMatcher, self).setUp()
3444
# Any simple store is good enough
3445
self.store = config.IniFileStore()
3447
def assertSectionIDs(self, expected, location, content):
3448
self.store._load_from_string(content)
3449
matcher = config.StartingPathMatcher(self.store, location)
3450
sections = list(matcher.get_sections())
3451
self.assertLength(len(expected), sections)
3452
self.assertEqual(expected, [section.id for _, section in sections])
3455
def test_empty(self):
3456
self.assertSectionIDs([], self.get_url(), '')
3458
def test_url_vs_local_paths(self):
3459
# The matcher location is an url and the section names are local paths
3460
sections = self.assertSectionIDs(['/foo/bar', '/foo'],
3461
'file:///foo/bar/baz', '''\
3466
def test_local_path_vs_url(self):
3467
# The matcher location is a local path and the section names are urls
3468
sections = self.assertSectionIDs(['file:///foo/bar', 'file:///foo'],
3469
'/foo/bar/baz', '''\
3475
def test_no_name_section_included_when_present(self):
3476
# Note that other tests will cover the case where the no-name section
3477
# is empty and as such, not included.
3478
sections = self.assertSectionIDs(['/foo/bar', '/foo', None],
3479
'/foo/bar/baz', '''\
3480
option = defined so the no-name section exists
3484
self.assertEquals(['baz', 'bar/baz', '/foo/bar/baz'],
3485
[s.locals['relpath'] for _, s in sections])
3487
def test_order_reversed(self):
3488
self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
3493
def test_unrelated_section_excluded(self):
3494
self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
3500
def test_glob_included(self):
3501
sections = self.assertSectionIDs(['/foo/*/baz', '/foo/b*', '/foo'],
3502
'/foo/bar/baz', '''\
3508
# Note that 'baz' as a relpath for /foo/b* is not fully correct, but
3509
# nothing really is... as far using {relpath} to append it to something
3510
# else, this seems good enough though.
3511
self.assertEquals(['', 'baz', 'bar/baz'],
3512
[s.locals['relpath'] for _, s in sections])
3514
def test_respect_order(self):
3515
self.assertSectionIDs(['/foo', '/foo/b*', '/foo/*/baz'],
3516
'/foo/bar/baz', '''\
3524
class TestNameMatcher(TestStore):
3527
super(TestNameMatcher, self).setUp()
3528
self.matcher = config.NameMatcher
3529
# Any simple store is good enough
3530
self.get_store = config.test_store_builder_registry.get('configobj')
3532
def get_matching_sections(self, name):
3533
store = self.get_store(self)
3534
store._load_from_string('''
3542
matcher = self.matcher(store, name)
3543
return list(matcher.get_sections())
3545
def test_matching(self):
3546
sections = self.get_matching_sections('foo')
3547
self.assertLength(1, sections)
3548
self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3550
def test_not_matching(self):
3551
sections = self.get_matching_sections('baz')
3552
self.assertLength(0, sections)
3555
class TestBaseStackGet(tests.TestCase):
3558
super(TestBaseStackGet, self).setUp()
3559
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3561
def test_get_first_definition(self):
3562
store1 = config.IniFileStore()
3563
store1._load_from_string('foo=bar')
3564
store2 = config.IniFileStore()
3565
store2._load_from_string('foo=baz')
3566
conf = config.Stack([store1.get_sections, store2.get_sections])
3567
self.assertEquals('bar', conf.get('foo'))
3569
def test_get_with_registered_default_value(self):
3570
config.option_registry.register(config.Option('foo', default='bar'))
3571
conf_stack = config.Stack([])
3572
self.assertEquals('bar', conf_stack.get('foo'))
3574
def test_get_without_registered_default_value(self):
3575
config.option_registry.register(config.Option('foo'))
3576
conf_stack = config.Stack([])
3577
self.assertEquals(None, conf_stack.get('foo'))
3579
def test_get_without_default_value_for_not_registered(self):
3580
conf_stack = config.Stack([])
3581
self.assertEquals(None, conf_stack.get('foo'))
3583
def test_get_for_empty_section_callable(self):
3584
conf_stack = config.Stack([lambda : []])
3585
self.assertEquals(None, conf_stack.get('foo'))
3587
def test_get_for_broken_callable(self):
3588
# Trying to use and invalid callable raises an exception on first use
3589
conf_stack = config.Stack([object])
3590
self.assertRaises(TypeError, conf_stack.get, 'foo')
3593
class TestStackWithSimpleStore(tests.TestCase):
3596
super(TestStackWithSimpleStore, self).setUp()
3597
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3598
self.registry = config.option_registry
3600
def get_conf(self, content=None):
3601
return config.MemoryStack(content)
3603
def test_override_value_from_env(self):
3604
self.registry.register(
3605
config.Option('foo', default='bar', override_from_env=['FOO']))
3606
self.overrideEnv('FOO', 'quux')
3607
# Env variable provides a default taking over the option one
3608
conf = self.get_conf('foo=store')
3609
self.assertEquals('quux', conf.get('foo'))
3611
def test_first_override_value_from_env_wins(self):
3612
self.registry.register(
3613
config.Option('foo', default='bar',
3614
override_from_env=['NO_VALUE', 'FOO', 'BAZ']))
3615
self.overrideEnv('FOO', 'foo')
3616
self.overrideEnv('BAZ', 'baz')
3617
# The first env var set wins
3618
conf = self.get_conf('foo=store')
3619
self.assertEquals('foo', conf.get('foo'))
3622
class TestMemoryStack(tests.TestCase):
3625
conf = config.MemoryStack('foo=bar')
3626
self.assertEquals('bar', conf.get('foo'))
3629
conf = config.MemoryStack('foo=bar')
3630
conf.set('foo', 'baz')
3631
self.assertEquals('baz', conf.get('foo'))
3633
def test_no_content(self):
3634
conf = config.MemoryStack()
3635
# No content means no loading
3636
self.assertFalse(conf.store.is_loaded())
3637
self.assertRaises(NotImplementedError, conf.get, 'foo')
3638
# But a content can still be provided
3639
conf.store._load_from_string('foo=bar')
3640
self.assertEquals('bar', conf.get('foo'))
3643
class TestStackWithTransport(tests.TestCaseWithTransport):
3645
scenarios = [(key, {'get_stack': builder}) for key, builder
3646
in config.test_stack_builder_registry.iteritems()]
3649
class TestConcreteStacks(TestStackWithTransport):
3651
def test_build_stack(self):
3652
# Just a smoke test to help debug builders
3653
stack = self.get_stack(self)
3656
class TestStackGet(TestStackWithTransport):
3659
super(TestStackGet, self).setUp()
3660
self.conf = self.get_stack(self)
3662
def test_get_for_empty_stack(self):
3663
self.assertEquals(None, self.conf.get('foo'))
3665
def test_get_hook(self):
3666
self.conf.set('foo', 'bar')
3670
config.ConfigHooks.install_named_hook('get', hook, None)
3671
self.assertLength(0, calls)
3672
value = self.conf.get('foo')
3673
self.assertEquals('bar', value)
3674
self.assertLength(1, calls)
3675
self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3678
class TestStackGetWithConverter(tests.TestCase):
3681
super(TestStackGetWithConverter, self).setUp()
3682
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3683
self.registry = config.option_registry
3685
def get_conf(self, content=None):
3686
return config.MemoryStack(content)
3688
def register_bool_option(self, name, default=None, default_from_env=None):
3689
b = config.Option(name, help='A boolean.',
3690
default=default, default_from_env=default_from_env,
3691
from_unicode=config.bool_from_store)
3692
self.registry.register(b)
3694
def test_get_default_bool_None(self):
3695
self.register_bool_option('foo')
3696
conf = self.get_conf('')
3697
self.assertEquals(None, conf.get('foo'))
3699
def test_get_default_bool_True(self):
3700
self.register_bool_option('foo', u'True')
3701
conf = self.get_conf('')
3702
self.assertEquals(True, conf.get('foo'))
3704
def test_get_default_bool_False(self):
3705
self.register_bool_option('foo', False)
3706
conf = self.get_conf('')
3707
self.assertEquals(False, conf.get('foo'))
3709
def test_get_default_bool_False_as_string(self):
3710
self.register_bool_option('foo', u'False')
3711
conf = self.get_conf('')
3712
self.assertEquals(False, conf.get('foo'))
3714
def test_get_default_bool_from_env_converted(self):
3715
self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3716
self.overrideEnv('FOO', 'False')
3717
conf = self.get_conf('')
3718
self.assertEquals(False, conf.get('foo'))
3720
def test_get_default_bool_when_conversion_fails(self):
3721
self.register_bool_option('foo', default='True')
3722
conf = self.get_conf('foo=invalid boolean')
3723
self.assertEquals(True, conf.get('foo'))
3725
def register_integer_option(self, name,
3726
default=None, default_from_env=None):
3727
i = config.Option(name, help='An integer.',
3728
default=default, default_from_env=default_from_env,
3729
from_unicode=config.int_from_store)
3730
self.registry.register(i)
3732
def test_get_default_integer_None(self):
3733
self.register_integer_option('foo')
3734
conf = self.get_conf('')
3735
self.assertEquals(None, conf.get('foo'))
3737
def test_get_default_integer(self):
3738
self.register_integer_option('foo', 42)
3739
conf = self.get_conf('')
3740
self.assertEquals(42, conf.get('foo'))
3742
def test_get_default_integer_as_string(self):
3743
self.register_integer_option('foo', u'42')
3744
conf = self.get_conf('')
3745
self.assertEquals(42, conf.get('foo'))
3747
def test_get_default_integer_from_env(self):
3748
self.register_integer_option('foo', default_from_env=['FOO'])
3749
self.overrideEnv('FOO', '18')
3750
conf = self.get_conf('')
3751
self.assertEquals(18, conf.get('foo'))
3753
def test_get_default_integer_when_conversion_fails(self):
3754
self.register_integer_option('foo', default='12')
3755
conf = self.get_conf('foo=invalid integer')
3756
self.assertEquals(12, conf.get('foo'))
3758
def register_list_option(self, name, default=None, default_from_env=None):
3759
l = config.ListOption(name, help='A list.', default=default,
3760
default_from_env=default_from_env)
3761
self.registry.register(l)
3763
def test_get_default_list_None(self):
3764
self.register_list_option('foo')
3765
conf = self.get_conf('')
3766
self.assertEquals(None, conf.get('foo'))
3768
def test_get_default_list_empty(self):
3769
self.register_list_option('foo', '')
3770
conf = self.get_conf('')
3771
self.assertEquals([], conf.get('foo'))
3773
def test_get_default_list_from_env(self):
3774
self.register_list_option('foo', default_from_env=['FOO'])
3775
self.overrideEnv('FOO', '')
3776
conf = self.get_conf('')
3777
self.assertEquals([], conf.get('foo'))
3779
def test_get_with_list_converter_no_item(self):
3780
self.register_list_option('foo', None)
3781
conf = self.get_conf('foo=,')
3782
self.assertEquals([], conf.get('foo'))
3784
def test_get_with_list_converter_many_items(self):
3785
self.register_list_option('foo', None)
3786
conf = self.get_conf('foo=m,o,r,e')
3787
self.assertEquals(['m', 'o', 'r', 'e'], conf.get('foo'))
3789
def test_get_with_list_converter_embedded_spaces_many_items(self):
3790
self.register_list_option('foo', None)
3791
conf = self.get_conf('foo=" bar", "baz "')
3792
self.assertEquals([' bar', 'baz '], conf.get('foo'))
3794
def test_get_with_list_converter_stripped_spaces_many_items(self):
3795
self.register_list_option('foo', None)
3796
conf = self.get_conf('foo= bar , baz ')
3797
self.assertEquals(['bar', 'baz'], conf.get('foo'))
3800
class TestIterOptionRefs(tests.TestCase):
3801
"""iter_option_refs is a bit unusual, document some cases."""
3803
def assertRefs(self, expected, string):
3804
self.assertEquals(expected, list(config.iter_option_refs(string)))
3806
def test_empty(self):
3807
self.assertRefs([(False, '')], '')
3809
def test_no_refs(self):
3810
self.assertRefs([(False, 'foo bar')], 'foo bar')
3812
def test_single_ref(self):
3813
self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
3815
def test_broken_ref(self):
3816
self.assertRefs([(False, '{foo')], '{foo')
3818
def test_embedded_ref(self):
3819
self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
3822
def test_two_refs(self):
3823
self.assertRefs([(False, ''), (True, '{foo}'),
3824
(False, ''), (True, '{bar}'),
3828
def test_newline_in_refs_are_not_matched(self):
3829
self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
3832
class TestStackExpandOptions(tests.TestCaseWithTransport):
3835
super(TestStackExpandOptions, self).setUp()
3836
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3837
self.registry = config.option_registry
3838
self.conf = build_branch_stack(self)
3840
def assertExpansion(self, expected, string, env=None):
3841
self.assertEquals(expected, self.conf.expand_options(string, env))
3843
def test_no_expansion(self):
3844
self.assertExpansion('foo', 'foo')
3846
def test_expand_default_value(self):
3847
self.conf.store._load_from_string('bar=baz')
3848
self.registry.register(config.Option('foo', default=u'{bar}'))
3849
self.assertEquals('baz', self.conf.get('foo', expand=True))
3851
def test_expand_default_from_env(self):
3852
self.conf.store._load_from_string('bar=baz')
3853
self.registry.register(config.Option('foo', default_from_env=['FOO']))
3854
self.overrideEnv('FOO', '{bar}')
3855
self.assertEquals('baz', self.conf.get('foo', expand=True))
3857
def test_expand_default_on_failed_conversion(self):
3858
self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
3859
self.registry.register(
3860
config.Option('foo', default=u'{bar}',
3861
from_unicode=config.int_from_store))
3862
self.assertEquals(42, self.conf.get('foo', expand=True))
3864
def test_env_adding_options(self):
3865
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3867
def test_env_overriding_options(self):
3868
self.conf.store._load_from_string('foo=baz')
3869
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3871
def test_simple_ref(self):
3872
self.conf.store._load_from_string('foo=xxx')
3873
self.assertExpansion('xxx', '{foo}')
3875
def test_unknown_ref(self):
3876
self.assertRaises(errors.ExpandingUnknownOption,
3877
self.conf.expand_options, '{foo}')
3879
def test_indirect_ref(self):
3880
self.conf.store._load_from_string('''
3884
self.assertExpansion('xxx', '{bar}')
3886
def test_embedded_ref(self):
3887
self.conf.store._load_from_string('''
3891
self.assertExpansion('xxx', '{{bar}}')
3893
def test_simple_loop(self):
3894
self.conf.store._load_from_string('foo={foo}')
3895
self.assertRaises(errors.OptionExpansionLoop,
3896
self.conf.expand_options, '{foo}')
3898
def test_indirect_loop(self):
3899
self.conf.store._load_from_string('''
3903
e = self.assertRaises(errors.OptionExpansionLoop,
3904
self.conf.expand_options, '{foo}')
3905
self.assertEquals('foo->bar->baz', e.refs)
3906
self.assertEquals('{foo}', e.string)
3908
def test_list(self):
3909
self.conf.store._load_from_string('''
3913
list={foo},{bar},{baz}
3915
self.registry.register(
3916
config.ListOption('list'))
3917
self.assertEquals(['start', 'middle', 'end'],
3918
self.conf.get('list', expand=True))
3920
def test_cascading_list(self):
3921
self.conf.store._load_from_string('''
3927
self.registry.register(
3928
config.ListOption('list'))
3929
self.assertEquals(['start', 'middle', 'end'],
3930
self.conf.get('list', expand=True))
3932
def test_pathologically_hidden_list(self):
3933
self.conf.store._load_from_string('''
3939
hidden={start}{middle}{end}
3941
# What matters is what the registration says, the conversion happens
3942
# only after all expansions have been performed
3943
self.registry.register(config.ListOption('hidden'))
3944
self.assertEquals(['bin', 'go'],
3945
self.conf.get('hidden', expand=True))
3948
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3951
super(TestStackCrossSectionsExpand, self).setUp()
3953
def get_config(self, location, string):
3956
# Since we don't save the config we won't strictly require to inherit
3957
# from TestCaseInTempDir, but an error occurs so quickly...
3958
c = config.LocationStack(location)
3959
c.store._load_from_string(string)
3962
def test_dont_cross_unrelated_section(self):
3963
c = self.get_config('/another/branch/path','''
3968
[/another/branch/path]
3971
self.assertRaises(errors.ExpandingUnknownOption,
3972
c.get, 'bar', expand=True)
3974
def test_cross_related_sections(self):
3975
c = self.get_config('/project/branch/path','''
3979
[/project/branch/path]
3982
self.assertEquals('quux', c.get('bar', expand=True))
3985
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
3987
def test_cross_global_locations(self):
3988
l_store = config.LocationStore()
3989
l_store._load_from_string('''
3995
g_store = config.GlobalStore()
3996
g_store._load_from_string('''
4002
stack = config.LocationStack('/branch')
4003
self.assertEquals('glob-bar', stack.get('lbar', expand=True))
4004
self.assertEquals('loc-foo', stack.get('gfoo', expand=True))
4007
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
4009
def test_expand_locals_empty(self):
4010
l_store = config.LocationStore()
4011
l_store._load_from_string('''
4012
[/home/user/project]
4017
stack = config.LocationStack('/home/user/project/')
4018
self.assertEquals('', stack.get('base', expand=True))
4019
self.assertEquals('', stack.get('rel', expand=True))
4021
def test_expand_basename_locally(self):
4022
l_store = config.LocationStore()
4023
l_store._load_from_string('''
4024
[/home/user/project]
4028
stack = config.LocationStack('/home/user/project/branch')
4029
self.assertEquals('branch', stack.get('bfoo', expand=True))
4031
def test_expand_basename_locally_longer_path(self):
4032
l_store = config.LocationStore()
4033
l_store._load_from_string('''
4038
stack = config.LocationStack('/home/user/project/dir/branch')
4039
self.assertEquals('branch', stack.get('bfoo', expand=True))
4041
def test_expand_relpath_locally(self):
4042
l_store = config.LocationStore()
4043
l_store._load_from_string('''
4044
[/home/user/project]
4045
lfoo = loc-foo/{relpath}
4048
stack = config.LocationStack('/home/user/project/branch')
4049
self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
4051
def test_expand_relpath_unknonw_in_global(self):
4052
g_store = config.GlobalStore()
4053
g_store._load_from_string('''
4058
stack = config.LocationStack('/home/user/project/branch')
4059
self.assertRaises(errors.ExpandingUnknownOption,
4060
stack.get, 'gfoo', expand=True)
4062
def test_expand_local_option_locally(self):
4063
l_store = config.LocationStore()
4064
l_store._load_from_string('''
4065
[/home/user/project]
4066
lfoo = loc-foo/{relpath}
4070
g_store = config.GlobalStore()
4071
g_store._load_from_string('''
4077
stack = config.LocationStack('/home/user/project/branch')
4078
self.assertEquals('glob-bar', stack.get('lbar', expand=True))
4079
self.assertEquals('loc-foo/branch', stack.get('gfoo', expand=True))
4081
def test_locals_dont_leak(self):
4082
"""Make sure we chose the right local in presence of several sections.
4084
l_store = config.LocationStore()
4085
l_store._load_from_string('''
4087
lfoo = loc-foo/{relpath}
4088
[/home/user/project]
4089
lfoo = loc-foo/{relpath}
4092
stack = config.LocationStack('/home/user/project/branch')
4093
self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
4094
stack = config.LocationStack('/home/user/bar/baz')
4095
self.assertEquals('loc-foo/bar/baz', stack.get('lfoo', expand=True))
4099
class TestStackSet(TestStackWithTransport):
4101
def test_simple_set(self):
4102
conf = self.get_stack(self)
4103
self.assertEquals(None, conf.get('foo'))
4104
conf.set('foo', 'baz')
4105
# Did we get it back ?
4106
self.assertEquals('baz', conf.get('foo'))
4108
def test_set_creates_a_new_section(self):
4109
conf = self.get_stack(self)
4110
conf.set('foo', 'baz')
4111
self.assertEquals, 'baz', conf.get('foo')
4113
def test_set_hook(self):
4117
config.ConfigHooks.install_named_hook('set', hook, None)
4118
self.assertLength(0, calls)
4119
conf = self.get_stack(self)
4120
conf.set('foo', 'bar')
4121
self.assertLength(1, calls)
4122
self.assertEquals((conf, 'foo', 'bar'), calls[0])
4125
class TestStackRemove(TestStackWithTransport):
4127
def test_remove_existing(self):
4128
conf = self.get_stack(self)
4129
conf.set('foo', 'bar')
4130
self.assertEquals('bar', conf.get('foo'))
4132
# Did we get it back ?
4133
self.assertEquals(None, conf.get('foo'))
4135
def test_remove_unknown(self):
4136
conf = self.get_stack(self)
4137
self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
4139
def test_remove_hook(self):
4143
config.ConfigHooks.install_named_hook('remove', hook, None)
4144
self.assertLength(0, calls)
4145
conf = self.get_stack(self)
4146
conf.set('foo', 'bar')
4148
self.assertLength(1, calls)
4149
self.assertEquals((conf, 'foo'), calls[0])
4152
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
4155
super(TestConfigGetOptions, self).setUp()
4156
create_configs(self)
4158
def test_no_variable(self):
4159
# Using branch should query branch, locations and bazaar
4160
self.assertOptions([], self.branch_config)
4162
def test_option_in_bazaar(self):
4163
self.bazaar_config.set_user_option('file', 'bazaar')
4164
self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
4167
def test_option_in_locations(self):
4168
self.locations_config.set_user_option('file', 'locations')
4170
[('file', 'locations', self.tree.basedir, 'locations')],
4171
self.locations_config)
4173
def test_option_in_branch(self):
4174
self.branch_config.set_user_option('file', 'branch')
4175
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
4178
def test_option_in_bazaar_and_branch(self):
4179
self.bazaar_config.set_user_option('file', 'bazaar')
4180
self.branch_config.set_user_option('file', 'branch')
4181
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
4182
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
4185
def test_option_in_branch_and_locations(self):
4186
# Hmm, locations override branch :-/
4187
self.locations_config.set_user_option('file', 'locations')
4188
self.branch_config.set_user_option('file', 'branch')
4190
[('file', 'locations', self.tree.basedir, 'locations'),
4191
('file', 'branch', 'DEFAULT', 'branch'),],
4194
def test_option_in_bazaar_locations_and_branch(self):
4195
self.bazaar_config.set_user_option('file', 'bazaar')
4196
self.locations_config.set_user_option('file', 'locations')
4197
self.branch_config.set_user_option('file', 'branch')
4199
[('file', 'locations', self.tree.basedir, 'locations'),
4200
('file', 'branch', 'DEFAULT', 'branch'),
4201
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
4205
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
4208
super(TestConfigRemoveOption, self).setUp()
4209
create_configs_with_file_option(self)
4211
def test_remove_in_locations(self):
4212
self.locations_config.remove_user_option('file', self.tree.basedir)
4214
[('file', 'branch', 'DEFAULT', 'branch'),
4215
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
4218
def test_remove_in_branch(self):
4219
self.branch_config.remove_user_option('file')
4221
[('file', 'locations', self.tree.basedir, 'locations'),
4222
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
4225
def test_remove_in_bazaar(self):
4226
self.bazaar_config.remove_user_option('file')
4228
[('file', 'locations', self.tree.basedir, 'locations'),
4229
('file', 'branch', 'DEFAULT', 'branch'),],
4233
class TestConfigGetSections(tests.TestCaseWithTransport):
4236
super(TestConfigGetSections, self).setUp()
4237
create_configs(self)
4239
def assertSectionNames(self, expected, conf, name=None):
4240
"""Check which sections are returned for a given config.
4242
If fallback configurations exist their sections can be included.
4244
:param expected: A list of section names.
4246
:param conf: The configuration that will be queried.
4248
:param name: An optional section name that will be passed to
4251
sections = list(conf._get_sections(name))
4252
self.assertLength(len(expected), sections)
4253
self.assertEqual(expected, [name for name, _, _ in sections])
4255
def test_bazaar_default_section(self):
4256
self.assertSectionNames(['DEFAULT'], self.bazaar_config)
4258
def test_locations_default_section(self):
4259
# No sections are defined in an empty file
4260
self.assertSectionNames([], self.locations_config)
4262
def test_locations_named_section(self):
4263
self.locations_config.set_user_option('file', 'locations')
4264
self.assertSectionNames([self.tree.basedir], self.locations_config)
4266
def test_locations_matching_sections(self):
4267
loc_config = self.locations_config
4268
loc_config.set_user_option('file', 'locations')
4269
# We need to cheat a bit here to create an option in sections above and
4270
# below the 'location' one.
4271
parser = loc_config._get_parser()
4272
# locations.cong deals with '/' ignoring native os.sep
4273
location_names = self.tree.basedir.split('/')
4274
parent = '/'.join(location_names[:-1])
4275
child = '/'.join(location_names + ['child'])
4277
parser[parent]['file'] = 'parent'
4279
parser[child]['file'] = 'child'
4280
self.assertSectionNames([self.tree.basedir, parent], loc_config)
4282
def test_branch_data_default_section(self):
4283
self.assertSectionNames([None],
4284
self.branch_config._get_branch_data_config())
4286
def test_branch_default_sections(self):
4287
# No sections are defined in an empty locations file
4288
self.assertSectionNames([None, 'DEFAULT'],
4290
# Unless we define an option
4291
self.branch_config._get_location_config().set_user_option(
4292
'file', 'locations')
4293
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
4296
def test_bazaar_named_section(self):
4297
# We need to cheat as the API doesn't give direct access to sections
4298
# other than DEFAULT.
4299
self.bazaar_config.set_alias('bazaar', 'bzr')
4300
self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
1315
4303
class TestAuthenticationConfigFile(tests.TestCase):
1316
4304
"""Test the authentication.conf file matching"""