1471
2074
self.assertIs(None, bzrdir_config.get_default_stack_on())
2077
class TestOldConfigHooks(tests.TestCaseWithTransport):
2080
super(TestOldConfigHooks, self).setUp()
2081
create_configs_with_file_option(self)
2083
def assertGetHook(self, conf, name, value):
2087
config.OldConfigHooks.install_named_hook('get', hook, None)
2089
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2090
self.assertLength(0, calls)
2091
actual_value = conf.get_user_option(name)
2092
self.assertEquals(value, actual_value)
2093
self.assertLength(1, calls)
2094
self.assertEquals((conf, name, value), calls[0])
2096
def test_get_hook_bazaar(self):
2097
self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
2099
def test_get_hook_locations(self):
2100
self.assertGetHook(self.locations_config, 'file', 'locations')
2102
def test_get_hook_branch(self):
2103
# Since locations masks branch, we define a different option
2104
self.branch_config.set_user_option('file2', 'branch')
2105
self.assertGetHook(self.branch_config, 'file2', 'branch')
2107
def assertSetHook(self, conf, name, value):
2111
config.OldConfigHooks.install_named_hook('set', hook, None)
2113
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2114
self.assertLength(0, calls)
2115
conf.set_user_option(name, value)
2116
self.assertLength(1, calls)
2117
# We can't assert the conf object below as different configs use
2118
# different means to implement set_user_option and we care only about
2120
self.assertEquals((name, value), calls[0][1:])
2122
def test_set_hook_bazaar(self):
2123
self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
2125
def test_set_hook_locations(self):
2126
self.assertSetHook(self.locations_config, 'foo', 'locations')
2128
def test_set_hook_branch(self):
2129
self.assertSetHook(self.branch_config, 'foo', 'branch')
2131
def assertRemoveHook(self, conf, name, section_name=None):
2135
config.OldConfigHooks.install_named_hook('remove', hook, None)
2137
config.OldConfigHooks.uninstall_named_hook, 'remove', None)
2138
self.assertLength(0, calls)
2139
conf.remove_user_option(name, section_name)
2140
self.assertLength(1, calls)
2141
# We can't assert the conf object below as different configs use
2142
# different means to implement remove_user_option and we care only about
2144
self.assertEquals((name,), calls[0][1:])
2146
def test_remove_hook_bazaar(self):
2147
self.assertRemoveHook(self.bazaar_config, 'file')
2149
def test_remove_hook_locations(self):
2150
self.assertRemoveHook(self.locations_config, 'file',
2151
self.locations_config.location)
2153
def test_remove_hook_branch(self):
2154
self.assertRemoveHook(self.branch_config, 'file')
2156
def assertLoadHook(self, name, conf_class, *conf_args):
2160
config.OldConfigHooks.install_named_hook('load', hook, None)
2162
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2163
self.assertLength(0, calls)
2165
conf = conf_class(*conf_args)
2166
# Access an option to trigger a load
2167
conf.get_user_option(name)
2168
self.assertLength(1, calls)
2169
# Since we can't assert about conf, we just use the number of calls ;-/
2171
def test_load_hook_bazaar(self):
2172
self.assertLoadHook('file', config.GlobalConfig)
2174
def test_load_hook_locations(self):
2175
self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
2177
def test_load_hook_branch(self):
2178
self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
2180
def assertSaveHook(self, conf):
2184
config.OldConfigHooks.install_named_hook('save', hook, None)
2186
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2187
self.assertLength(0, calls)
2188
# Setting an option triggers a save
2189
conf.set_user_option('foo', 'bar')
2190
self.assertLength(1, calls)
2191
# Since we can't assert about conf, we just use the number of calls ;-/
2193
def test_save_hook_bazaar(self):
2194
self.assertSaveHook(self.bazaar_config)
2196
def test_save_hook_locations(self):
2197
self.assertSaveHook(self.locations_config)
2199
def test_save_hook_branch(self):
2200
self.assertSaveHook(self.branch_config)
2203
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
2204
"""Tests config hooks for remote configs.
2206
No tests for the remove hook as this is not implemented there.
2210
super(TestOldConfigHooksForRemote, self).setUp()
2211
self.transport_server = test_server.SmartTCPServer_for_testing
2212
create_configs_with_file_option(self)
2214
def assertGetHook(self, conf, name, value):
2218
config.OldConfigHooks.install_named_hook('get', hook, None)
2220
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2221
self.assertLength(0, calls)
2222
actual_value = conf.get_option(name)
2223
self.assertEquals(value, actual_value)
2224
self.assertLength(1, calls)
2225
self.assertEquals((conf, name, value), calls[0])
2227
def test_get_hook_remote_branch(self):
2228
remote_branch = branch.Branch.open(self.get_url('tree'))
2229
self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2231
def test_get_hook_remote_bzrdir(self):
2232
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2233
conf = remote_bzrdir._get_config()
2234
conf.set_option('remotedir', 'file')
2235
self.assertGetHook(conf, 'file', 'remotedir')
2237
def assertSetHook(self, conf, name, value):
2241
config.OldConfigHooks.install_named_hook('set', hook, None)
2243
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2244
self.assertLength(0, calls)
2245
conf.set_option(value, name)
2246
self.assertLength(1, calls)
2247
# We can't assert the conf object below as different configs use
2248
# different means to implement set_user_option and we care only about
2250
self.assertEquals((name, value), calls[0][1:])
2252
def test_set_hook_remote_branch(self):
2253
remote_branch = branch.Branch.open(self.get_url('tree'))
2254
self.addCleanup(remote_branch.lock_write().unlock)
2255
self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
2257
def test_set_hook_remote_bzrdir(self):
2258
remote_branch = branch.Branch.open(self.get_url('tree'))
2259
self.addCleanup(remote_branch.lock_write().unlock)
2260
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2261
self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2263
def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2267
config.OldConfigHooks.install_named_hook('load', hook, None)
2269
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2270
self.assertLength(0, calls)
2272
conf = conf_class(*conf_args)
2273
# Access an option to trigger a load
2274
conf.get_option(name)
2275
self.assertLength(expected_nb_calls, calls)
2276
# Since we can't assert about conf, we just use the number of calls ;-/
2278
def test_load_hook_remote_branch(self):
2279
remote_branch = branch.Branch.open(self.get_url('tree'))
2280
self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2282
def test_load_hook_remote_bzrdir(self):
2283
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2284
# The config file doesn't exist, set an option to force its creation
2285
conf = remote_bzrdir._get_config()
2286
conf.set_option('remotedir', 'file')
2287
# We get one call for the server and one call for the client, this is
2288
# caused by the differences in implementations betwen
2289
# SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
2290
# SmartServerBranchGetConfigFile (in smart/branch.py)
2291
self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
2293
def assertSaveHook(self, conf):
2297
config.OldConfigHooks.install_named_hook('save', hook, None)
2299
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2300
self.assertLength(0, calls)
2301
# Setting an option triggers a save
2302
conf.set_option('foo', 'bar')
2303
self.assertLength(1, calls)
2304
# Since we can't assert about conf, we just use the number of calls ;-/
2306
def test_save_hook_remote_branch(self):
2307
remote_branch = branch.Branch.open(self.get_url('tree'))
2308
self.addCleanup(remote_branch.lock_write().unlock)
2309
self.assertSaveHook(remote_branch._get_config())
2311
def test_save_hook_remote_bzrdir(self):
2312
remote_branch = branch.Branch.open(self.get_url('tree'))
2313
self.addCleanup(remote_branch.lock_write().unlock)
2314
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2315
self.assertSaveHook(remote_bzrdir._get_config())
2318
class TestOption(tests.TestCase):
2320
def test_default_value(self):
2321
opt = config.Option('foo', default='bar')
2322
self.assertEquals('bar', opt.get_default())
2324
def test_callable_default_value(self):
2325
def bar_as_unicode():
2327
opt = config.Option('foo', default=bar_as_unicode)
2328
self.assertEquals('bar', opt.get_default())
2330
def test_default_value_from_env(self):
2331
opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2332
self.overrideEnv('FOO', 'quux')
2333
# Env variable provides a default taking over the option one
2334
self.assertEquals('quux', opt.get_default())
2336
def test_first_default_value_from_env_wins(self):
2337
opt = config.Option('foo', default='bar',
2338
default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2339
self.overrideEnv('FOO', 'foo')
2340
self.overrideEnv('BAZ', 'baz')
2341
# The first env var set wins
2342
self.assertEquals('foo', opt.get_default())
2344
def test_not_supported_list_default_value(self):
2345
self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2347
def test_not_supported_object_default_value(self):
2348
self.assertRaises(AssertionError, config.Option, 'foo',
2351
def test_not_supported_callable_default_value_not_unicode(self):
2352
def bar_not_unicode():
2354
opt = config.Option('foo', default=bar_not_unicode)
2355
self.assertRaises(AssertionError, opt.get_default)
2358
class TestOptionConverterMixin(object):
2360
def assertConverted(self, expected, opt, value):
2361
self.assertEquals(expected, opt.convert_from_unicode(value))
2363
def assertWarns(self, opt, value):
2366
warnings.append(args[0] % args[1:])
2367
self.overrideAttr(trace, 'warning', warning)
2368
self.assertEquals(None, opt.convert_from_unicode(value))
2369
self.assertLength(1, warnings)
2371
'Value "%s" is not valid for "%s"' % (value, opt.name),
2374
def assertErrors(self, opt, value):
2375
self.assertRaises(errors.ConfigOptionValueError,
2376
opt.convert_from_unicode, value)
2378
def assertConvertInvalid(self, opt, invalid_value):
2380
self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2381
opt.invalid = 'warning'
2382
self.assertWarns(opt, invalid_value)
2383
opt.invalid = 'error'
2384
self.assertErrors(opt, invalid_value)
2387
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2389
def get_option(self):
2390
return config.Option('foo', help='A boolean.',
2391
from_unicode=config.bool_from_store)
2393
def test_convert_invalid(self):
2394
opt = self.get_option()
2395
# A string that is not recognized as a boolean
2396
self.assertConvertInvalid(opt, u'invalid-boolean')
2397
# A list of strings is never recognized as a boolean
2398
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2400
def test_convert_valid(self):
2401
opt = self.get_option()
2402
self.assertConverted(True, opt, u'True')
2403
self.assertConverted(True, opt, u'1')
2404
self.assertConverted(False, opt, u'False')
2407
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2409
def get_option(self):
2410
return config.Option('foo', help='An integer.',
2411
from_unicode=config.int_from_store)
2413
def test_convert_invalid(self):
2414
opt = self.get_option()
2415
# A string that is not recognized as an integer
2416
self.assertConvertInvalid(opt, u'forty-two')
2417
# A list of strings is never recognized as an integer
2418
self.assertConvertInvalid(opt, [u'a', u'list'])
2420
def test_convert_valid(self):
2421
opt = self.get_option()
2422
self.assertConverted(16, opt, u'16')
2425
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2427
def get_option(self):
2428
return config.Option('foo', help='A list.',
2429
from_unicode=config.list_from_store)
2431
def test_convert_invalid(self):
2432
# No string is invalid as all forms can be converted to a list
2435
def test_convert_valid(self):
2436
opt = self.get_option()
2437
# An empty string is an empty list
2438
self.assertConverted([], opt, '') # Using a bare str() just in case
2439
self.assertConverted([], opt, u'')
2441
self.assertConverted([u'True'], opt, u'True')
2443
self.assertConverted([u'42'], opt, u'42')
2445
self.assertConverted([u'bar'], opt, u'bar')
2446
# A list remains a list (configObj will turn a string containing commas
2447
# into a list, but that's not what we're testing here)
2448
self.assertConverted([u'foo', u'1', u'True'],
2449
opt, [u'foo', u'1', u'True'])
2452
class TestOptionConverterMixin(object):
2454
def assertConverted(self, expected, opt, value):
2455
self.assertEquals(expected, opt.convert_from_unicode(value))
2457
def assertWarns(self, opt, value):
2460
warnings.append(args[0] % args[1:])
2461
self.overrideAttr(trace, 'warning', warning)
2462
self.assertEquals(None, opt.convert_from_unicode(value))
2463
self.assertLength(1, warnings)
2465
'Value "%s" is not valid for "%s"' % (value, opt.name),
2468
def assertErrors(self, opt, value):
2469
self.assertRaises(errors.ConfigOptionValueError,
2470
opt.convert_from_unicode, value)
2472
def assertConvertInvalid(self, opt, invalid_value):
2474
self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2475
opt.invalid = 'warning'
2476
self.assertWarns(opt, invalid_value)
2477
opt.invalid = 'error'
2478
self.assertErrors(opt, invalid_value)
2481
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2483
def get_option(self):
2484
return config.Option('foo', help='A boolean.',
2485
from_unicode=config.bool_from_store)
2487
def test_convert_invalid(self):
2488
opt = self.get_option()
2489
# A string that is not recognized as a boolean
2490
self.assertConvertInvalid(opt, u'invalid-boolean')
2491
# A list of strings is never recognized as a boolean
2492
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2494
def test_convert_valid(self):
2495
opt = self.get_option()
2496
self.assertConverted(True, opt, u'True')
2497
self.assertConverted(True, opt, u'1')
2498
self.assertConverted(False, opt, u'False')
2501
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2503
def get_option(self):
2504
return config.Option('foo', help='An integer.',
2505
from_unicode=config.int_from_store)
2507
def test_convert_invalid(self):
2508
opt = self.get_option()
2509
# A string that is not recognized as an integer
2510
self.assertConvertInvalid(opt, u'forty-two')
2511
# A list of strings is never recognized as an integer
2512
self.assertConvertInvalid(opt, [u'a', u'list'])
2514
def test_convert_valid(self):
2515
opt = self.get_option()
2516
self.assertConverted(16, opt, u'16')
2519
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2521
def get_option(self):
2522
return config.Option('foo', help='A list.',
2523
from_unicode=config.list_from_store)
2525
def test_convert_invalid(self):
2526
opt = self.get_option()
2527
# We don't even try to convert a list into a list, we only expect
2529
self.assertConvertInvalid(opt, [1])
2530
# No string is invalid as all forms can be converted to a list
2532
def test_convert_valid(self):
2533
opt = self.get_option()
2534
# An empty string is an empty list
2535
self.assertConverted([], opt, '') # Using a bare str() just in case
2536
self.assertConverted([], opt, u'')
2538
self.assertConverted([u'True'], opt, u'True')
2540
self.assertConverted([u'42'], opt, u'42')
2542
self.assertConverted([u'bar'], opt, u'bar')
2545
class TestOptionRegistry(tests.TestCase):
2548
super(TestOptionRegistry, self).setUp()
2549
# Always start with an empty registry
2550
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2551
self.registry = config.option_registry
2553
def test_register(self):
2554
opt = config.Option('foo')
2555
self.registry.register(opt)
2556
self.assertIs(opt, self.registry.get('foo'))
2558
def test_registered_help(self):
2559
opt = config.Option('foo', help='A simple option')
2560
self.registry.register(opt)
2561
self.assertEquals('A simple option', self.registry.get_help('foo'))
2563
lazy_option = config.Option('lazy_foo', help='Lazy help')
2565
def test_register_lazy(self):
2566
self.registry.register_lazy('lazy_foo', self.__module__,
2567
'TestOptionRegistry.lazy_option')
2568
self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2570
def test_registered_lazy_help(self):
2571
self.registry.register_lazy('lazy_foo', self.__module__,
2572
'TestOptionRegistry.lazy_option')
2573
self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2576
class TestRegisteredOptions(tests.TestCase):
2577
"""All registered options should verify some constraints."""
2579
scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2580
in config.option_registry.iteritems()]
2583
super(TestRegisteredOptions, self).setUp()
2584
self.registry = config.option_registry
2586
def test_proper_name(self):
2587
# An option should be registered under its own name, this can't be
2588
# checked at registration time for the lazy ones.
2589
self.assertEquals(self.option_name, self.option.name)
2591
def test_help_is_set(self):
2592
option_help = self.registry.get_help(self.option_name)
2593
self.assertNotEquals(None, option_help)
2594
# Come on, think about the user, he really wants to know what the
2596
self.assertIsNot(None, option_help)
2597
self.assertNotEquals('', option_help)
2600
class TestSection(tests.TestCase):
2602
# FIXME: Parametrize so that all sections produced by Stores run these
2603
# tests -- vila 2011-04-01
2605
def test_get_a_value(self):
2606
a_dict = dict(foo='bar')
2607
section = config.Section('myID', a_dict)
2608
self.assertEquals('bar', section.get('foo'))
2610
def test_get_unknown_option(self):
2612
section = config.Section(None, a_dict)
2613
self.assertEquals('out of thin air',
2614
section.get('foo', 'out of thin air'))
2616
def test_options_is_shared(self):
2618
section = config.Section(None, a_dict)
2619
self.assertIs(a_dict, section.options)
2622
class TestMutableSection(tests.TestCase):
2624
scenarios = [('mutable',
2626
lambda opts: config.MutableSection('myID', opts)},),
2630
a_dict = dict(foo='bar')
2631
section = self.get_section(a_dict)
2632
section.set('foo', 'new_value')
2633
self.assertEquals('new_value', section.get('foo'))
2634
# The change appears in the shared section
2635
self.assertEquals('new_value', a_dict.get('foo'))
2636
# We keep track of the change
2637
self.assertTrue('foo' in section.orig)
2638
self.assertEquals('bar', section.orig.get('foo'))
2640
def test_set_preserve_original_once(self):
2641
a_dict = dict(foo='bar')
2642
section = self.get_section(a_dict)
2643
section.set('foo', 'first_value')
2644
section.set('foo', 'second_value')
2645
# We keep track of the original value
2646
self.assertTrue('foo' in section.orig)
2647
self.assertEquals('bar', section.orig.get('foo'))
2649
def test_remove(self):
2650
a_dict = dict(foo='bar')
2651
section = self.get_section(a_dict)
2652
section.remove('foo')
2653
# We get None for unknown options via the default value
2654
self.assertEquals(None, section.get('foo'))
2655
# Or we just get the default value
2656
self.assertEquals('unknown', section.get('foo', 'unknown'))
2657
self.assertFalse('foo' in section.options)
2658
# We keep track of the deletion
2659
self.assertTrue('foo' in section.orig)
2660
self.assertEquals('bar', section.orig.get('foo'))
2662
def test_remove_new_option(self):
2664
section = self.get_section(a_dict)
2665
section.set('foo', 'bar')
2666
section.remove('foo')
2667
self.assertFalse('foo' in section.options)
2668
# The option didn't exist initially so it we need to keep track of it
2669
# with a special value
2670
self.assertTrue('foo' in section.orig)
2671
self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2674
class TestCommandLineStore(tests.TestCase):
2677
super(TestCommandLineStore, self).setUp()
2678
self.store = config.CommandLineStore()
2680
def get_section(self):
2681
"""Get the unique section for the command line overrides."""
2682
sections = list(self.store.get_sections())
2683
self.assertLength(1, sections)
2684
store, section = sections[0]
2685
self.assertEquals(self.store, store)
2688
def test_no_override(self):
2689
self.store._from_cmdline([])
2690
section = self.get_section()
2691
self.assertLength(0, list(section.iter_option_names()))
2693
def test_simple_override(self):
2694
self.store._from_cmdline(['a=b'])
2695
section = self.get_section()
2696
self.assertEqual('b', section.get('a'))
2698
def test_list_override(self):
2699
self.store._from_cmdline(['l=1,2,3'])
2700
val = self.get_section().get('l')
2701
self.assertEqual('1,2,3', val)
2702
# Reminder: lists should be registered as such explicitely, otherwise
2703
# the conversion needs to be done afterwards.
2704
self.assertEqual(['1', '2', '3'], config.list_from_store(val))
2706
def test_multiple_overrides(self):
2707
self.store._from_cmdline(['a=b', 'x=y'])
2708
section = self.get_section()
2709
self.assertEquals('b', section.get('a'))
2710
self.assertEquals('y', section.get('x'))
2712
def test_wrong_syntax(self):
2713
self.assertRaises(errors.BzrCommandError,
2714
self.store._from_cmdline, ['a=b', 'c'])
2717
class TestStore(tests.TestCaseWithTransport):
2719
def assertSectionContent(self, expected, (store, section)):
2720
"""Assert that some options have the proper values in a section."""
2721
expected_name, expected_options = expected
2722
self.assertEquals(expected_name, section.id)
2725
dict([(k, section.get(k)) for k in expected_options.keys()]))
2728
class TestReadonlyStore(TestStore):
2730
scenarios = [(key, {'get_store': builder}) for key, builder
2731
in config.test_store_builder_registry.iteritems()]
2733
def test_building_delays_load(self):
2734
store = self.get_store(self)
2735
self.assertEquals(False, store.is_loaded())
2736
store._load_from_string('')
2737
self.assertEquals(True, store.is_loaded())
2739
def test_get_no_sections_for_empty(self):
2740
store = self.get_store(self)
2741
store._load_from_string('')
2742
self.assertEquals([], list(store.get_sections()))
2744
def test_get_default_section(self):
2745
store = self.get_store(self)
2746
store._load_from_string('foo=bar')
2747
sections = list(store.get_sections())
2748
self.assertLength(1, sections)
2749
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2751
def test_get_named_section(self):
2752
store = self.get_store(self)
2753
store._load_from_string('[baz]\nfoo=bar')
2754
sections = list(store.get_sections())
2755
self.assertLength(1, sections)
2756
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2758
def test_load_from_string_fails_for_non_empty_store(self):
2759
store = self.get_store(self)
2760
store._load_from_string('foo=bar')
2761
self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2764
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2765
"""Simulate loading a config store with content of various encodings.
2767
All files produced by bzr are in utf8 content.
2769
Users may modify them manually and end up with a file that can't be
2770
loaded. We need to issue proper error messages in this case.
2773
invalid_utf8_char = '\xff'
2775
def test_load_utf8(self):
2776
"""Ensure we can load an utf8-encoded file."""
2777
t = self.get_transport()
2778
# From http://pad.lv/799212
2779
unicode_user = u'b\N{Euro Sign}ar'
2780
unicode_content = u'user=%s' % (unicode_user,)
2781
utf8_content = unicode_content.encode('utf8')
2782
# Store the raw content in the config file
2783
t.put_bytes('foo.conf', utf8_content)
2784
store = config.TransportIniFileStore(t, 'foo.conf')
2786
stack = config.Stack([store.get_sections], store)
2787
self.assertEquals(unicode_user, stack.get('user'))
2789
def test_load_non_ascii(self):
2790
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2791
t = self.get_transport()
2792
t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2793
store = config.TransportIniFileStore(t, 'foo.conf')
2794
self.assertRaises(errors.ConfigContentError, store.load)
2796
def test_load_erroneous_content(self):
2797
"""Ensure we display a proper error on content that can't be parsed."""
2798
t = self.get_transport()
2799
t.put_bytes('foo.conf', '[open_section\n')
2800
store = config.TransportIniFileStore(t, 'foo.conf')
2801
self.assertRaises(errors.ParseConfigError, store.load)
2803
def test_load_permission_denied(self):
2804
"""Ensure we get warned when trying to load an inaccessible file."""
2807
warnings.append(args[0] % args[1:])
2808
self.overrideAttr(trace, 'warning', warning)
2810
t = self.get_transport()
2812
def get_bytes(relpath):
2813
raise errors.PermissionDenied(relpath, "")
2814
t.get_bytes = get_bytes
2815
store = config.TransportIniFileStore(t, 'foo.conf')
2816
self.assertRaises(errors.PermissionDenied, store.load)
2819
[u'Permission denied while trying to load configuration store %s.'
2820
% store.external_url()])
2823
class TestIniConfigContent(tests.TestCaseWithTransport):
2824
"""Simulate loading a IniBasedConfig with content of various encodings.
2826
All files produced by bzr are in utf8 content.
2828
Users may modify them manually and end up with a file that can't be
2829
loaded. We need to issue proper error messages in this case.
2832
invalid_utf8_char = '\xff'
2834
def test_load_utf8(self):
2835
"""Ensure we can load an utf8-encoded file."""
2836
# From http://pad.lv/799212
2837
unicode_user = u'b\N{Euro Sign}ar'
2838
unicode_content = u'user=%s' % (unicode_user,)
2839
utf8_content = unicode_content.encode('utf8')
2840
# Store the raw content in the config file
2841
with open('foo.conf', 'wb') as f:
2842
f.write(utf8_content)
2843
conf = config.IniBasedConfig(file_name='foo.conf')
2844
self.assertEquals(unicode_user, conf.get_user_option('user'))
2846
def test_load_badly_encoded_content(self):
2847
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2848
with open('foo.conf', 'wb') as f:
2849
f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2850
conf = config.IniBasedConfig(file_name='foo.conf')
2851
self.assertRaises(errors.ConfigContentError, conf._get_parser)
2853
def test_load_erroneous_content(self):
2854
"""Ensure we display a proper error on content that can't be parsed."""
2855
with open('foo.conf', 'wb') as f:
2856
f.write('[open_section\n')
2857
conf = config.IniBasedConfig(file_name='foo.conf')
2858
self.assertRaises(errors.ParseConfigError, conf._get_parser)
2861
class TestMutableStore(TestStore):
2863
scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2864
in config.test_store_builder_registry.iteritems()]
2867
super(TestMutableStore, self).setUp()
2868
self.transport = self.get_transport()
2870
def has_store(self, store):
2871
store_basename = urlutils.relative_url(self.transport.external_url(),
2872
store.external_url())
2873
return self.transport.has(store_basename)
2875
def test_save_empty_creates_no_file(self):
2876
# FIXME: There should be a better way than relying on the test
2877
# parametrization to identify branch.conf -- vila 2011-0526
2878
if self.store_id in ('branch', 'remote_branch'):
2879
raise tests.TestNotApplicable(
2880
'branch.conf is *always* created when a branch is initialized')
2881
store = self.get_store(self)
2883
self.assertEquals(False, self.has_store(store))
2885
def test_save_emptied_succeeds(self):
2886
store = self.get_store(self)
2887
store._load_from_string('foo=bar\n')
2888
section = store.get_mutable_section(None)
2889
section.remove('foo')
2891
self.assertEquals(True, self.has_store(store))
2892
modified_store = self.get_store(self)
2893
sections = list(modified_store.get_sections())
2894
self.assertLength(0, sections)
2896
def test_save_with_content_succeeds(self):
2897
# FIXME: There should be a better way than relying on the test
2898
# parametrization to identify branch.conf -- vila 2011-0526
2899
if self.store_id in ('branch', 'remote_branch'):
2900
raise tests.TestNotApplicable(
2901
'branch.conf is *always* created when a branch is initialized')
2902
store = self.get_store(self)
2903
store._load_from_string('foo=bar\n')
2904
self.assertEquals(False, self.has_store(store))
2906
self.assertEquals(True, self.has_store(store))
2907
modified_store = self.get_store(self)
2908
sections = list(modified_store.get_sections())
2909
self.assertLength(1, sections)
2910
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2912
def test_set_option_in_empty_store(self):
2913
store = self.get_store(self)
2914
section = store.get_mutable_section(None)
2915
section.set('foo', 'bar')
2917
modified_store = self.get_store(self)
2918
sections = list(modified_store.get_sections())
2919
self.assertLength(1, sections)
2920
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2922
def test_set_option_in_default_section(self):
2923
store = self.get_store(self)
2924
store._load_from_string('')
2925
section = store.get_mutable_section(None)
2926
section.set('foo', 'bar')
2928
modified_store = self.get_store(self)
2929
sections = list(modified_store.get_sections())
2930
self.assertLength(1, sections)
2931
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2933
def test_set_option_in_named_section(self):
2934
store = self.get_store(self)
2935
store._load_from_string('')
2936
section = store.get_mutable_section('baz')
2937
section.set('foo', 'bar')
2939
modified_store = self.get_store(self)
2940
sections = list(modified_store.get_sections())
2941
self.assertLength(1, sections)
2942
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2944
def test_load_hook(self):
2945
# We first needs to ensure that the store exists
2946
store = self.get_store(self)
2947
section = store.get_mutable_section('baz')
2948
section.set('foo', 'bar')
2950
# Now we can try to load it
2951
store = self.get_store(self)
2955
config.ConfigHooks.install_named_hook('load', hook, None)
2956
self.assertLength(0, calls)
2958
self.assertLength(1, calls)
2959
self.assertEquals((store,), calls[0])
2961
def test_save_hook(self):
2965
config.ConfigHooks.install_named_hook('save', hook, None)
2966
self.assertLength(0, calls)
2967
store = self.get_store(self)
2968
section = store.get_mutable_section('baz')
2969
section.set('foo', 'bar')
2971
self.assertLength(1, calls)
2972
self.assertEquals((store,), calls[0])
2975
class TestTransportIniFileStore(TestStore):
2977
def test_loading_unknown_file_fails(self):
2978
store = config.TransportIniFileStore(self.get_transport(),
2980
self.assertRaises(errors.NoSuchFile, store.load)
2982
def test_invalid_content(self):
2983
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2984
self.assertEquals(False, store.is_loaded())
2985
exc = self.assertRaises(
2986
errors.ParseConfigError, store._load_from_string,
2987
'this is invalid !')
2988
self.assertEndsWith(exc.filename, 'foo.conf')
2989
# And the load failed
2990
self.assertEquals(False, store.is_loaded())
2992
def test_get_embedded_sections(self):
2993
# A more complicated example (which also shows that section names and
2994
# option names share the same name space...)
2995
# FIXME: This should be fixed by forbidding dicts as values ?
2996
# -- vila 2011-04-05
2997
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2998
store._load_from_string('''
3002
foo_in_DEFAULT=foo_DEFAULT
3010
sections = list(store.get_sections())
3011
self.assertLength(4, sections)
3012
# The default section has no name.
3013
# List values are provided as strings and need to be explicitly
3014
# converted by specifying from_unicode=list_from_store at option
3016
self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
3018
self.assertSectionContent(
3019
('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
3020
self.assertSectionContent(
3021
('bar', {'foo_in_bar': 'barbar'}), sections[2])
3022
# sub sections are provided as embedded dicts.
3023
self.assertSectionContent(
3024
('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
3028
class TestLockableIniFileStore(TestStore):
3030
def test_create_store_in_created_dir(self):
3031
self.assertPathDoesNotExist('dir')
3032
t = self.get_transport('dir/subdir')
3033
store = config.LockableIniFileStore(t, 'foo.conf')
3034
store.get_mutable_section(None).set('foo', 'bar')
3036
self.assertPathExists('dir/subdir')
3039
class TestConcurrentStoreUpdates(TestStore):
3040
"""Test that Stores properly handle conccurent updates.
3042
New Store implementation may fail some of these tests but until such
3043
implementations exist it's hard to properly filter them from the scenarios
3044
applied here. If you encounter such a case, contact the bzr devs.
3047
scenarios = [(key, {'get_stack': builder}) for key, builder
3048
in config.test_stack_builder_registry.iteritems()]
3051
super(TestConcurrentStoreUpdates, self).setUp()
3052
self.stack = self.get_stack(self)
3053
if not isinstance(self.stack, config._CompatibleStack):
3054
raise tests.TestNotApplicable(
3055
'%s is not meant to be compatible with the old config design'
3057
self.stack.set('one', '1')
3058
self.stack.set('two', '2')
3060
self.stack.store.save()
3062
def test_simple_read_access(self):
3063
self.assertEquals('1', self.stack.get('one'))
3065
def test_simple_write_access(self):
3066
self.stack.set('one', 'one')
3067
self.assertEquals('one', self.stack.get('one'))
3069
def test_listen_to_the_last_speaker(self):
3071
c2 = self.get_stack(self)
3072
c1.set('one', 'ONE')
3073
c2.set('two', 'TWO')
3074
self.assertEquals('ONE', c1.get('one'))
3075
self.assertEquals('TWO', c2.get('two'))
3076
# The second update respect the first one
3077
self.assertEquals('ONE', c2.get('one'))
3079
def test_last_speaker_wins(self):
3080
# If the same config is not shared, the same variable modified twice
3081
# can only see a single result.
3083
c2 = self.get_stack(self)
3086
self.assertEquals('c2', c2.get('one'))
3087
# The first modification is still available until another refresh
3089
self.assertEquals('c1', c1.get('one'))
3090
c1.set('two', 'done')
3091
self.assertEquals('c2', c1.get('one'))
3093
def test_writes_are_serialized(self):
3095
c2 = self.get_stack(self)
3097
# We spawn a thread that will pause *during* the config saving.
3098
before_writing = threading.Event()
3099
after_writing = threading.Event()
3100
writing_done = threading.Event()
3101
c1_save_without_locking_orig = c1.store.save_without_locking
3102
def c1_save_without_locking():
3103
before_writing.set()
3104
c1_save_without_locking_orig()
3105
# The lock is held. We wait for the main thread to decide when to
3107
after_writing.wait()
3108
c1.store.save_without_locking = c1_save_without_locking
3112
t1 = threading.Thread(target=c1_set)
3113
# Collect the thread after the test
3114
self.addCleanup(t1.join)
3115
# Be ready to unblock the thread if the test goes wrong
3116
self.addCleanup(after_writing.set)
3118
before_writing.wait()
3119
self.assertRaises(errors.LockContention,
3120
c2.set, 'one', 'c2')
3121
self.assertEquals('c1', c1.get('one'))
3122
# Let the lock be released
3126
self.assertEquals('c2', c2.get('one'))
3128
def test_read_while_writing(self):
3130
# We spawn a thread that will pause *during* the write
3131
ready_to_write = threading.Event()
3132
do_writing = threading.Event()
3133
writing_done = threading.Event()
3134
# We override the _save implementation so we know the store is locked
3135
c1_save_without_locking_orig = c1.store.save_without_locking
3136
def c1_save_without_locking():
3137
ready_to_write.set()
3138
# The lock is held. We wait for the main thread to decide when to
3141
c1_save_without_locking_orig()
3143
c1.store.save_without_locking = c1_save_without_locking
3146
t1 = threading.Thread(target=c1_set)
3147
# Collect the thread after the test
3148
self.addCleanup(t1.join)
3149
# Be ready to unblock the thread if the test goes wrong
3150
self.addCleanup(do_writing.set)
3152
# Ensure the thread is ready to write
3153
ready_to_write.wait()
3154
self.assertEquals('c1', c1.get('one'))
3155
# If we read during the write, we get the old value
3156
c2 = self.get_stack(self)
3157
self.assertEquals('1', c2.get('one'))
3158
# Let the writing occur and ensure it occurred
3161
# Now we get the updated value
3162
c3 = self.get_stack(self)
3163
self.assertEquals('c1', c3.get('one'))
3165
# FIXME: It may be worth looking into removing the lock dir when it's not
3166
# needed anymore and look at possible fallouts for concurrent lockers. This
3167
# will matter if/when we use config files outside of bazaar directories
3168
# (.bazaar or .bzr) -- vila 20110-04-111
3171
class TestSectionMatcher(TestStore):
3173
scenarios = [('location', {'matcher': config.LocationMatcher}),
3174
('id', {'matcher': config.NameMatcher}),]
3177
super(TestSectionMatcher, self).setUp()
3178
# Any simple store is good enough
3179
self.get_store = config.test_store_builder_registry.get('configobj')
3181
def test_no_matches_for_empty_stores(self):
3182
store = self.get_store(self)
3183
store._load_from_string('')
3184
matcher = self.matcher(store, '/bar')
3185
self.assertEquals([], list(matcher.get_sections()))
3187
def test_build_doesnt_load_store(self):
3188
store = self.get_store(self)
3189
matcher = self.matcher(store, '/bar')
3190
self.assertFalse(store.is_loaded())
3193
class TestLocationSection(tests.TestCase):
3195
def get_section(self, options, extra_path):
3196
section = config.Section('foo', options)
3197
# We don't care about the length so we use '0'
3198
return config.LocationSection(section, 0, extra_path)
3200
def test_simple_option(self):
3201
section = self.get_section({'foo': 'bar'}, '')
3202
self.assertEquals('bar', section.get('foo'))
3204
def test_option_with_extra_path(self):
3205
section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
3207
self.assertEquals('bar/baz', section.get('foo'))
3209
def test_invalid_policy(self):
3210
section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
3212
# invalid policies are ignored
3213
self.assertEquals('bar', section.get('foo'))
3216
class TestLocationMatcher(TestStore):
3219
super(TestLocationMatcher, self).setUp()
3220
# Any simple store is good enough
3221
self.get_store = config.test_store_builder_registry.get('configobj')
3223
def test_unrelated_section_excluded(self):
3224
store = self.get_store(self)
3225
store._load_from_string('''
3233
section=/foo/bar/baz
3237
self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3239
[section.id for _, section in store.get_sections()])
3240
matcher = config.LocationMatcher(store, '/foo/bar/quux')
3241
sections = [section for s, section in matcher.get_sections()]
3242
self.assertEquals([3, 2],
3243
[section.length for section in sections])
3244
self.assertEquals(['/foo/bar', '/foo'],
3245
[section.id for section in sections])
3246
self.assertEquals(['quux', 'bar/quux'],
3247
[section.extra_path for section in sections])
3249
def test_more_specific_sections_first(self):
3250
store = self.get_store(self)
3251
store._load_from_string('''
3257
self.assertEquals(['/foo', '/foo/bar'],
3258
[section.id for _, section in store.get_sections()])
3259
matcher = config.LocationMatcher(store, '/foo/bar/baz')
3260
sections = [section for s, section in matcher.get_sections()]
3261
self.assertEquals([3, 2],
3262
[section.length for section in sections])
3263
self.assertEquals(['/foo/bar', '/foo'],
3264
[section.id for section in sections])
3265
self.assertEquals(['baz', 'bar/baz'],
3266
[section.extra_path for section in sections])
3268
def test_appendpath_in_no_name_section(self):
3269
# It's a bit weird to allow appendpath in a no-name section, but
3270
# someone may found a use for it
3271
store = self.get_store(self)
3272
store._load_from_string('''
3274
foo:policy = appendpath
3276
matcher = config.LocationMatcher(store, 'dir/subdir')
3277
sections = list(matcher.get_sections())
3278
self.assertLength(1, sections)
3279
self.assertEquals('bar/dir/subdir', sections[0][1].get('foo'))
3281
def test_file_urls_are_normalized(self):
3282
store = self.get_store(self)
3283
if sys.platform == 'win32':
3284
expected_url = 'file:///C:/dir/subdir'
3285
expected_location = 'C:/dir/subdir'
3287
expected_url = 'file:///dir/subdir'
3288
expected_location = '/dir/subdir'
3289
matcher = config.LocationMatcher(store, expected_url)
3290
self.assertEquals(expected_location, matcher.location)
3293
class TestNameMatcher(TestStore):
3296
super(TestNameMatcher, self).setUp()
3297
self.matcher = config.NameMatcher
3298
# Any simple store is good enough
3299
self.get_store = config.test_store_builder_registry.get('configobj')
3301
def get_matching_sections(self, name):
3302
store = self.get_store(self)
3303
store._load_from_string('''
3311
matcher = self.matcher(store, name)
3312
return list(matcher.get_sections())
3314
def test_matching(self):
3315
sections = self.get_matching_sections('foo')
3316
self.assertLength(1, sections)
3317
self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3319
def test_not_matching(self):
3320
sections = self.get_matching_sections('baz')
3321
self.assertLength(0, sections)
3324
class TestStackGet(tests.TestCase):
3326
# FIXME: This should be parametrized for all known Stack or dedicated
3327
# paramerized tests created to avoid bloating -- vila 2011-03-31
3329
def overrideOptionRegistry(self):
3330
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3332
def test_single_config_get(self):
3333
conf = dict(foo='bar')
3334
conf_stack = config.Stack([conf])
3335
self.assertEquals('bar', conf_stack.get('foo'))
3337
def test_get_with_registered_default_value(self):
3338
conf_stack = config.Stack([dict()])
3339
opt = config.Option('foo', default='bar')
3340
self.overrideOptionRegistry()
3341
config.option_registry.register('foo', opt)
3342
self.assertEquals('bar', conf_stack.get('foo'))
3344
def test_get_without_registered_default_value(self):
3345
conf_stack = config.Stack([dict()])
3346
opt = config.Option('foo')
3347
self.overrideOptionRegistry()
3348
config.option_registry.register('foo', opt)
3349
self.assertEquals(None, conf_stack.get('foo'))
3351
def test_get_without_default_value_for_not_registered(self):
3352
conf_stack = config.Stack([dict()])
3353
opt = config.Option('foo')
3354
self.overrideOptionRegistry()
3355
self.assertEquals(None, conf_stack.get('foo'))
3357
def test_get_first_definition(self):
3358
conf1 = dict(foo='bar')
3359
conf2 = dict(foo='baz')
3360
conf_stack = config.Stack([conf1, conf2])
3361
self.assertEquals('bar', conf_stack.get('foo'))
3363
def test_get_embedded_definition(self):
3364
conf1 = dict(yy='12')
3365
conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
3366
conf_stack = config.Stack([conf1, conf2])
3367
self.assertEquals('baz', conf_stack.get('foo'))
3369
def test_get_for_empty_section_callable(self):
3370
conf_stack = config.Stack([lambda : []])
3371
self.assertEquals(None, conf_stack.get('foo'))
3373
def test_get_for_broken_callable(self):
3374
# Trying to use and invalid callable raises an exception on first use
3375
conf_stack = config.Stack([lambda : object()])
3376
self.assertRaises(TypeError, conf_stack.get, 'foo')
3379
class TestStackWithTransport(tests.TestCaseWithTransport):
3381
scenarios = [(key, {'get_stack': builder}) for key, builder
3382
in config.test_stack_builder_registry.iteritems()]
3385
class TestConcreteStacks(TestStackWithTransport):
3387
def test_build_stack(self):
3388
# Just a smoke test to help debug builders
3389
stack = self.get_stack(self)
3392
class TestStackGet(TestStackWithTransport):
3395
super(TestStackGet, self).setUp()
3396
self.conf = self.get_stack(self)
3398
def test_get_for_empty_stack(self):
3399
self.assertEquals(None, self.conf.get('foo'))
3401
def test_get_hook(self):
3402
self.conf.set('foo', 'bar')
3406
config.ConfigHooks.install_named_hook('get', hook, None)
3407
self.assertLength(0, calls)
3408
value = self.conf.get('foo')
3409
self.assertEquals('bar', value)
3410
self.assertLength(1, calls)
3411
self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3414
class TestStackGetWithConverter(tests.TestCaseWithTransport):
3417
super(TestStackGetWithConverter, self).setUp()
3418
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3419
self.registry = config.option_registry
3420
# We just want a simple stack with a simple store so we can inject
3421
# whatever content the tests need without caring about what section
3422
# names are valid for a given store/stack.
3423
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3424
self.conf = config.Stack([store.get_sections], store)
3426
def register_bool_option(self, name, default=None, default_from_env=None):
3427
b = config.Option(name, help='A boolean.',
3428
default=default, default_from_env=default_from_env,
3429
from_unicode=config.bool_from_store)
3430
self.registry.register(b)
3432
def test_get_default_bool_None(self):
3433
self.register_bool_option('foo')
3434
self.assertEquals(None, self.conf.get('foo'))
3436
def test_get_default_bool_True(self):
3437
self.register_bool_option('foo', u'True')
3438
self.assertEquals(True, self.conf.get('foo'))
3440
def test_get_default_bool_False(self):
3441
self.register_bool_option('foo', False)
3442
self.assertEquals(False, self.conf.get('foo'))
3444
def test_get_default_bool_False_as_string(self):
3445
self.register_bool_option('foo', u'False')
3446
self.assertEquals(False, self.conf.get('foo'))
3448
def test_get_default_bool_from_env_converted(self):
3449
self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3450
self.overrideEnv('FOO', 'False')
3451
self.assertEquals(False, self.conf.get('foo'))
3453
def test_get_default_bool_when_conversion_fails(self):
3454
self.register_bool_option('foo', default='True')
3455
self.conf.store._load_from_string('foo=invalid boolean')
3456
self.assertEquals(True, self.conf.get('foo'))
3458
def register_integer_option(self, name,
3459
default=None, default_from_env=None):
3460
i = config.Option(name, help='An integer.',
3461
default=default, default_from_env=default_from_env,
3462
from_unicode=config.int_from_store)
3463
self.registry.register(i)
3465
def test_get_default_integer_None(self):
3466
self.register_integer_option('foo')
3467
self.assertEquals(None, self.conf.get('foo'))
3469
def test_get_default_integer(self):
3470
self.register_integer_option('foo', 42)
3471
self.assertEquals(42, self.conf.get('foo'))
3473
def test_get_default_integer_as_string(self):
3474
self.register_integer_option('foo', u'42')
3475
self.assertEquals(42, self.conf.get('foo'))
3477
def test_get_default_integer_from_env(self):
3478
self.register_integer_option('foo', default_from_env=['FOO'])
3479
self.overrideEnv('FOO', '18')
3480
self.assertEquals(18, self.conf.get('foo'))
3482
def test_get_default_integer_when_conversion_fails(self):
3483
self.register_integer_option('foo', default='12')
3484
self.conf.store._load_from_string('foo=invalid integer')
3485
self.assertEquals(12, self.conf.get('foo'))
3487
def register_list_option(self, name, default=None, default_from_env=None):
3488
l = config.Option(name, help='A list.',
3489
default=default, default_from_env=default_from_env,
3490
from_unicode=config.list_from_store)
3491
self.registry.register(l)
3493
def test_get_default_list_None(self):
3494
self.register_list_option('foo')
3495
self.assertEquals(None, self.conf.get('foo'))
3497
def test_get_default_list_empty(self):
3498
self.register_list_option('foo', '')
3499
self.assertEquals([], self.conf.get('foo'))
3501
def test_get_default_list_from_env(self):
3502
self.register_list_option('foo', default_from_env=['FOO'])
3503
self.overrideEnv('FOO', '')
3504
self.assertEquals([], self.conf.get('foo'))
3506
def test_get_with_list_converter_no_item(self):
3507
self.register_list_option('foo', None)
3508
self.conf.store._load_from_string('foo=,')
3509
self.assertEquals([], self.conf.get('foo'))
3511
def test_get_with_list_converter_many_items(self):
3512
self.register_list_option('foo', None)
3513
self.conf.store._load_from_string('foo=m,o,r,e')
3514
self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
3516
def test_get_with_list_converter_embedded_spaces_many_items(self):
3517
self.register_list_option('foo', None)
3518
self.conf.store._load_from_string('foo=" bar", "baz "')
3519
self.assertEquals([' bar', 'baz '], self.conf.get('foo'))
3521
def test_get_with_list_converter_stripped_spaces_many_items(self):
3522
self.register_list_option('foo', None)
3523
self.conf.store._load_from_string('foo= bar , baz ')
3524
self.assertEquals(['bar', 'baz'], self.conf.get('foo'))
3527
class TestIterOptionRefs(tests.TestCase):
3528
"""iter_option_refs is a bit unusual, document some cases."""
3530
def assertRefs(self, expected, string):
3531
self.assertEquals(expected, list(config.iter_option_refs(string)))
3533
def test_empty(self):
3534
self.assertRefs([(False, '')], '')
3536
def test_no_refs(self):
3537
self.assertRefs([(False, 'foo bar')], 'foo bar')
3539
def test_single_ref(self):
3540
self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
3542
def test_broken_ref(self):
3543
self.assertRefs([(False, '{foo')], '{foo')
3545
def test_embedded_ref(self):
3546
self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
3549
def test_two_refs(self):
3550
self.assertRefs([(False, ''), (True, '{foo}'),
3551
(False, ''), (True, '{bar}'),
3555
def test_newline_in_refs_are_not_matched(self):
3556
self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
3559
class TestStackExpandOptions(tests.TestCaseWithTransport):
3562
super(TestStackExpandOptions, self).setUp()
3563
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3564
self.registry = config.option_registry
3565
self.conf = build_branch_stack(self)
3567
def assertExpansion(self, expected, string, env=None):
3568
self.assertEquals(expected, self.conf.expand_options(string, env))
3570
def test_no_expansion(self):
3571
self.assertExpansion('foo', 'foo')
3573
def test_expand_default_value(self):
3574
self.conf.store._load_from_string('bar=baz')
3575
self.registry.register(config.Option('foo', default=u'{bar}'))
3576
self.assertEquals('baz', self.conf.get('foo', expand=True))
3578
def test_expand_default_from_env(self):
3579
self.conf.store._load_from_string('bar=baz')
3580
self.registry.register(config.Option('foo', default_from_env=['FOO']))
3581
self.overrideEnv('FOO', '{bar}')
3582
self.assertEquals('baz', self.conf.get('foo', expand=True))
3584
def test_expand_default_on_failed_conversion(self):
3585
self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
3586
self.registry.register(
3587
config.Option('foo', default=u'{bar}',
3588
from_unicode=config.int_from_store))
3589
self.assertEquals(42, self.conf.get('foo', expand=True))
3591
def test_env_adding_options(self):
3592
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3594
def test_env_overriding_options(self):
3595
self.conf.store._load_from_string('foo=baz')
3596
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3598
def test_simple_ref(self):
3599
self.conf.store._load_from_string('foo=xxx')
3600
self.assertExpansion('xxx', '{foo}')
3602
def test_unknown_ref(self):
3603
self.assertRaises(errors.ExpandingUnknownOption,
3604
self.conf.expand_options, '{foo}')
3606
def test_indirect_ref(self):
3607
self.conf.store._load_from_string('''
3611
self.assertExpansion('xxx', '{bar}')
3613
def test_embedded_ref(self):
3614
self.conf.store._load_from_string('''
3618
self.assertExpansion('xxx', '{{bar}}')
3620
def test_simple_loop(self):
3621
self.conf.store._load_from_string('foo={foo}')
3622
self.assertRaises(errors.OptionExpansionLoop,
3623
self.conf.expand_options, '{foo}')
3625
def test_indirect_loop(self):
3626
self.conf.store._load_from_string('''
3630
e = self.assertRaises(errors.OptionExpansionLoop,
3631
self.conf.expand_options, '{foo}')
3632
self.assertEquals('foo->bar->baz', e.refs)
3633
self.assertEquals('{foo}', e.string)
3635
def test_list(self):
3636
self.conf.store._load_from_string('''
3640
list={foo},{bar},{baz}
3642
self.registry.register(
3643
config.Option('list', from_unicode=config.list_from_store))
3644
self.assertEquals(['start', 'middle', 'end'],
3645
self.conf.get('list', expand=True))
3647
def test_cascading_list(self):
3648
self.conf.store._load_from_string('''
3654
self.registry.register(
3655
config.Option('list', from_unicode=config.list_from_store))
3656
self.assertEquals(['start', 'middle', 'end'],
3657
self.conf.get('list', expand=True))
3659
def test_pathologically_hidden_list(self):
3660
self.conf.store._load_from_string('''
3666
hidden={start}{middle}{end}
3668
# What matters is what the registration says, the conversion happens
3669
# only after all expansions have been performed
3670
self.registry.register(
3671
config.Option('hidden', from_unicode=config.list_from_store))
3672
self.assertEquals(['bin', 'go'],
3673
self.conf.get('hidden', expand=True))
3676
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3679
super(TestStackCrossSectionsExpand, self).setUp()
3681
def get_config(self, location, string):
3684
# Since we don't save the config we won't strictly require to inherit
3685
# from TestCaseInTempDir, but an error occurs so quickly...
3686
c = config.LocationStack(location)
3687
c.store._load_from_string(string)
3690
def test_dont_cross_unrelated_section(self):
3691
c = self.get_config('/another/branch/path','''
3696
[/another/branch/path]
3699
self.assertRaises(errors.ExpandingUnknownOption,
3700
c.get, 'bar', expand=True)
3702
def test_cross_related_sections(self):
3703
c = self.get_config('/project/branch/path','''
3707
[/project/branch/path]
3710
self.assertEquals('quux', c.get('bar', expand=True))
3713
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
3715
def test_cross_global_locations(self):
3716
l_store = config.LocationStore()
3717
l_store._load_from_string('''
3723
g_store = config.GlobalStore()
3724
g_store._load_from_string('''
3730
stack = config.LocationStack('/branch')
3731
self.assertEquals('glob-bar', stack.get('lbar', expand=True))
3732
self.assertEquals('loc-foo', stack.get('gfoo', expand=True))
3735
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
3737
def test_expand_locals_empty(self):
3738
l_store = config.LocationStore()
3739
l_store._load_from_string('''
3740
[/home/user/project]
3745
stack = config.LocationStack('/home/user/project/')
3746
self.assertEquals('', stack.get('base', expand=True))
3747
self.assertEquals('', stack.get('rel', expand=True))
3749
def test_expand_basename_locally(self):
3750
l_store = config.LocationStore()
3751
l_store._load_from_string('''
3752
[/home/user/project]
3756
stack = config.LocationStack('/home/user/project/branch')
3757
self.assertEquals('branch', stack.get('bfoo', expand=True))
3759
def test_expand_basename_locally_longer_path(self):
3760
l_store = config.LocationStore()
3761
l_store._load_from_string('''
3766
stack = config.LocationStack('/home/user/project/dir/branch')
3767
self.assertEquals('branch', stack.get('bfoo', expand=True))
3769
def test_expand_relpath_locally(self):
3770
l_store = config.LocationStore()
3771
l_store._load_from_string('''
3772
[/home/user/project]
3773
lfoo = loc-foo/{relpath}
3776
stack = config.LocationStack('/home/user/project/branch')
3777
self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
3779
def test_expand_relpath_unknonw_in_global(self):
3780
g_store = config.GlobalStore()
3781
g_store._load_from_string('''
3786
stack = config.LocationStack('/home/user/project/branch')
3787
self.assertRaises(errors.ExpandingUnknownOption,
3788
stack.get, 'gfoo', expand=True)
3790
def test_expand_local_option_locally(self):
3791
l_store = config.LocationStore()
3792
l_store._load_from_string('''
3793
[/home/user/project]
3794
lfoo = loc-foo/{relpath}
3798
g_store = config.GlobalStore()
3799
g_store._load_from_string('''
3805
stack = config.LocationStack('/home/user/project/branch')
3806
self.assertEquals('glob-bar', stack.get('lbar', expand=True))
3807
self.assertEquals('loc-foo/branch', stack.get('gfoo', expand=True))
3809
def test_locals_dont_leak(self):
3810
"""Make sure we chose the right local in presence of several sections.
3812
l_store = config.LocationStore()
3813
l_store._load_from_string('''
3815
lfoo = loc-foo/{relpath}
3816
[/home/user/project]
3817
lfoo = loc-foo/{relpath}
3820
stack = config.LocationStack('/home/user/project/branch')
3821
self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
3822
stack = config.LocationStack('/home/user/bar/baz')
3823
self.assertEquals('loc-foo/bar/baz', stack.get('lfoo', expand=True))
3827
class TestStackSet(TestStackWithTransport):
3829
def test_simple_set(self):
3830
conf = self.get_stack(self)
3831
self.assertEquals(None, conf.get('foo'))
3832
conf.set('foo', 'baz')
3833
# Did we get it back ?
3834
self.assertEquals('baz', conf.get('foo'))
3836
def test_set_creates_a_new_section(self):
3837
conf = self.get_stack(self)
3838
conf.set('foo', 'baz')
3839
self.assertEquals, 'baz', conf.get('foo')
3841
def test_set_hook(self):
3845
config.ConfigHooks.install_named_hook('set', hook, None)
3846
self.assertLength(0, calls)
3847
conf = self.get_stack(self)
3848
conf.set('foo', 'bar')
3849
self.assertLength(1, calls)
3850
self.assertEquals((conf, 'foo', 'bar'), calls[0])
3853
class TestStackRemove(TestStackWithTransport):
3855
def test_remove_existing(self):
3856
conf = self.get_stack(self)
3857
conf.set('foo', 'bar')
3858
self.assertEquals('bar', conf.get('foo'))
3860
# Did we get it back ?
3861
self.assertEquals(None, conf.get('foo'))
3863
def test_remove_unknown(self):
3864
conf = self.get_stack(self)
3865
self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3867
def test_remove_hook(self):
3871
config.ConfigHooks.install_named_hook('remove', hook, None)
3872
self.assertLength(0, calls)
3873
conf = self.get_stack(self)
3874
conf.set('foo', 'bar')
3876
self.assertLength(1, calls)
3877
self.assertEquals((conf, 'foo'), calls[0])
3880
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3883
super(TestConfigGetOptions, self).setUp()
3884
create_configs(self)
3886
def test_no_variable(self):
3887
# Using branch should query branch, locations and bazaar
3888
self.assertOptions([], self.branch_config)
3890
def test_option_in_bazaar(self):
3891
self.bazaar_config.set_user_option('file', 'bazaar')
3892
self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
3895
def test_option_in_locations(self):
3896
self.locations_config.set_user_option('file', 'locations')
3898
[('file', 'locations', self.tree.basedir, 'locations')],
3899
self.locations_config)
3901
def test_option_in_branch(self):
3902
self.branch_config.set_user_option('file', 'branch')
3903
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
3906
def test_option_in_bazaar_and_branch(self):
3907
self.bazaar_config.set_user_option('file', 'bazaar')
3908
self.branch_config.set_user_option('file', 'branch')
3909
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
3910
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3913
def test_option_in_branch_and_locations(self):
3914
# Hmm, locations override branch :-/
3915
self.locations_config.set_user_option('file', 'locations')
3916
self.branch_config.set_user_option('file', 'branch')
3918
[('file', 'locations', self.tree.basedir, 'locations'),
3919
('file', 'branch', 'DEFAULT', 'branch'),],
3922
def test_option_in_bazaar_locations_and_branch(self):
3923
self.bazaar_config.set_user_option('file', 'bazaar')
3924
self.locations_config.set_user_option('file', 'locations')
3925
self.branch_config.set_user_option('file', 'branch')
3927
[('file', 'locations', self.tree.basedir, 'locations'),
3928
('file', 'branch', 'DEFAULT', 'branch'),
3929
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3933
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
3936
super(TestConfigRemoveOption, self).setUp()
3937
create_configs_with_file_option(self)
3939
def test_remove_in_locations(self):
3940
self.locations_config.remove_user_option('file', self.tree.basedir)
3942
[('file', 'branch', 'DEFAULT', 'branch'),
3943
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3946
def test_remove_in_branch(self):
3947
self.branch_config.remove_user_option('file')
3949
[('file', 'locations', self.tree.basedir, 'locations'),
3950
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3953
def test_remove_in_bazaar(self):
3954
self.bazaar_config.remove_user_option('file')
3956
[('file', 'locations', self.tree.basedir, 'locations'),
3957
('file', 'branch', 'DEFAULT', 'branch'),],
3961
class TestConfigGetSections(tests.TestCaseWithTransport):
3964
super(TestConfigGetSections, self).setUp()
3965
create_configs(self)
3967
def assertSectionNames(self, expected, conf, name=None):
3968
"""Check which sections are returned for a given config.
3970
If fallback configurations exist their sections can be included.
3972
:param expected: A list of section names.
3974
:param conf: The configuration that will be queried.
3976
:param name: An optional section name that will be passed to
3979
sections = list(conf._get_sections(name))
3980
self.assertLength(len(expected), sections)
3981
self.assertEqual(expected, [name for name, _, _ in sections])
3983
def test_bazaar_default_section(self):
3984
self.assertSectionNames(['DEFAULT'], self.bazaar_config)
3986
def test_locations_default_section(self):
3987
# No sections are defined in an empty file
3988
self.assertSectionNames([], self.locations_config)
3990
def test_locations_named_section(self):
3991
self.locations_config.set_user_option('file', 'locations')
3992
self.assertSectionNames([self.tree.basedir], self.locations_config)
3994
def test_locations_matching_sections(self):
3995
loc_config = self.locations_config
3996
loc_config.set_user_option('file', 'locations')
3997
# We need to cheat a bit here to create an option in sections above and
3998
# below the 'location' one.
3999
parser = loc_config._get_parser()
4000
# locations.cong deals with '/' ignoring native os.sep
4001
location_names = self.tree.basedir.split('/')
4002
parent = '/'.join(location_names[:-1])
4003
child = '/'.join(location_names + ['child'])
4005
parser[parent]['file'] = 'parent'
4007
parser[child]['file'] = 'child'
4008
self.assertSectionNames([self.tree.basedir, parent], loc_config)
4010
def test_branch_data_default_section(self):
4011
self.assertSectionNames([None],
4012
self.branch_config._get_branch_data_config())
4014
def test_branch_default_sections(self):
4015
# No sections are defined in an empty locations file
4016
self.assertSectionNames([None, 'DEFAULT'],
4018
# Unless we define an option
4019
self.branch_config._get_location_config().set_user_option(
4020
'file', 'locations')
4021
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
4024
def test_bazaar_named_section(self):
4025
# We need to cheat as the API doesn't give direct access to sections
4026
# other than DEFAULT.
4027
self.bazaar_config.set_alias('bazaar', 'bzr')
4028
self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
1474
4031
class TestAuthenticationConfigFile(tests.TestCase):
1475
4032
"""Test the authentication.conf file matching"""