1312
2082
self.assertIs(None, bzrdir_config.get_default_stack_on())
2085
class TestOldConfigHooks(tests.TestCaseWithTransport):
2088
super(TestOldConfigHooks, self).setUp()
2089
create_configs_with_file_option(self)
2091
def assertGetHook(self, conf, name, value):
2095
config.OldConfigHooks.install_named_hook('get', hook, None)
2097
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2098
self.assertLength(0, calls)
2099
actual_value = conf.get_user_option(name)
2100
self.assertEquals(value, actual_value)
2101
self.assertLength(1, calls)
2102
self.assertEquals((conf, name, value), calls[0])
2104
def test_get_hook_bazaar(self):
2105
self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
2107
def test_get_hook_locations(self):
2108
self.assertGetHook(self.locations_config, 'file', 'locations')
2110
def test_get_hook_branch(self):
2111
# Since locations masks branch, we define a different option
2112
self.branch_config.set_user_option('file2', 'branch')
2113
self.assertGetHook(self.branch_config, 'file2', 'branch')
2115
def assertSetHook(self, conf, name, value):
2119
config.OldConfigHooks.install_named_hook('set', hook, None)
2121
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2122
self.assertLength(0, calls)
2123
conf.set_user_option(name, value)
2124
self.assertLength(1, calls)
2125
# We can't assert the conf object below as different configs use
2126
# different means to implement set_user_option and we care only about
2128
self.assertEquals((name, value), calls[0][1:])
2130
def test_set_hook_bazaar(self):
2131
self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
2133
def test_set_hook_locations(self):
2134
self.assertSetHook(self.locations_config, 'foo', 'locations')
2136
def test_set_hook_branch(self):
2137
self.assertSetHook(self.branch_config, 'foo', 'branch')
2139
def assertRemoveHook(self, conf, name, section_name=None):
2143
config.OldConfigHooks.install_named_hook('remove', hook, None)
2145
config.OldConfigHooks.uninstall_named_hook, 'remove', None)
2146
self.assertLength(0, calls)
2147
conf.remove_user_option(name, section_name)
2148
self.assertLength(1, calls)
2149
# We can't assert the conf object below as different configs use
2150
# different means to implement remove_user_option and we care only about
2152
self.assertEquals((name,), calls[0][1:])
2154
def test_remove_hook_bazaar(self):
2155
self.assertRemoveHook(self.bazaar_config, 'file')
2157
def test_remove_hook_locations(self):
2158
self.assertRemoveHook(self.locations_config, 'file',
2159
self.locations_config.location)
2161
def test_remove_hook_branch(self):
2162
self.assertRemoveHook(self.branch_config, 'file')
2164
def assertLoadHook(self, name, conf_class, *conf_args):
2168
config.OldConfigHooks.install_named_hook('load', hook, None)
2170
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2171
self.assertLength(0, calls)
2173
conf = conf_class(*conf_args)
2174
# Access an option to trigger a load
2175
conf.get_user_option(name)
2176
self.assertLength(1, calls)
2177
# Since we can't assert about conf, we just use the number of calls ;-/
2179
def test_load_hook_bazaar(self):
2180
self.assertLoadHook('file', config.GlobalConfig)
2182
def test_load_hook_locations(self):
2183
self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
2185
def test_load_hook_branch(self):
2186
self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
2188
def assertSaveHook(self, conf):
2192
config.OldConfigHooks.install_named_hook('save', hook, None)
2194
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2195
self.assertLength(0, calls)
2196
# Setting an option triggers a save
2197
conf.set_user_option('foo', 'bar')
2198
self.assertLength(1, calls)
2199
# Since we can't assert about conf, we just use the number of calls ;-/
2201
def test_save_hook_bazaar(self):
2202
self.assertSaveHook(self.bazaar_config)
2204
def test_save_hook_locations(self):
2205
self.assertSaveHook(self.locations_config)
2207
def test_save_hook_branch(self):
2208
self.assertSaveHook(self.branch_config)
2211
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
2212
"""Tests config hooks for remote configs.
2214
No tests for the remove hook as this is not implemented there.
2218
super(TestOldConfigHooksForRemote, self).setUp()
2219
self.transport_server = test_server.SmartTCPServer_for_testing
2220
create_configs_with_file_option(self)
2222
def assertGetHook(self, conf, name, value):
2226
config.OldConfigHooks.install_named_hook('get', hook, None)
2228
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2229
self.assertLength(0, calls)
2230
actual_value = conf.get_option(name)
2231
self.assertEquals(value, actual_value)
2232
self.assertLength(1, calls)
2233
self.assertEquals((conf, name, value), calls[0])
2235
def test_get_hook_remote_branch(self):
2236
remote_branch = branch.Branch.open(self.get_url('tree'))
2237
self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2239
def test_get_hook_remote_bzrdir(self):
2240
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2241
conf = remote_bzrdir._get_config()
2242
conf.set_option('remotedir', 'file')
2243
self.assertGetHook(conf, 'file', 'remotedir')
2245
def assertSetHook(self, conf, name, value):
2249
config.OldConfigHooks.install_named_hook('set', hook, None)
2251
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2252
self.assertLength(0, calls)
2253
conf.set_option(value, name)
2254
self.assertLength(1, calls)
2255
# We can't assert the conf object below as different configs use
2256
# different means to implement set_user_option and we care only about
2258
self.assertEquals((name, value), calls[0][1:])
2260
def test_set_hook_remote_branch(self):
2261
remote_branch = branch.Branch.open(self.get_url('tree'))
2262
self.addCleanup(remote_branch.lock_write().unlock)
2263
self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
2265
def test_set_hook_remote_bzrdir(self):
2266
remote_branch = branch.Branch.open(self.get_url('tree'))
2267
self.addCleanup(remote_branch.lock_write().unlock)
2268
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2269
self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2271
def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2275
config.OldConfigHooks.install_named_hook('load', hook, None)
2277
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2278
self.assertLength(0, calls)
2280
conf = conf_class(*conf_args)
2281
# Access an option to trigger a load
2282
conf.get_option(name)
2283
self.assertLength(expected_nb_calls, calls)
2284
# Since we can't assert about conf, we just use the number of calls ;-/
2286
def test_load_hook_remote_branch(self):
2287
remote_branch = branch.Branch.open(self.get_url('tree'))
2288
self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2290
def test_load_hook_remote_bzrdir(self):
2291
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2292
# The config file doesn't exist, set an option to force its creation
2293
conf = remote_bzrdir._get_config()
2294
conf.set_option('remotedir', 'file')
2295
# We get one call for the server and one call for the client, this is
2296
# caused by the differences in implementations betwen
2297
# SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
2298
# SmartServerBranchGetConfigFile (in smart/branch.py)
2299
self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
2301
def assertSaveHook(self, conf):
2305
config.OldConfigHooks.install_named_hook('save', hook, None)
2307
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2308
self.assertLength(0, calls)
2309
# Setting an option triggers a save
2310
conf.set_option('foo', 'bar')
2311
self.assertLength(1, calls)
2312
# Since we can't assert about conf, we just use the number of calls ;-/
2314
def test_save_hook_remote_branch(self):
2315
remote_branch = branch.Branch.open(self.get_url('tree'))
2316
self.addCleanup(remote_branch.lock_write().unlock)
2317
self.assertSaveHook(remote_branch._get_config())
2319
def test_save_hook_remote_bzrdir(self):
2320
remote_branch = branch.Branch.open(self.get_url('tree'))
2321
self.addCleanup(remote_branch.lock_write().unlock)
2322
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2323
self.assertSaveHook(remote_bzrdir._get_config())
2326
class TestOption(tests.TestCase):
2328
def test_default_value(self):
2329
opt = config.Option('foo', default='bar')
2330
self.assertEquals('bar', opt.get_default())
2332
def test_callable_default_value(self):
2333
def bar_as_unicode():
2335
opt = config.Option('foo', default=bar_as_unicode)
2336
self.assertEquals('bar', opt.get_default())
2338
def test_default_value_from_env(self):
2339
opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2340
self.overrideEnv('FOO', 'quux')
2341
# Env variable provides a default taking over the option one
2342
self.assertEquals('quux', opt.get_default())
2344
def test_first_default_value_from_env_wins(self):
2345
opt = config.Option('foo', default='bar',
2346
default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2347
self.overrideEnv('FOO', 'foo')
2348
self.overrideEnv('BAZ', 'baz')
2349
# The first env var set wins
2350
self.assertEquals('foo', opt.get_default())
2352
def test_not_supported_list_default_value(self):
2353
self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2355
def test_not_supported_object_default_value(self):
2356
self.assertRaises(AssertionError, config.Option, 'foo',
2359
def test_not_supported_callable_default_value_not_unicode(self):
2360
def bar_not_unicode():
2362
opt = config.Option('foo', default=bar_not_unicode)
2363
self.assertRaises(AssertionError, opt.get_default)
2366
class TestOptionConverterMixin(object):
2368
def assertConverted(self, expected, opt, value):
2369
self.assertEquals(expected, opt.convert_from_unicode(None, value))
2371
def assertWarns(self, opt, value):
2374
warnings.append(args[0] % args[1:])
2375
self.overrideAttr(trace, 'warning', warning)
2376
self.assertEquals(None, opt.convert_from_unicode(None, value))
2377
self.assertLength(1, warnings)
2379
'Value "%s" is not valid for "%s"' % (value, opt.name),
2382
def assertErrors(self, opt, value):
2383
self.assertRaises(errors.ConfigOptionValueError,
2384
opt.convert_from_unicode, None, value)
2386
def assertConvertInvalid(self, opt, invalid_value):
2388
self.assertEquals(None, opt.convert_from_unicode(None, invalid_value))
2389
opt.invalid = 'warning'
2390
self.assertWarns(opt, invalid_value)
2391
opt.invalid = 'error'
2392
self.assertErrors(opt, invalid_value)
2395
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2397
def get_option(self):
2398
return config.Option('foo', help='A boolean.',
2399
from_unicode=config.bool_from_store)
2401
def test_convert_invalid(self):
2402
opt = self.get_option()
2403
# A string that is not recognized as a boolean
2404
self.assertConvertInvalid(opt, u'invalid-boolean')
2405
# A list of strings is never recognized as a boolean
2406
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2408
def test_convert_valid(self):
2409
opt = self.get_option()
2410
self.assertConverted(True, opt, u'True')
2411
self.assertConverted(True, opt, u'1')
2412
self.assertConverted(False, opt, u'False')
2415
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2417
def get_option(self):
2418
return config.Option('foo', help='An integer.',
2419
from_unicode=config.int_from_store)
2421
def test_convert_invalid(self):
2422
opt = self.get_option()
2423
# A string that is not recognized as an integer
2424
self.assertConvertInvalid(opt, u'forty-two')
2425
# A list of strings is never recognized as an integer
2426
self.assertConvertInvalid(opt, [u'a', u'list'])
2428
def test_convert_valid(self):
2429
opt = self.get_option()
2430
self.assertConverted(16, opt, u'16')
2433
class TestOptionWithSIUnitConverter(tests.TestCase, TestOptionConverterMixin):
2435
def get_option(self):
2436
return config.Option('foo', help='An integer in SI units.',
2437
from_unicode=config.int_SI_from_store)
2439
def test_convert_invalid(self):
2440
opt = self.get_option()
2441
self.assertConvertInvalid(opt, u'not-a-unit')
2442
self.assertConvertInvalid(opt, u'Gb') # Forgot the int
2443
self.assertConvertInvalid(opt, u'1b') # Forgot the unit
2444
self.assertConvertInvalid(opt, u'1GG')
2445
self.assertConvertInvalid(opt, u'1Mbb')
2446
self.assertConvertInvalid(opt, u'1MM')
2448
def test_convert_valid(self):
2449
opt = self.get_option()
2450
self.assertConverted(int(5e3), opt, u'5kb')
2451
self.assertConverted(int(5e6), opt, u'5M')
2452
self.assertConverted(int(5e6), opt, u'5MB')
2453
self.assertConverted(int(5e9), opt, u'5g')
2454
self.assertConverted(int(5e9), opt, u'5gB')
2455
self.assertConverted(100, opt, u'100')
2458
class TestListOption(tests.TestCase, TestOptionConverterMixin):
2460
def get_option(self):
2461
return config.ListOption('foo', help='A list.')
2463
def test_convert_invalid(self):
2464
opt = self.get_option()
2465
# We don't even try to convert a list into a list, we only expect
2467
self.assertConvertInvalid(opt, [1])
2468
# No string is invalid as all forms can be converted to a list
2470
def test_convert_valid(self):
2471
opt = self.get_option()
2472
# An empty string is an empty list
2473
self.assertConverted([], opt, '') # Using a bare str() just in case
2474
self.assertConverted([], opt, u'')
2476
self.assertConverted([u'True'], opt, u'True')
2478
self.assertConverted([u'42'], opt, u'42')
2480
self.assertConverted([u'bar'], opt, u'bar')
2483
class TestOptionRegistry(tests.TestCase):
2486
super(TestOptionRegistry, self).setUp()
2487
# Always start with an empty registry
2488
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2489
self.registry = config.option_registry
2491
def test_register(self):
2492
opt = config.Option('foo')
2493
self.registry.register(opt)
2494
self.assertIs(opt, self.registry.get('foo'))
2496
def test_registered_help(self):
2497
opt = config.Option('foo', help='A simple option')
2498
self.registry.register(opt)
2499
self.assertEquals('A simple option', self.registry.get_help('foo'))
2501
lazy_option = config.Option('lazy_foo', help='Lazy help')
2503
def test_register_lazy(self):
2504
self.registry.register_lazy('lazy_foo', self.__module__,
2505
'TestOptionRegistry.lazy_option')
2506
self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2508
def test_registered_lazy_help(self):
2509
self.registry.register_lazy('lazy_foo', self.__module__,
2510
'TestOptionRegistry.lazy_option')
2511
self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2514
class TestRegisteredOptions(tests.TestCase):
2515
"""All registered options should verify some constraints."""
2517
scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2518
in config.option_registry.iteritems()]
2521
super(TestRegisteredOptions, self).setUp()
2522
self.registry = config.option_registry
2524
def test_proper_name(self):
2525
# An option should be registered under its own name, this can't be
2526
# checked at registration time for the lazy ones.
2527
self.assertEquals(self.option_name, self.option.name)
2529
def test_help_is_set(self):
2530
option_help = self.registry.get_help(self.option_name)
2531
self.assertNotEquals(None, option_help)
2532
# Come on, think about the user, he really wants to know what the
2534
self.assertIsNot(None, option_help)
2535
self.assertNotEquals('', option_help)
2538
class TestSection(tests.TestCase):
2540
# FIXME: Parametrize so that all sections produced by Stores run these
2541
# tests -- vila 2011-04-01
2543
def test_get_a_value(self):
2544
a_dict = dict(foo='bar')
2545
section = config.Section('myID', a_dict)
2546
self.assertEquals('bar', section.get('foo'))
2548
def test_get_unknown_option(self):
2550
section = config.Section(None, a_dict)
2551
self.assertEquals('out of thin air',
2552
section.get('foo', 'out of thin air'))
2554
def test_options_is_shared(self):
2556
section = config.Section(None, a_dict)
2557
self.assertIs(a_dict, section.options)
2560
class TestMutableSection(tests.TestCase):
2562
scenarios = [('mutable',
2564
lambda opts: config.MutableSection('myID', opts)},),
2568
a_dict = dict(foo='bar')
2569
section = self.get_section(a_dict)
2570
section.set('foo', 'new_value')
2571
self.assertEquals('new_value', section.get('foo'))
2572
# The change appears in the shared section
2573
self.assertEquals('new_value', a_dict.get('foo'))
2574
# We keep track of the change
2575
self.assertTrue('foo' in section.orig)
2576
self.assertEquals('bar', section.orig.get('foo'))
2578
def test_set_preserve_original_once(self):
2579
a_dict = dict(foo='bar')
2580
section = self.get_section(a_dict)
2581
section.set('foo', 'first_value')
2582
section.set('foo', 'second_value')
2583
# We keep track of the original value
2584
self.assertTrue('foo' in section.orig)
2585
self.assertEquals('bar', section.orig.get('foo'))
2587
def test_remove(self):
2588
a_dict = dict(foo='bar')
2589
section = self.get_section(a_dict)
2590
section.remove('foo')
2591
# We get None for unknown options via the default value
2592
self.assertEquals(None, section.get('foo'))
2593
# Or we just get the default value
2594
self.assertEquals('unknown', section.get('foo', 'unknown'))
2595
self.assertFalse('foo' in section.options)
2596
# We keep track of the deletion
2597
self.assertTrue('foo' in section.orig)
2598
self.assertEquals('bar', section.orig.get('foo'))
2600
def test_remove_new_option(self):
2602
section = self.get_section(a_dict)
2603
section.set('foo', 'bar')
2604
section.remove('foo')
2605
self.assertFalse('foo' in section.options)
2606
# The option didn't exist initially so it we need to keep track of it
2607
# with a special value
2608
self.assertTrue('foo' in section.orig)
2609
self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2612
class TestCommandLineStore(tests.TestCase):
2615
super(TestCommandLineStore, self).setUp()
2616
self.store = config.CommandLineStore()
2617
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2619
def get_section(self):
2620
"""Get the unique section for the command line overrides."""
2621
sections = list(self.store.get_sections())
2622
self.assertLength(1, sections)
2623
store, section = sections[0]
2624
self.assertEquals(self.store, store)
2627
def test_no_override(self):
2628
self.store._from_cmdline([])
2629
section = self.get_section()
2630
self.assertLength(0, list(section.iter_option_names()))
2632
def test_simple_override(self):
2633
self.store._from_cmdline(['a=b'])
2634
section = self.get_section()
2635
self.assertEqual('b', section.get('a'))
2637
def test_list_override(self):
2638
opt = config.ListOption('l')
2639
config.option_registry.register(opt)
2640
self.store._from_cmdline(['l=1,2,3'])
2641
val = self.get_section().get('l')
2642
self.assertEqual('1,2,3', val)
2643
# Reminder: lists should be registered as such explicitely, otherwise
2644
# the conversion needs to be done afterwards.
2645
self.assertEqual(['1', '2', '3'],
2646
opt.convert_from_unicode(self.store, val))
2648
def test_multiple_overrides(self):
2649
self.store._from_cmdline(['a=b', 'x=y'])
2650
section = self.get_section()
2651
self.assertEquals('b', section.get('a'))
2652
self.assertEquals('y', section.get('x'))
2654
def test_wrong_syntax(self):
2655
self.assertRaises(errors.BzrCommandError,
2656
self.store._from_cmdline, ['a=b', 'c'])
2658
class TestStoreMinimalAPI(tests.TestCaseWithTransport):
2660
scenarios = [(key, {'get_store': builder}) for key, builder
2661
in config.test_store_builder_registry.iteritems()] + [
2662
('cmdline', {'get_store': lambda test: config.CommandLineStore()})]
2665
store = self.get_store(self)
2666
if type(store) == config.TransportIniFileStore:
2667
raise tests.TestNotApplicable(
2668
"%s is not a concrete Store implementation"
2669
" so it doesn't need an id" % (store.__class__.__name__,))
2670
self.assertIsNot(None, store.id)
2673
class TestStore(tests.TestCaseWithTransport):
2675
def assertSectionContent(self, expected, (store, section)):
2676
"""Assert that some options have the proper values in a section."""
2677
expected_name, expected_options = expected
2678
self.assertEquals(expected_name, section.id)
2681
dict([(k, section.get(k)) for k in expected_options.keys()]))
2684
class TestReadonlyStore(TestStore):
2686
scenarios = [(key, {'get_store': builder}) for key, builder
2687
in config.test_store_builder_registry.iteritems()]
2689
def test_building_delays_load(self):
2690
store = self.get_store(self)
2691
self.assertEquals(False, store.is_loaded())
2692
store._load_from_string('')
2693
self.assertEquals(True, store.is_loaded())
2695
def test_get_no_sections_for_empty(self):
2696
store = self.get_store(self)
2697
store._load_from_string('')
2698
self.assertEquals([], list(store.get_sections()))
2700
def test_get_default_section(self):
2701
store = self.get_store(self)
2702
store._load_from_string('foo=bar')
2703
sections = list(store.get_sections())
2704
self.assertLength(1, sections)
2705
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2707
def test_get_named_section(self):
2708
store = self.get_store(self)
2709
store._load_from_string('[baz]\nfoo=bar')
2710
sections = list(store.get_sections())
2711
self.assertLength(1, sections)
2712
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2714
def test_load_from_string_fails_for_non_empty_store(self):
2715
store = self.get_store(self)
2716
store._load_from_string('foo=bar')
2717
self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2720
class TestStoreQuoting(TestStore):
2722
scenarios = [(key, {'get_store': builder}) for key, builder
2723
in config.test_store_builder_registry.iteritems()]
2726
super(TestStoreQuoting, self).setUp()
2727
self.store = self.get_store(self)
2728
# We need a loaded store but any content will do
2729
self.store._load_from_string('')
2731
def assertIdempotent(self, s):
2732
"""Assert that quoting an unquoted string is a no-op and vice-versa.
2734
What matters here is that option values, as they appear in a store, can
2735
be safely round-tripped out of the store and back.
2737
:param s: A string, quoted if required.
2739
self.assertEquals(s, self.store.quote(self.store.unquote(s)))
2740
self.assertEquals(s, self.store.unquote(self.store.quote(s)))
2742
def test_empty_string(self):
2743
if isinstance(self.store, config.IniFileStore):
2744
# configobj._quote doesn't handle empty values
2745
self.assertRaises(AssertionError,
2746
self.assertIdempotent, '')
2748
self.assertIdempotent('')
2749
# But quoted empty strings are ok
2750
self.assertIdempotent('""')
2752
def test_embedded_spaces(self):
2753
self.assertIdempotent('" a b c "')
2755
def test_embedded_commas(self):
2756
self.assertIdempotent('" a , b c "')
2758
def test_simple_comma(self):
2759
if isinstance(self.store, config.IniFileStore):
2760
# configobj requires that lists are special-cased
2761
self.assertRaises(AssertionError,
2762
self.assertIdempotent, ',')
2764
self.assertIdempotent(',')
2765
# When a single comma is required, quoting is also required
2766
self.assertIdempotent('","')
2768
def test_list(self):
2769
if isinstance(self.store, config.IniFileStore):
2770
# configobj requires that lists are special-cased
2771
self.assertRaises(AssertionError,
2772
self.assertIdempotent, 'a,b')
2774
self.assertIdempotent('a,b')
2777
class TestDictFromStore(tests.TestCase):
2779
def test_unquote_not_string(self):
2780
conf = config.MemoryStack('x=2\n[a_section]\na=1\n')
2781
value = conf.get('a_section')
2782
# Urgh, despite 'conf' asking for the no-name section, we get the
2783
# content of another section as a dict o_O
2784
self.assertEquals({'a': '1'}, value)
2785
unquoted = conf.store.unquote(value)
2786
# Which cannot be unquoted but shouldn't crash either (the use cases
2787
# are getting the value or displaying it. In the later case, '%s' will
2789
self.assertEquals({'a': '1'}, unquoted)
2790
self.assertEquals("{u'a': u'1'}", '%s' % (unquoted,))
2793
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2794
"""Simulate loading a config store with content of various encodings.
2796
All files produced by bzr are in utf8 content.
2798
Users may modify them manually and end up with a file that can't be
2799
loaded. We need to issue proper error messages in this case.
2802
invalid_utf8_char = '\xff'
2804
def test_load_utf8(self):
2805
"""Ensure we can load an utf8-encoded file."""
2806
t = self.get_transport()
2807
# From http://pad.lv/799212
2808
unicode_user = u'b\N{Euro Sign}ar'
2809
unicode_content = u'user=%s' % (unicode_user,)
2810
utf8_content = unicode_content.encode('utf8')
2811
# Store the raw content in the config file
2812
t.put_bytes('foo.conf', utf8_content)
2813
store = config.TransportIniFileStore(t, 'foo.conf')
2815
stack = config.Stack([store.get_sections], store)
2816
self.assertEquals(unicode_user, stack.get('user'))
2818
def test_load_non_ascii(self):
2819
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2820
t = self.get_transport()
2821
t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2822
store = config.TransportIniFileStore(t, 'foo.conf')
2823
self.assertRaises(errors.ConfigContentError, store.load)
2825
def test_load_erroneous_content(self):
2826
"""Ensure we display a proper error on content that can't be parsed."""
2827
t = self.get_transport()
2828
t.put_bytes('foo.conf', '[open_section\n')
2829
store = config.TransportIniFileStore(t, 'foo.conf')
2830
self.assertRaises(errors.ParseConfigError, store.load)
2832
def test_load_permission_denied(self):
2833
"""Ensure we get warned when trying to load an inaccessible file."""
2836
warnings.append(args[0] % args[1:])
2837
self.overrideAttr(trace, 'warning', warning)
2839
t = self.get_transport()
2841
def get_bytes(relpath):
2842
raise errors.PermissionDenied(relpath, "")
2843
t.get_bytes = get_bytes
2844
store = config.TransportIniFileStore(t, 'foo.conf')
2845
self.assertRaises(errors.PermissionDenied, store.load)
2848
[u'Permission denied while trying to load configuration store %s.'
2849
% store.external_url()])
2852
class TestIniConfigContent(tests.TestCaseWithTransport):
2853
"""Simulate loading a IniBasedConfig with content of various encodings.
2855
All files produced by bzr are in utf8 content.
2857
Users may modify them manually and end up with a file that can't be
2858
loaded. We need to issue proper error messages in this case.
2861
invalid_utf8_char = '\xff'
2863
def test_load_utf8(self):
2864
"""Ensure we can load an utf8-encoded file."""
2865
# From http://pad.lv/799212
2866
unicode_user = u'b\N{Euro Sign}ar'
2867
unicode_content = u'user=%s' % (unicode_user,)
2868
utf8_content = unicode_content.encode('utf8')
2869
# Store the raw content in the config file
2870
with open('foo.conf', 'wb') as f:
2871
f.write(utf8_content)
2872
conf = config.IniBasedConfig(file_name='foo.conf')
2873
self.assertEquals(unicode_user, conf.get_user_option('user'))
2875
def test_load_badly_encoded_content(self):
2876
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2877
with open('foo.conf', 'wb') as f:
2878
f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2879
conf = config.IniBasedConfig(file_name='foo.conf')
2880
self.assertRaises(errors.ConfigContentError, conf._get_parser)
2882
def test_load_erroneous_content(self):
2883
"""Ensure we display a proper error on content that can't be parsed."""
2884
with open('foo.conf', 'wb') as f:
2885
f.write('[open_section\n')
2886
conf = config.IniBasedConfig(file_name='foo.conf')
2887
self.assertRaises(errors.ParseConfigError, conf._get_parser)
2890
class TestMutableStore(TestStore):
2892
scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2893
in config.test_store_builder_registry.iteritems()]
2896
super(TestMutableStore, self).setUp()
2897
self.transport = self.get_transport()
2899
def has_store(self, store):
2900
store_basename = urlutils.relative_url(self.transport.external_url(),
2901
store.external_url())
2902
return self.transport.has(store_basename)
2904
def test_save_empty_creates_no_file(self):
2905
# FIXME: There should be a better way than relying on the test
2906
# parametrization to identify branch.conf -- vila 2011-0526
2907
if self.store_id in ('branch', 'remote_branch'):
2908
raise tests.TestNotApplicable(
2909
'branch.conf is *always* created when a branch is initialized')
2910
store = self.get_store(self)
2912
self.assertEquals(False, self.has_store(store))
2914
def test_save_emptied_succeeds(self):
2915
store = self.get_store(self)
2916
store._load_from_string('foo=bar\n')
2917
section = store.get_mutable_section(None)
2918
section.remove('foo')
2920
self.assertEquals(True, self.has_store(store))
2921
modified_store = self.get_store(self)
2922
sections = list(modified_store.get_sections())
2923
self.assertLength(0, sections)
2925
def test_save_with_content_succeeds(self):
2926
# FIXME: There should be a better way than relying on the test
2927
# parametrization to identify branch.conf -- vila 2011-0526
2928
if self.store_id in ('branch', 'remote_branch'):
2929
raise tests.TestNotApplicable(
2930
'branch.conf is *always* created when a branch is initialized')
2931
store = self.get_store(self)
2932
store._load_from_string('foo=bar\n')
2933
self.assertEquals(False, self.has_store(store))
2935
self.assertEquals(True, self.has_store(store))
2936
modified_store = self.get_store(self)
2937
sections = list(modified_store.get_sections())
2938
self.assertLength(1, sections)
2939
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2941
def test_set_option_in_empty_store(self):
2942
store = self.get_store(self)
2943
section = store.get_mutable_section(None)
2944
section.set('foo', 'bar')
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_default_section(self):
2952
store = self.get_store(self)
2953
store._load_from_string('')
2954
section = store.get_mutable_section(None)
2955
section.set('foo', 'bar')
2957
modified_store = self.get_store(self)
2958
sections = list(modified_store.get_sections())
2959
self.assertLength(1, sections)
2960
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2962
def test_set_option_in_named_section(self):
2963
store = self.get_store(self)
2964
store._load_from_string('')
2965
section = store.get_mutable_section('baz')
2966
section.set('foo', 'bar')
2968
modified_store = self.get_store(self)
2969
sections = list(modified_store.get_sections())
2970
self.assertLength(1, sections)
2971
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2973
def test_load_hook(self):
2974
# We first needs to ensure that the store exists
2975
store = self.get_store(self)
2976
section = store.get_mutable_section('baz')
2977
section.set('foo', 'bar')
2979
# Now we can try to load it
2980
store = self.get_store(self)
2984
config.ConfigHooks.install_named_hook('load', hook, None)
2985
self.assertLength(0, calls)
2987
self.assertLength(1, calls)
2988
self.assertEquals((store,), calls[0])
2990
def test_save_hook(self):
2994
config.ConfigHooks.install_named_hook('save', hook, None)
2995
self.assertLength(0, calls)
2996
store = self.get_store(self)
2997
section = store.get_mutable_section('baz')
2998
section.set('foo', 'bar')
3000
self.assertLength(1, calls)
3001
self.assertEquals((store,), calls[0])
3004
class TestQuotingIniFileStore(tests.TestCaseWithTransport):
3006
def get_store(self):
3007
return config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3009
def test_get_quoted_string(self):
3010
store = self.get_store()
3011
store._load_from_string('foo= " abc "')
3012
stack = config.Stack([store.get_sections])
3013
self.assertEquals(' abc ', stack.get('foo'))
3015
def test_set_quoted_string(self):
3016
store = self.get_store()
3017
stack = config.Stack([store.get_sections], store)
3018
stack.set('foo', ' a b c ')
3020
self.assertFileEqual('foo = " a b c "\n', 'foo.conf')
3023
class TestTransportIniFileStore(TestStore):
3025
def test_loading_unknown_file_fails(self):
3026
store = config.TransportIniFileStore(self.get_transport(),
3028
self.assertRaises(errors.NoSuchFile, store.load)
3030
def test_invalid_content(self):
3031
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3032
self.assertEquals(False, store.is_loaded())
3033
exc = self.assertRaises(
3034
errors.ParseConfigError, store._load_from_string,
3035
'this is invalid !')
3036
self.assertEndsWith(exc.filename, 'foo.conf')
3037
# And the load failed
3038
self.assertEquals(False, store.is_loaded())
3040
def test_get_embedded_sections(self):
3041
# A more complicated example (which also shows that section names and
3042
# option names share the same name space...)
3043
# FIXME: This should be fixed by forbidding dicts as values ?
3044
# -- vila 2011-04-05
3045
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3046
store._load_from_string('''
3050
foo_in_DEFAULT=foo_DEFAULT
3058
sections = list(store.get_sections())
3059
self.assertLength(4, sections)
3060
# The default section has no name.
3061
# List values are provided as strings and need to be explicitly
3062
# converted by specifying from_unicode=list_from_store at option
3064
self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
3066
self.assertSectionContent(
3067
('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
3068
self.assertSectionContent(
3069
('bar', {'foo_in_bar': 'barbar'}), sections[2])
3070
# sub sections are provided as embedded dicts.
3071
self.assertSectionContent(
3072
('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
3076
class TestLockableIniFileStore(TestStore):
3078
def test_create_store_in_created_dir(self):
3079
self.assertPathDoesNotExist('dir')
3080
t = self.get_transport('dir/subdir')
3081
store = config.LockableIniFileStore(t, 'foo.conf')
3082
store.get_mutable_section(None).set('foo', 'bar')
3084
self.assertPathExists('dir/subdir')
3087
class TestConcurrentStoreUpdates(TestStore):
3088
"""Test that Stores properly handle conccurent updates.
3090
New Store implementation may fail some of these tests but until such
3091
implementations exist it's hard to properly filter them from the scenarios
3092
applied here. If you encounter such a case, contact the bzr devs.
3095
scenarios = [(key, {'get_stack': builder}) for key, builder
3096
in config.test_stack_builder_registry.iteritems()]
3099
super(TestConcurrentStoreUpdates, self).setUp()
3100
self.stack = self.get_stack(self)
3101
if not isinstance(self.stack, config._CompatibleStack):
3102
raise tests.TestNotApplicable(
3103
'%s is not meant to be compatible with the old config design'
3105
self.stack.set('one', '1')
3106
self.stack.set('two', '2')
3108
self.stack.store.save()
3110
def test_simple_read_access(self):
3111
self.assertEquals('1', self.stack.get('one'))
3113
def test_simple_write_access(self):
3114
self.stack.set('one', 'one')
3115
self.assertEquals('one', self.stack.get('one'))
3117
def test_listen_to_the_last_speaker(self):
3119
c2 = self.get_stack(self)
3120
c1.set('one', 'ONE')
3121
c2.set('two', 'TWO')
3122
self.assertEquals('ONE', c1.get('one'))
3123
self.assertEquals('TWO', c2.get('two'))
3124
# The second update respect the first one
3125
self.assertEquals('ONE', c2.get('one'))
3127
def test_last_speaker_wins(self):
3128
# If the same config is not shared, the same variable modified twice
3129
# can only see a single result.
3131
c2 = self.get_stack(self)
3134
self.assertEquals('c2', c2.get('one'))
3135
# The first modification is still available until another refresh
3137
self.assertEquals('c1', c1.get('one'))
3138
c1.set('two', 'done')
3139
self.assertEquals('c2', c1.get('one'))
3141
def test_writes_are_serialized(self):
3143
c2 = self.get_stack(self)
3145
# We spawn a thread that will pause *during* the config saving.
3146
before_writing = threading.Event()
3147
after_writing = threading.Event()
3148
writing_done = threading.Event()
3149
c1_save_without_locking_orig = c1.store.save_without_locking
3150
def c1_save_without_locking():
3151
before_writing.set()
3152
c1_save_without_locking_orig()
3153
# The lock is held. We wait for the main thread to decide when to
3155
after_writing.wait()
3156
c1.store.save_without_locking = c1_save_without_locking
3160
t1 = threading.Thread(target=c1_set)
3161
# Collect the thread after the test
3162
self.addCleanup(t1.join)
3163
# Be ready to unblock the thread if the test goes wrong
3164
self.addCleanup(after_writing.set)
3166
before_writing.wait()
3167
self.assertRaises(errors.LockContention,
3168
c2.set, 'one', 'c2')
3169
self.assertEquals('c1', c1.get('one'))
3170
# Let the lock be released
3174
self.assertEquals('c2', c2.get('one'))
3176
def test_read_while_writing(self):
3178
# We spawn a thread that will pause *during* the write
3179
ready_to_write = threading.Event()
3180
do_writing = threading.Event()
3181
writing_done = threading.Event()
3182
# We override the _save implementation so we know the store is locked
3183
c1_save_without_locking_orig = c1.store.save_without_locking
3184
def c1_save_without_locking():
3185
ready_to_write.set()
3186
# The lock is held. We wait for the main thread to decide when to
3189
c1_save_without_locking_orig()
3191
c1.store.save_without_locking = c1_save_without_locking
3194
t1 = threading.Thread(target=c1_set)
3195
# Collect the thread after the test
3196
self.addCleanup(t1.join)
3197
# Be ready to unblock the thread if the test goes wrong
3198
self.addCleanup(do_writing.set)
3200
# Ensure the thread is ready to write
3201
ready_to_write.wait()
3202
self.assertEquals('c1', c1.get('one'))
3203
# If we read during the write, we get the old value
3204
c2 = self.get_stack(self)
3205
self.assertEquals('1', c2.get('one'))
3206
# Let the writing occur and ensure it occurred
3209
# Now we get the updated value
3210
c3 = self.get_stack(self)
3211
self.assertEquals('c1', c3.get('one'))
3213
# FIXME: It may be worth looking into removing the lock dir when it's not
3214
# needed anymore and look at possible fallouts for concurrent lockers. This
3215
# will matter if/when we use config files outside of bazaar directories
3216
# (.bazaar or .bzr) -- vila 20110-04-111
3219
class TestSectionMatcher(TestStore):
3221
scenarios = [('location', {'matcher': config.LocationMatcher}),
3222
('id', {'matcher': config.NameMatcher}),]
3225
super(TestSectionMatcher, self).setUp()
3226
# Any simple store is good enough
3227
self.get_store = config.test_store_builder_registry.get('configobj')
3229
def test_no_matches_for_empty_stores(self):
3230
store = self.get_store(self)
3231
store._load_from_string('')
3232
matcher = self.matcher(store, '/bar')
3233
self.assertEquals([], list(matcher.get_sections()))
3235
def test_build_doesnt_load_store(self):
3236
store = self.get_store(self)
3237
matcher = self.matcher(store, '/bar')
3238
self.assertFalse(store.is_loaded())
3241
class TestLocationSection(tests.TestCase):
3243
def get_section(self, options, extra_path):
3244
section = config.Section('foo', options)
3245
# We don't care about the length so we use '0'
3246
return config.LocationSection(section, 0, extra_path)
3248
def test_simple_option(self):
3249
section = self.get_section({'foo': 'bar'}, '')
3250
self.assertEquals('bar', section.get('foo'))
3252
def test_option_with_extra_path(self):
3253
section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
3255
self.assertEquals('bar/baz', section.get('foo'))
3257
def test_invalid_policy(self):
3258
section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
3260
# invalid policies are ignored
3261
self.assertEquals('bar', section.get('foo'))
3264
class TestLocationMatcher(TestStore):
3267
super(TestLocationMatcher, self).setUp()
3268
# Any simple store is good enough
3269
self.get_store = config.test_store_builder_registry.get('configobj')
3271
def test_unrelated_section_excluded(self):
3272
store = self.get_store(self)
3273
store._load_from_string('''
3281
section=/foo/bar/baz
3285
self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3287
[section.id for _, section in store.get_sections()])
3288
matcher = config.LocationMatcher(store, '/foo/bar/quux')
3289
sections = [section for s, section in matcher.get_sections()]
3290
self.assertEquals([3, 2],
3291
[section.length for section in sections])
3292
self.assertEquals(['/foo/bar', '/foo'],
3293
[section.id for section in sections])
3294
self.assertEquals(['quux', 'bar/quux'],
3295
[section.extra_path for section in sections])
3297
def test_more_specific_sections_first(self):
3298
store = self.get_store(self)
3299
store._load_from_string('''
3305
self.assertEquals(['/foo', '/foo/bar'],
3306
[section.id for _, section in store.get_sections()])
3307
matcher = config.LocationMatcher(store, '/foo/bar/baz')
3308
sections = [section for s, section in matcher.get_sections()]
3309
self.assertEquals([3, 2],
3310
[section.length for section in sections])
3311
self.assertEquals(['/foo/bar', '/foo'],
3312
[section.id for section in sections])
3313
self.assertEquals(['baz', 'bar/baz'],
3314
[section.extra_path for section in sections])
3316
def test_appendpath_in_no_name_section(self):
3317
# It's a bit weird to allow appendpath in a no-name section, but
3318
# someone may found a use for it
3319
store = self.get_store(self)
3320
store._load_from_string('''
3322
foo:policy = appendpath
3324
matcher = config.LocationMatcher(store, 'dir/subdir')
3325
sections = list(matcher.get_sections())
3326
self.assertLength(1, sections)
3327
self.assertEquals('bar/dir/subdir', sections[0][1].get('foo'))
3329
def test_file_urls_are_normalized(self):
3330
store = self.get_store(self)
3331
if sys.platform == 'win32':
3332
expected_url = 'file:///C:/dir/subdir'
3333
expected_location = 'C:/dir/subdir'
3335
expected_url = 'file:///dir/subdir'
3336
expected_location = '/dir/subdir'
3337
matcher = config.LocationMatcher(store, expected_url)
3338
self.assertEquals(expected_location, matcher.location)
3341
class TestNameMatcher(TestStore):
3344
super(TestNameMatcher, self).setUp()
3345
self.matcher = config.NameMatcher
3346
# Any simple store is good enough
3347
self.get_store = config.test_store_builder_registry.get('configobj')
3349
def get_matching_sections(self, name):
3350
store = self.get_store(self)
3351
store._load_from_string('''
3359
matcher = self.matcher(store, name)
3360
return list(matcher.get_sections())
3362
def test_matching(self):
3363
sections = self.get_matching_sections('foo')
3364
self.assertLength(1, sections)
3365
self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3367
def test_not_matching(self):
3368
sections = self.get_matching_sections('baz')
3369
self.assertLength(0, sections)
3372
class TestBaseStackGet(tests.TestCase):
3375
super(TestBaseStackGet, self).setUp()
3376
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3378
def test_get_first_definition(self):
3379
store1 = config.IniFileStore()
3380
store1._load_from_string('foo=bar')
3381
store2 = config.IniFileStore()
3382
store2._load_from_string('foo=baz')
3383
conf = config.Stack([store1.get_sections, store2.get_sections])
3384
self.assertEquals('bar', conf.get('foo'))
3386
def test_get_with_registered_default_value(self):
3387
config.option_registry.register(config.Option('foo', default='bar'))
3388
conf_stack = config.Stack([])
3389
self.assertEquals('bar', conf_stack.get('foo'))
3391
def test_get_without_registered_default_value(self):
3392
config.option_registry.register(config.Option('foo'))
3393
conf_stack = config.Stack([])
3394
self.assertEquals(None, conf_stack.get('foo'))
3396
def test_get_without_default_value_for_not_registered(self):
3397
conf_stack = config.Stack([])
3398
self.assertEquals(None, conf_stack.get('foo'))
3400
def test_get_for_empty_section_callable(self):
3401
conf_stack = config.Stack([lambda : []])
3402
self.assertEquals(None, conf_stack.get('foo'))
3404
def test_get_for_broken_callable(self):
3405
# Trying to use and invalid callable raises an exception on first use
3406
conf_stack = config.Stack([object])
3407
self.assertRaises(TypeError, conf_stack.get, 'foo')
3410
class TestStackWithSimpleStore(tests.TestCase):
3413
super(TestStackWithSimpleStore, self).setUp()
3414
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3415
self.registry = config.option_registry
3417
def get_conf(self, content=None):
3418
return config.MemoryStack(content)
3420
def test_override_value_from_env(self):
3421
self.registry.register(
3422
config.Option('foo', default='bar', override_from_env=['FOO']))
3423
self.overrideEnv('FOO', 'quux')
3424
# Env variable provides a default taking over the option one
3425
conf = self.get_conf('foo=store')
3426
self.assertEquals('quux', conf.get('foo'))
3428
def test_first_override_value_from_env_wins(self):
3429
self.registry.register(
3430
config.Option('foo', default='bar',
3431
override_from_env=['NO_VALUE', 'FOO', 'BAZ']))
3432
self.overrideEnv('FOO', 'foo')
3433
self.overrideEnv('BAZ', 'baz')
3434
# The first env var set wins
3435
conf = self.get_conf('foo=store')
3436
self.assertEquals('foo', conf.get('foo'))
3439
class TestMemoryStack(tests.TestCase):
3442
conf = config.MemoryStack('foo=bar')
3443
self.assertEquals('bar', conf.get('foo'))
3446
conf = config.MemoryStack('foo=bar')
3447
conf.set('foo', 'baz')
3448
self.assertEquals('baz', conf.get('foo'))
3450
def test_no_content(self):
3451
conf = config.MemoryStack()
3452
# No content means no loading
3453
self.assertFalse(conf.store.is_loaded())
3454
self.assertRaises(NotImplementedError, conf.get, 'foo')
3455
# But a content can still be provided
3456
conf.store._load_from_string('foo=bar')
3457
self.assertEquals('bar', conf.get('foo'))
3460
class TestStackWithTransport(tests.TestCaseWithTransport):
3462
scenarios = [(key, {'get_stack': builder}) for key, builder
3463
in config.test_stack_builder_registry.iteritems()]
3466
class TestConcreteStacks(TestStackWithTransport):
3468
def test_build_stack(self):
3469
# Just a smoke test to help debug builders
3470
stack = self.get_stack(self)
3473
class TestStackGet(TestStackWithTransport):
3476
super(TestStackGet, self).setUp()
3477
self.conf = self.get_stack(self)
3479
def test_get_for_empty_stack(self):
3480
self.assertEquals(None, self.conf.get('foo'))
3482
def test_get_hook(self):
3483
self.conf.set('foo', 'bar')
3487
config.ConfigHooks.install_named_hook('get', hook, None)
3488
self.assertLength(0, calls)
3489
value = self.conf.get('foo')
3490
self.assertEquals('bar', value)
3491
self.assertLength(1, calls)
3492
self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3495
class TestStackGetWithConverter(tests.TestCase):
3498
super(TestStackGetWithConverter, self).setUp()
3499
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3500
self.registry = config.option_registry
3502
def get_conf(self, content=None):
3503
return config.MemoryStack(content)
3505
def register_bool_option(self, name, default=None, default_from_env=None):
3506
b = config.Option(name, help='A boolean.',
3507
default=default, default_from_env=default_from_env,
3508
from_unicode=config.bool_from_store)
3509
self.registry.register(b)
3511
def test_get_default_bool_None(self):
3512
self.register_bool_option('foo')
3513
conf = self.get_conf('')
3514
self.assertEquals(None, conf.get('foo'))
3516
def test_get_default_bool_True(self):
3517
self.register_bool_option('foo', u'True')
3518
conf = self.get_conf('')
3519
self.assertEquals(True, conf.get('foo'))
3521
def test_get_default_bool_False(self):
3522
self.register_bool_option('foo', False)
3523
conf = self.get_conf('')
3524
self.assertEquals(False, conf.get('foo'))
3526
def test_get_default_bool_False_as_string(self):
3527
self.register_bool_option('foo', u'False')
3528
conf = self.get_conf('')
3529
self.assertEquals(False, conf.get('foo'))
3531
def test_get_default_bool_from_env_converted(self):
3532
self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3533
self.overrideEnv('FOO', 'False')
3534
conf = self.get_conf('')
3535
self.assertEquals(False, conf.get('foo'))
3537
def test_get_default_bool_when_conversion_fails(self):
3538
self.register_bool_option('foo', default='True')
3539
conf = self.get_conf('foo=invalid boolean')
3540
self.assertEquals(True, conf.get('foo'))
3542
def register_integer_option(self, name,
3543
default=None, default_from_env=None):
3544
i = config.Option(name, help='An integer.',
3545
default=default, default_from_env=default_from_env,
3546
from_unicode=config.int_from_store)
3547
self.registry.register(i)
3549
def test_get_default_integer_None(self):
3550
self.register_integer_option('foo')
3551
conf = self.get_conf('')
3552
self.assertEquals(None, conf.get('foo'))
3554
def test_get_default_integer(self):
3555
self.register_integer_option('foo', 42)
3556
conf = self.get_conf('')
3557
self.assertEquals(42, conf.get('foo'))
3559
def test_get_default_integer_as_string(self):
3560
self.register_integer_option('foo', u'42')
3561
conf = self.get_conf('')
3562
self.assertEquals(42, conf.get('foo'))
3564
def test_get_default_integer_from_env(self):
3565
self.register_integer_option('foo', default_from_env=['FOO'])
3566
self.overrideEnv('FOO', '18')
3567
conf = self.get_conf('')
3568
self.assertEquals(18, conf.get('foo'))
3570
def test_get_default_integer_when_conversion_fails(self):
3571
self.register_integer_option('foo', default='12')
3572
conf = self.get_conf('foo=invalid integer')
3573
self.assertEquals(12, conf.get('foo'))
3575
def register_list_option(self, name, default=None, default_from_env=None):
3576
l = config.ListOption(name, help='A list.', default=default,
3577
default_from_env=default_from_env)
3578
self.registry.register(l)
3580
def test_get_default_list_None(self):
3581
self.register_list_option('foo')
3582
conf = self.get_conf('')
3583
self.assertEquals(None, conf.get('foo'))
3585
def test_get_default_list_empty(self):
3586
self.register_list_option('foo', '')
3587
conf = self.get_conf('')
3588
self.assertEquals([], conf.get('foo'))
3590
def test_get_default_list_from_env(self):
3591
self.register_list_option('foo', default_from_env=['FOO'])
3592
self.overrideEnv('FOO', '')
3593
conf = self.get_conf('')
3594
self.assertEquals([], conf.get('foo'))
3596
def test_get_with_list_converter_no_item(self):
3597
self.register_list_option('foo', None)
3598
conf = self.get_conf('foo=,')
3599
self.assertEquals([], conf.get('foo'))
3601
def test_get_with_list_converter_many_items(self):
3602
self.register_list_option('foo', None)
3603
conf = self.get_conf('foo=m,o,r,e')
3604
self.assertEquals(['m', 'o', 'r', 'e'], conf.get('foo'))
3606
def test_get_with_list_converter_embedded_spaces_many_items(self):
3607
self.register_list_option('foo', None)
3608
conf = self.get_conf('foo=" bar", "baz "')
3609
self.assertEquals([' bar', 'baz '], conf.get('foo'))
3611
def test_get_with_list_converter_stripped_spaces_many_items(self):
3612
self.register_list_option('foo', None)
3613
conf = self.get_conf('foo= bar , baz ')
3614
self.assertEquals(['bar', 'baz'], conf.get('foo'))
3617
class TestIterOptionRefs(tests.TestCase):
3618
"""iter_option_refs is a bit unusual, document some cases."""
3620
def assertRefs(self, expected, string):
3621
self.assertEquals(expected, list(config.iter_option_refs(string)))
3623
def test_empty(self):
3624
self.assertRefs([(False, '')], '')
3626
def test_no_refs(self):
3627
self.assertRefs([(False, 'foo bar')], 'foo bar')
3629
def test_single_ref(self):
3630
self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
3632
def test_broken_ref(self):
3633
self.assertRefs([(False, '{foo')], '{foo')
3635
def test_embedded_ref(self):
3636
self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
3639
def test_two_refs(self):
3640
self.assertRefs([(False, ''), (True, '{foo}'),
3641
(False, ''), (True, '{bar}'),
3645
def test_newline_in_refs_are_not_matched(self):
3646
self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
3649
class TestStackExpandOptions(tests.TestCaseWithTransport):
3652
super(TestStackExpandOptions, self).setUp()
3653
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3654
self.registry = config.option_registry
3655
self.conf = build_branch_stack(self)
3657
def assertExpansion(self, expected, string, env=None):
3658
self.assertEquals(expected, self.conf.expand_options(string, env))
3660
def test_no_expansion(self):
3661
self.assertExpansion('foo', 'foo')
3663
def test_expand_default_value(self):
3664
self.conf.store._load_from_string('bar=baz')
3665
self.registry.register(config.Option('foo', default=u'{bar}'))
3666
self.assertEquals('baz', self.conf.get('foo', expand=True))
3668
def test_expand_default_from_env(self):
3669
self.conf.store._load_from_string('bar=baz')
3670
self.registry.register(config.Option('foo', default_from_env=['FOO']))
3671
self.overrideEnv('FOO', '{bar}')
3672
self.assertEquals('baz', self.conf.get('foo', expand=True))
3674
def test_expand_default_on_failed_conversion(self):
3675
self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
3676
self.registry.register(
3677
config.Option('foo', default=u'{bar}',
3678
from_unicode=config.int_from_store))
3679
self.assertEquals(42, self.conf.get('foo', expand=True))
3681
def test_env_adding_options(self):
3682
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3684
def test_env_overriding_options(self):
3685
self.conf.store._load_from_string('foo=baz')
3686
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3688
def test_simple_ref(self):
3689
self.conf.store._load_from_string('foo=xxx')
3690
self.assertExpansion('xxx', '{foo}')
3692
def test_unknown_ref(self):
3693
self.assertRaises(errors.ExpandingUnknownOption,
3694
self.conf.expand_options, '{foo}')
3696
def test_indirect_ref(self):
3697
self.conf.store._load_from_string('''
3701
self.assertExpansion('xxx', '{bar}')
3703
def test_embedded_ref(self):
3704
self.conf.store._load_from_string('''
3708
self.assertExpansion('xxx', '{{bar}}')
3710
def test_simple_loop(self):
3711
self.conf.store._load_from_string('foo={foo}')
3712
self.assertRaises(errors.OptionExpansionLoop,
3713
self.conf.expand_options, '{foo}')
3715
def test_indirect_loop(self):
3716
self.conf.store._load_from_string('''
3720
e = self.assertRaises(errors.OptionExpansionLoop,
3721
self.conf.expand_options, '{foo}')
3722
self.assertEquals('foo->bar->baz', e.refs)
3723
self.assertEquals('{foo}', e.string)
3725
def test_list(self):
3726
self.conf.store._load_from_string('''
3730
list={foo},{bar},{baz}
3732
self.registry.register(
3733
config.ListOption('list'))
3734
self.assertEquals(['start', 'middle', 'end'],
3735
self.conf.get('list', expand=True))
3737
def test_cascading_list(self):
3738
self.conf.store._load_from_string('''
3744
self.registry.register(
3745
config.ListOption('list'))
3746
self.assertEquals(['start', 'middle', 'end'],
3747
self.conf.get('list', expand=True))
3749
def test_pathologically_hidden_list(self):
3750
self.conf.store._load_from_string('''
3756
hidden={start}{middle}{end}
3758
# What matters is what the registration says, the conversion happens
3759
# only after all expansions have been performed
3760
self.registry.register(config.ListOption('hidden'))
3761
self.assertEquals(['bin', 'go'],
3762
self.conf.get('hidden', expand=True))
3765
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3768
super(TestStackCrossSectionsExpand, self).setUp()
3770
def get_config(self, location, string):
3773
# Since we don't save the config we won't strictly require to inherit
3774
# from TestCaseInTempDir, but an error occurs so quickly...
3775
c = config.LocationStack(location)
3776
c.store._load_from_string(string)
3779
def test_dont_cross_unrelated_section(self):
3780
c = self.get_config('/another/branch/path','''
3785
[/another/branch/path]
3788
self.assertRaises(errors.ExpandingUnknownOption,
3789
c.get, 'bar', expand=True)
3791
def test_cross_related_sections(self):
3792
c = self.get_config('/project/branch/path','''
3796
[/project/branch/path]
3799
self.assertEquals('quux', c.get('bar', expand=True))
3802
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
3804
def test_cross_global_locations(self):
3805
l_store = config.LocationStore()
3806
l_store._load_from_string('''
3812
g_store = config.GlobalStore()
3813
g_store._load_from_string('''
3819
stack = config.LocationStack('/branch')
3820
self.assertEquals('glob-bar', stack.get('lbar', expand=True))
3821
self.assertEquals('loc-foo', stack.get('gfoo', expand=True))
3824
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
3826
def test_expand_locals_empty(self):
3827
l_store = config.LocationStore()
3828
l_store._load_from_string('''
3829
[/home/user/project]
3834
stack = config.LocationStack('/home/user/project/')
3835
self.assertEquals('', stack.get('base', expand=True))
3836
self.assertEquals('', stack.get('rel', expand=True))
3838
def test_expand_basename_locally(self):
3839
l_store = config.LocationStore()
3840
l_store._load_from_string('''
3841
[/home/user/project]
3845
stack = config.LocationStack('/home/user/project/branch')
3846
self.assertEquals('branch', stack.get('bfoo', expand=True))
3848
def test_expand_basename_locally_longer_path(self):
3849
l_store = config.LocationStore()
3850
l_store._load_from_string('''
3855
stack = config.LocationStack('/home/user/project/dir/branch')
3856
self.assertEquals('branch', stack.get('bfoo', expand=True))
3858
def test_expand_relpath_locally(self):
3859
l_store = config.LocationStore()
3860
l_store._load_from_string('''
3861
[/home/user/project]
3862
lfoo = loc-foo/{relpath}
3865
stack = config.LocationStack('/home/user/project/branch')
3866
self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
3868
def test_expand_relpath_unknonw_in_global(self):
3869
g_store = config.GlobalStore()
3870
g_store._load_from_string('''
3875
stack = config.LocationStack('/home/user/project/branch')
3876
self.assertRaises(errors.ExpandingUnknownOption,
3877
stack.get, 'gfoo', expand=True)
3879
def test_expand_local_option_locally(self):
3880
l_store = config.LocationStore()
3881
l_store._load_from_string('''
3882
[/home/user/project]
3883
lfoo = loc-foo/{relpath}
3887
g_store = config.GlobalStore()
3888
g_store._load_from_string('''
3894
stack = config.LocationStack('/home/user/project/branch')
3895
self.assertEquals('glob-bar', stack.get('lbar', expand=True))
3896
self.assertEquals('loc-foo/branch', stack.get('gfoo', expand=True))
3898
def test_locals_dont_leak(self):
3899
"""Make sure we chose the right local in presence of several sections.
3901
l_store = config.LocationStore()
3902
l_store._load_from_string('''
3904
lfoo = loc-foo/{relpath}
3905
[/home/user/project]
3906
lfoo = loc-foo/{relpath}
3909
stack = config.LocationStack('/home/user/project/branch')
3910
self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
3911
stack = config.LocationStack('/home/user/bar/baz')
3912
self.assertEquals('loc-foo/bar/baz', stack.get('lfoo', expand=True))
3916
class TestStackSet(TestStackWithTransport):
3918
def test_simple_set(self):
3919
conf = self.get_stack(self)
3920
self.assertEquals(None, conf.get('foo'))
3921
conf.set('foo', 'baz')
3922
# Did we get it back ?
3923
self.assertEquals('baz', conf.get('foo'))
3925
def test_set_creates_a_new_section(self):
3926
conf = self.get_stack(self)
3927
conf.set('foo', 'baz')
3928
self.assertEquals, 'baz', conf.get('foo')
3930
def test_set_hook(self):
3934
config.ConfigHooks.install_named_hook('set', hook, None)
3935
self.assertLength(0, calls)
3936
conf = self.get_stack(self)
3937
conf.set('foo', 'bar')
3938
self.assertLength(1, calls)
3939
self.assertEquals((conf, 'foo', 'bar'), calls[0])
3942
class TestStackRemove(TestStackWithTransport):
3944
def test_remove_existing(self):
3945
conf = self.get_stack(self)
3946
conf.set('foo', 'bar')
3947
self.assertEquals('bar', conf.get('foo'))
3949
# Did we get it back ?
3950
self.assertEquals(None, conf.get('foo'))
3952
def test_remove_unknown(self):
3953
conf = self.get_stack(self)
3954
self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3956
def test_remove_hook(self):
3960
config.ConfigHooks.install_named_hook('remove', hook, None)
3961
self.assertLength(0, calls)
3962
conf = self.get_stack(self)
3963
conf.set('foo', 'bar')
3965
self.assertLength(1, calls)
3966
self.assertEquals((conf, 'foo'), calls[0])
3969
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3972
super(TestConfigGetOptions, self).setUp()
3973
create_configs(self)
3975
def test_no_variable(self):
3976
# Using branch should query branch, locations and bazaar
3977
self.assertOptions([], self.branch_config)
3979
def test_option_in_bazaar(self):
3980
self.bazaar_config.set_user_option('file', 'bazaar')
3981
self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
3984
def test_option_in_locations(self):
3985
self.locations_config.set_user_option('file', 'locations')
3987
[('file', 'locations', self.tree.basedir, 'locations')],
3988
self.locations_config)
3990
def test_option_in_branch(self):
3991
self.branch_config.set_user_option('file', 'branch')
3992
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
3995
def test_option_in_bazaar_and_branch(self):
3996
self.bazaar_config.set_user_option('file', 'bazaar')
3997
self.branch_config.set_user_option('file', 'branch')
3998
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
3999
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
4002
def test_option_in_branch_and_locations(self):
4003
# Hmm, locations override branch :-/
4004
self.locations_config.set_user_option('file', 'locations')
4005
self.branch_config.set_user_option('file', 'branch')
4007
[('file', 'locations', self.tree.basedir, 'locations'),
4008
('file', 'branch', 'DEFAULT', 'branch'),],
4011
def test_option_in_bazaar_locations_and_branch(self):
4012
self.bazaar_config.set_user_option('file', 'bazaar')
4013
self.locations_config.set_user_option('file', 'locations')
4014
self.branch_config.set_user_option('file', 'branch')
4016
[('file', 'locations', self.tree.basedir, 'locations'),
4017
('file', 'branch', 'DEFAULT', 'branch'),
4018
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
4022
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
4025
super(TestConfigRemoveOption, self).setUp()
4026
create_configs_with_file_option(self)
4028
def test_remove_in_locations(self):
4029
self.locations_config.remove_user_option('file', self.tree.basedir)
4031
[('file', 'branch', 'DEFAULT', 'branch'),
4032
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
4035
def test_remove_in_branch(self):
4036
self.branch_config.remove_user_option('file')
4038
[('file', 'locations', self.tree.basedir, 'locations'),
4039
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
4042
def test_remove_in_bazaar(self):
4043
self.bazaar_config.remove_user_option('file')
4045
[('file', 'locations', self.tree.basedir, 'locations'),
4046
('file', 'branch', 'DEFAULT', 'branch'),],
4050
class TestConfigGetSections(tests.TestCaseWithTransport):
4053
super(TestConfigGetSections, self).setUp()
4054
create_configs(self)
4056
def assertSectionNames(self, expected, conf, name=None):
4057
"""Check which sections are returned for a given config.
4059
If fallback configurations exist their sections can be included.
4061
:param expected: A list of section names.
4063
:param conf: The configuration that will be queried.
4065
:param name: An optional section name that will be passed to
4068
sections = list(conf._get_sections(name))
4069
self.assertLength(len(expected), sections)
4070
self.assertEqual(expected, [name for name, _, _ in sections])
4072
def test_bazaar_default_section(self):
4073
self.assertSectionNames(['DEFAULT'], self.bazaar_config)
4075
def test_locations_default_section(self):
4076
# No sections are defined in an empty file
4077
self.assertSectionNames([], self.locations_config)
4079
def test_locations_named_section(self):
4080
self.locations_config.set_user_option('file', 'locations')
4081
self.assertSectionNames([self.tree.basedir], self.locations_config)
4083
def test_locations_matching_sections(self):
4084
loc_config = self.locations_config
4085
loc_config.set_user_option('file', 'locations')
4086
# We need to cheat a bit here to create an option in sections above and
4087
# below the 'location' one.
4088
parser = loc_config._get_parser()
4089
# locations.cong deals with '/' ignoring native os.sep
4090
location_names = self.tree.basedir.split('/')
4091
parent = '/'.join(location_names[:-1])
4092
child = '/'.join(location_names + ['child'])
4094
parser[parent]['file'] = 'parent'
4096
parser[child]['file'] = 'child'
4097
self.assertSectionNames([self.tree.basedir, parent], loc_config)
4099
def test_branch_data_default_section(self):
4100
self.assertSectionNames([None],
4101
self.branch_config._get_branch_data_config())
4103
def test_branch_default_sections(self):
4104
# No sections are defined in an empty locations file
4105
self.assertSectionNames([None, 'DEFAULT'],
4107
# Unless we define an option
4108
self.branch_config._get_location_config().set_user_option(
4109
'file', 'locations')
4110
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
4113
def test_bazaar_named_section(self):
4114
# We need to cheat as the API doesn't give direct access to sections
4115
# other than DEFAULT.
4116
self.bazaar_config.set_alias('bazaar', 'bzr')
4117
self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
1315
4120
class TestAuthenticationConfigFile(tests.TestCase):
1316
4121
"""Test the authentication.conf file matching"""