1471
2028
self.assertIs(None, bzrdir_config.get_default_stack_on())
2031
class TestOldConfigHooks(tests.TestCaseWithTransport):
2034
super(TestOldConfigHooks, self).setUp()
2035
create_configs_with_file_option(self)
2037
def assertGetHook(self, conf, name, value):
2041
config.OldConfigHooks.install_named_hook('get', hook, None)
2043
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2044
self.assertLength(0, calls)
2045
actual_value = conf.get_user_option(name)
2046
self.assertEquals(value, actual_value)
2047
self.assertLength(1, calls)
2048
self.assertEquals((conf, name, value), calls[0])
2050
def test_get_hook_bazaar(self):
2051
self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
2053
def test_get_hook_locations(self):
2054
self.assertGetHook(self.locations_config, 'file', 'locations')
2056
def test_get_hook_branch(self):
2057
# Since locations masks branch, we define a different option
2058
self.branch_config.set_user_option('file2', 'branch')
2059
self.assertGetHook(self.branch_config, 'file2', 'branch')
2061
def assertSetHook(self, conf, name, value):
2065
config.OldConfigHooks.install_named_hook('set', hook, None)
2067
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2068
self.assertLength(0, calls)
2069
conf.set_user_option(name, value)
2070
self.assertLength(1, calls)
2071
# We can't assert the conf object below as different configs use
2072
# different means to implement set_user_option and we care only about
2074
self.assertEquals((name, value), calls[0][1:])
2076
def test_set_hook_bazaar(self):
2077
self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
2079
def test_set_hook_locations(self):
2080
self.assertSetHook(self.locations_config, 'foo', 'locations')
2082
def test_set_hook_branch(self):
2083
self.assertSetHook(self.branch_config, 'foo', 'branch')
2085
def assertRemoveHook(self, conf, name, section_name=None):
2089
config.OldConfigHooks.install_named_hook('remove', hook, None)
2091
config.OldConfigHooks.uninstall_named_hook, 'remove', None)
2092
self.assertLength(0, calls)
2093
conf.remove_user_option(name, section_name)
2094
self.assertLength(1, calls)
2095
# We can't assert the conf object below as different configs use
2096
# different means to implement remove_user_option and we care only about
2098
self.assertEquals((name,), calls[0][1:])
2100
def test_remove_hook_bazaar(self):
2101
self.assertRemoveHook(self.bazaar_config, 'file')
2103
def test_remove_hook_locations(self):
2104
self.assertRemoveHook(self.locations_config, 'file',
2105
self.locations_config.location)
2107
def test_remove_hook_branch(self):
2108
self.assertRemoveHook(self.branch_config, 'file')
2110
def assertLoadHook(self, name, conf_class, *conf_args):
2114
config.OldConfigHooks.install_named_hook('load', hook, None)
2116
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2117
self.assertLength(0, calls)
2119
conf = conf_class(*conf_args)
2120
# Access an option to trigger a load
2121
conf.get_user_option(name)
2122
self.assertLength(1, calls)
2123
# Since we can't assert about conf, we just use the number of calls ;-/
2125
def test_load_hook_bazaar(self):
2126
self.assertLoadHook('file', config.GlobalConfig)
2128
def test_load_hook_locations(self):
2129
self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
2131
def test_load_hook_branch(self):
2132
self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
2134
def assertSaveHook(self, conf):
2138
config.OldConfigHooks.install_named_hook('save', hook, None)
2140
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2141
self.assertLength(0, calls)
2142
# Setting an option triggers a save
2143
conf.set_user_option('foo', 'bar')
2144
self.assertLength(1, calls)
2145
# Since we can't assert about conf, we just use the number of calls ;-/
2147
def test_save_hook_bazaar(self):
2148
self.assertSaveHook(self.bazaar_config)
2150
def test_save_hook_locations(self):
2151
self.assertSaveHook(self.locations_config)
2153
def test_save_hook_branch(self):
2154
self.assertSaveHook(self.branch_config)
2157
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
2158
"""Tests config hooks for remote configs.
2160
No tests for the remove hook as this is not implemented there.
2164
super(TestOldConfigHooksForRemote, self).setUp()
2165
self.transport_server = test_server.SmartTCPServer_for_testing
2166
create_configs_with_file_option(self)
2168
def assertGetHook(self, conf, name, value):
2172
config.OldConfigHooks.install_named_hook('get', hook, None)
2174
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2175
self.assertLength(0, calls)
2176
actual_value = conf.get_option(name)
2177
self.assertEquals(value, actual_value)
2178
self.assertLength(1, calls)
2179
self.assertEquals((conf, name, value), calls[0])
2181
def test_get_hook_remote_branch(self):
2182
remote_branch = branch.Branch.open(self.get_url('tree'))
2183
self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2185
def test_get_hook_remote_bzrdir(self):
2186
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2187
conf = remote_bzrdir._get_config()
2188
conf.set_option('remotedir', 'file')
2189
self.assertGetHook(conf, 'file', 'remotedir')
2191
def assertSetHook(self, conf, name, value):
2195
config.OldConfigHooks.install_named_hook('set', hook, None)
2197
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2198
self.assertLength(0, calls)
2199
conf.set_option(value, name)
2200
self.assertLength(1, calls)
2201
# We can't assert the conf object below as different configs use
2202
# different means to implement set_user_option and we care only about
2204
self.assertEquals((name, value), calls[0][1:])
2206
def test_set_hook_remote_branch(self):
2207
remote_branch = branch.Branch.open(self.get_url('tree'))
2208
self.addCleanup(remote_branch.lock_write().unlock)
2209
self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
2211
def test_set_hook_remote_bzrdir(self):
2212
remote_branch = branch.Branch.open(self.get_url('tree'))
2213
self.addCleanup(remote_branch.lock_write().unlock)
2214
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2215
self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2217
def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2221
config.OldConfigHooks.install_named_hook('load', hook, None)
2223
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2224
self.assertLength(0, calls)
2226
conf = conf_class(*conf_args)
2227
# Access an option to trigger a load
2228
conf.get_option(name)
2229
self.assertLength(expected_nb_calls, calls)
2230
# Since we can't assert about conf, we just use the number of calls ;-/
2232
def test_load_hook_remote_branch(self):
2233
remote_branch = branch.Branch.open(self.get_url('tree'))
2234
self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2236
def test_load_hook_remote_bzrdir(self):
2237
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2238
# The config file doesn't exist, set an option to force its creation
2239
conf = remote_bzrdir._get_config()
2240
conf.set_option('remotedir', 'file')
2241
# We get one call for the server and one call for the client, this is
2242
# caused by the differences in implementations betwen
2243
# SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
2244
# SmartServerBranchGetConfigFile (in smart/branch.py)
2245
self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
2247
def assertSaveHook(self, conf):
2251
config.OldConfigHooks.install_named_hook('save', hook, None)
2253
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2254
self.assertLength(0, calls)
2255
# Setting an option triggers a save
2256
conf.set_option('foo', 'bar')
2257
self.assertLength(1, calls)
2258
# Since we can't assert about conf, we just use the number of calls ;-/
2260
def test_save_hook_remote_branch(self):
2261
remote_branch = branch.Branch.open(self.get_url('tree'))
2262
self.addCleanup(remote_branch.lock_write().unlock)
2263
self.assertSaveHook(remote_branch._get_config())
2265
def test_save_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.assertSaveHook(remote_bzrdir._get_config())
2272
class TestOption(tests.TestCase):
2274
def test_default_value(self):
2275
opt = config.Option('foo', default='bar')
2276
self.assertEquals('bar', opt.get_default())
2278
def test_default_value_from_env(self):
2279
opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2280
self.overrideEnv('FOO', 'quux')
2281
# Env variable provides a default taking over the option one
2282
self.assertEquals('quux', opt.get_default())
2284
def test_first_default_value_from_env_wins(self):
2285
opt = config.Option('foo', default='bar',
2286
default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2287
self.overrideEnv('FOO', 'foo')
2288
self.overrideEnv('BAZ', 'baz')
2289
# The first env var set wins
2290
self.assertEquals('foo', opt.get_default())
2292
def test_not_supported_list_default_value(self):
2293
self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2295
def test_not_supported_object_default_value(self):
2296
self.assertRaises(AssertionError, config.Option, 'foo',
2300
class TestOptionConverterMixin(object):
2302
def assertConverted(self, expected, opt, value):
2303
self.assertEquals(expected, opt.convert_from_unicode(value))
2305
def assertWarns(self, opt, value):
2308
warnings.append(args[0] % args[1:])
2309
self.overrideAttr(trace, 'warning', warning)
2310
self.assertEquals(None, opt.convert_from_unicode(value))
2311
self.assertLength(1, warnings)
2313
'Value "%s" is not valid for "%s"' % (value, opt.name),
2316
def assertErrors(self, opt, value):
2317
self.assertRaises(errors.ConfigOptionValueError,
2318
opt.convert_from_unicode, value)
2320
def assertConvertInvalid(self, opt, invalid_value):
2322
self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2323
opt.invalid = 'warning'
2324
self.assertWarns(opt, invalid_value)
2325
opt.invalid = 'error'
2326
self.assertErrors(opt, invalid_value)
2329
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2331
def get_option(self):
2332
return config.Option('foo', help='A boolean.',
2333
from_unicode=config.bool_from_store)
2335
def test_convert_invalid(self):
2336
opt = self.get_option()
2337
# A string that is not recognized as a boolean
2338
self.assertConvertInvalid(opt, u'invalid-boolean')
2339
# A list of strings is never recognized as a boolean
2340
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2342
def test_convert_valid(self):
2343
opt = self.get_option()
2344
self.assertConverted(True, opt, u'True')
2345
self.assertConverted(True, opt, u'1')
2346
self.assertConverted(False, opt, u'False')
2349
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2351
def get_option(self):
2352
return config.Option('foo', help='An integer.',
2353
from_unicode=config.int_from_store)
2355
def test_convert_invalid(self):
2356
opt = self.get_option()
2357
# A string that is not recognized as an integer
2358
self.assertConvertInvalid(opt, u'forty-two')
2359
# A list of strings is never recognized as an integer
2360
self.assertConvertInvalid(opt, [u'a', u'list'])
2362
def test_convert_valid(self):
2363
opt = self.get_option()
2364
self.assertConverted(16, opt, u'16')
2366
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2368
def get_option(self):
2369
return config.Option('foo', help='A list.',
2370
from_unicode=config.list_from_store)
2372
def test_convert_invalid(self):
2373
# No string is invalid as all forms can be converted to a list
2376
def test_convert_valid(self):
2377
opt = self.get_option()
2378
# An empty string is an empty list
2379
self.assertConverted([], opt, '') # Using a bare str() just in case
2380
self.assertConverted([], opt, u'')
2382
self.assertConverted([u'True'], opt, u'True')
2384
self.assertConverted([u'42'], opt, u'42')
2386
self.assertConverted([u'bar'], opt, u'bar')
2387
# A list remains a list (configObj will turn a string containing commas
2388
# into a list, but that's not what we're testing here)
2389
self.assertConverted([u'foo', u'1', u'True'],
2390
opt, [u'foo', u'1', u'True'])
2393
class TestOptionConverterMixin(object):
2395
def assertConverted(self, expected, opt, value):
2396
self.assertEquals(expected, opt.convert_from_unicode(value))
2398
def assertWarns(self, opt, value):
2401
warnings.append(args[0] % args[1:])
2402
self.overrideAttr(trace, 'warning', warning)
2403
self.assertEquals(None, opt.convert_from_unicode(value))
2404
self.assertLength(1, warnings)
2406
'Value "%s" is not valid for "%s"' % (value, opt.name),
2409
def assertErrors(self, opt, value):
2410
self.assertRaises(errors.ConfigOptionValueError,
2411
opt.convert_from_unicode, value)
2413
def assertConvertInvalid(self, opt, invalid_value):
2415
self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2416
opt.invalid = 'warning'
2417
self.assertWarns(opt, invalid_value)
2418
opt.invalid = 'error'
2419
self.assertErrors(opt, invalid_value)
2422
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2424
def get_option(self):
2425
return config.Option('foo', help='A boolean.',
2426
from_unicode=config.bool_from_store)
2428
def test_convert_invalid(self):
2429
opt = self.get_option()
2430
# A string that is not recognized as a boolean
2431
self.assertConvertInvalid(opt, u'invalid-boolean')
2432
# A list of strings is never recognized as a boolean
2433
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2435
def test_convert_valid(self):
2436
opt = self.get_option()
2437
self.assertConverted(True, opt, u'True')
2438
self.assertConverted(True, opt, u'1')
2439
self.assertConverted(False, opt, u'False')
2442
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2444
def get_option(self):
2445
return config.Option('foo', help='An integer.',
2446
from_unicode=config.int_from_store)
2448
def test_convert_invalid(self):
2449
opt = self.get_option()
2450
# A string that is not recognized as an integer
2451
self.assertConvertInvalid(opt, u'forty-two')
2452
# A list of strings is never recognized as an integer
2453
self.assertConvertInvalid(opt, [u'a', u'list'])
2455
def test_convert_valid(self):
2456
opt = self.get_option()
2457
self.assertConverted(16, opt, u'16')
2460
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2462
def get_option(self):
2463
return config.Option('foo', help='A list.',
2464
from_unicode=config.list_from_store)
2466
def test_convert_invalid(self):
2467
opt = self.get_option()
2468
# We don't even try to convert a list into a list, we only expect
2470
self.assertConvertInvalid(opt, [1])
2471
# No string is invalid as all forms can be converted to a list
2473
def test_convert_valid(self):
2474
opt = self.get_option()
2475
# An empty string is an empty list
2476
self.assertConverted([], opt, '') # Using a bare str() just in case
2477
self.assertConverted([], opt, u'')
2479
self.assertConverted([u'True'], opt, u'True')
2481
self.assertConverted([u'42'], opt, u'42')
2483
self.assertConverted([u'bar'], opt, u'bar')
2486
class TestOptionRegistry(tests.TestCase):
2489
super(TestOptionRegistry, self).setUp()
2490
# Always start with an empty registry
2491
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2492
self.registry = config.option_registry
2494
def test_register(self):
2495
opt = config.Option('foo')
2496
self.registry.register(opt)
2497
self.assertIs(opt, self.registry.get('foo'))
2499
def test_registered_help(self):
2500
opt = config.Option('foo', help='A simple option')
2501
self.registry.register(opt)
2502
self.assertEquals('A simple option', self.registry.get_help('foo'))
2504
lazy_option = config.Option('lazy_foo', help='Lazy help')
2506
def test_register_lazy(self):
2507
self.registry.register_lazy('lazy_foo', self.__module__,
2508
'TestOptionRegistry.lazy_option')
2509
self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2511
def test_registered_lazy_help(self):
2512
self.registry.register_lazy('lazy_foo', self.__module__,
2513
'TestOptionRegistry.lazy_option')
2514
self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2517
class TestRegisteredOptions(tests.TestCase):
2518
"""All registered options should verify some constraints."""
2520
scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2521
in config.option_registry.iteritems()]
2524
super(TestRegisteredOptions, self).setUp()
2525
self.registry = config.option_registry
2527
def test_proper_name(self):
2528
# An option should be registered under its own name, this can't be
2529
# checked at registration time for the lazy ones.
2530
self.assertEquals(self.option_name, self.option.name)
2532
def test_help_is_set(self):
2533
option_help = self.registry.get_help(self.option_name)
2534
self.assertNotEquals(None, option_help)
2535
# Come on, think about the user, he really wants to know what the
2537
self.assertIsNot(None, option_help)
2538
self.assertNotEquals('', option_help)
2541
class TestSection(tests.TestCase):
2543
# FIXME: Parametrize so that all sections produced by Stores run these
2544
# tests -- vila 2011-04-01
2546
def test_get_a_value(self):
2547
a_dict = dict(foo='bar')
2548
section = config.Section('myID', a_dict)
2549
self.assertEquals('bar', section.get('foo'))
2551
def test_get_unknown_option(self):
2553
section = config.Section(None, a_dict)
2554
self.assertEquals('out of thin air',
2555
section.get('foo', 'out of thin air'))
2557
def test_options_is_shared(self):
2559
section = config.Section(None, a_dict)
2560
self.assertIs(a_dict, section.options)
2563
class TestMutableSection(tests.TestCase):
2565
# FIXME: Parametrize so that all sections (including os.environ and the
2566
# ones produced by Stores) run these tests -- vila 2011-04-01
2569
a_dict = dict(foo='bar')
2570
section = config.MutableSection('myID', a_dict)
2571
section.set('foo', 'new_value')
2572
self.assertEquals('new_value', section.get('foo'))
2573
# The change appears in the shared section
2574
self.assertEquals('new_value', a_dict.get('foo'))
2575
# We keep track of the change
2576
self.assertTrue('foo' in section.orig)
2577
self.assertEquals('bar', section.orig.get('foo'))
2579
def test_set_preserve_original_once(self):
2580
a_dict = dict(foo='bar')
2581
section = config.MutableSection('myID', a_dict)
2582
section.set('foo', 'first_value')
2583
section.set('foo', 'second_value')
2584
# We keep track of the original value
2585
self.assertTrue('foo' in section.orig)
2586
self.assertEquals('bar', section.orig.get('foo'))
2588
def test_remove(self):
2589
a_dict = dict(foo='bar')
2590
section = config.MutableSection('myID', a_dict)
2591
section.remove('foo')
2592
# We get None for unknown options via the default value
2593
self.assertEquals(None, section.get('foo'))
2594
# Or we just get the default value
2595
self.assertEquals('unknown', section.get('foo', 'unknown'))
2596
self.assertFalse('foo' in section.options)
2597
# We keep track of the deletion
2598
self.assertTrue('foo' in section.orig)
2599
self.assertEquals('bar', section.orig.get('foo'))
2601
def test_remove_new_option(self):
2603
section = config.MutableSection('myID', a_dict)
2604
section.set('foo', 'bar')
2605
section.remove('foo')
2606
self.assertFalse('foo' in section.options)
2607
# The option didn't exist initially so it we need to keep track of it
2608
# with a special value
2609
self.assertTrue('foo' in section.orig)
2610
self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2613
class TestStore(tests.TestCaseWithTransport):
2615
def assertSectionContent(self, expected, section):
2616
"""Assert that some options have the proper values in a section."""
2617
expected_name, expected_options = expected
2618
self.assertEquals(expected_name, section.id)
2621
dict([(k, section.get(k)) for k in expected_options.keys()]))
2624
class TestReadonlyStore(TestStore):
2626
scenarios = [(key, {'get_store': builder}) for key, builder
2627
in config.test_store_builder_registry.iteritems()]
2629
def test_building_delays_load(self):
2630
store = self.get_store(self)
2631
self.assertEquals(False, store.is_loaded())
2632
store._load_from_string('')
2633
self.assertEquals(True, store.is_loaded())
2635
def test_get_no_sections_for_empty(self):
2636
store = self.get_store(self)
2637
store._load_from_string('')
2638
self.assertEquals([], list(store.get_sections()))
2640
def test_get_default_section(self):
2641
store = self.get_store(self)
2642
store._load_from_string('foo=bar')
2643
sections = list(store.get_sections())
2644
self.assertLength(1, sections)
2645
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2647
def test_get_named_section(self):
2648
store = self.get_store(self)
2649
store._load_from_string('[baz]\nfoo=bar')
2650
sections = list(store.get_sections())
2651
self.assertLength(1, sections)
2652
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2654
def test_load_from_string_fails_for_non_empty_store(self):
2655
store = self.get_store(self)
2656
store._load_from_string('foo=bar')
2657
self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2660
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2661
"""Simulate loading a config store with content of various encodings.
2663
All files produced by bzr are in utf8 content.
2665
Users may modify them manually and end up with a file that can't be
2666
loaded. We need to issue proper error messages in this case.
2669
invalid_utf8_char = '\xff'
2671
def test_load_utf8(self):
2672
"""Ensure we can load an utf8-encoded file."""
2673
t = self.get_transport()
2674
# From http://pad.lv/799212
2675
unicode_user = u'b\N{Euro Sign}ar'
2676
unicode_content = u'user=%s' % (unicode_user,)
2677
utf8_content = unicode_content.encode('utf8')
2678
# Store the raw content in the config file
2679
t.put_bytes('foo.conf', utf8_content)
2680
store = config.IniFileStore(t, 'foo.conf')
2682
stack = config.Stack([store.get_sections], store)
2683
self.assertEquals(unicode_user, stack.get('user'))
2685
def test_load_non_ascii(self):
2686
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2687
t = self.get_transport()
2688
t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2689
store = config.IniFileStore(t, 'foo.conf')
2690
self.assertRaises(errors.ConfigContentError, store.load)
2692
def test_load_erroneous_content(self):
2693
"""Ensure we display a proper error on content that can't be parsed."""
2694
t = self.get_transport()
2695
t.put_bytes('foo.conf', '[open_section\n')
2696
store = config.IniFileStore(t, 'foo.conf')
2697
self.assertRaises(errors.ParseConfigError, store.load)
2699
def test_load_permission_denied(self):
2700
"""Ensure we get warned when trying to load an inaccessible file."""
2703
warnings.append(args[0] % args[1:])
2704
self.overrideAttr(trace, 'warning', warning)
2706
t = self.get_transport()
2708
def get_bytes(relpath):
2709
raise errors.PermissionDenied(relpath, "")
2710
t.get_bytes = get_bytes
2711
store = config.IniFileStore(t, 'foo.conf')
2712
self.assertRaises(errors.PermissionDenied, store.load)
2715
[u'Permission denied while trying to load configuration store %s.'
2716
% store.external_url()])
2719
class TestIniConfigContent(tests.TestCaseWithTransport):
2720
"""Simulate loading a IniBasedConfig with content of various encodings.
2722
All files produced by bzr are in utf8 content.
2724
Users may modify them manually and end up with a file that can't be
2725
loaded. We need to issue proper error messages in this case.
2728
invalid_utf8_char = '\xff'
2730
def test_load_utf8(self):
2731
"""Ensure we can load an utf8-encoded file."""
2732
# From http://pad.lv/799212
2733
unicode_user = u'b\N{Euro Sign}ar'
2734
unicode_content = u'user=%s' % (unicode_user,)
2735
utf8_content = unicode_content.encode('utf8')
2736
# Store the raw content in the config file
2737
with open('foo.conf', 'wb') as f:
2738
f.write(utf8_content)
2739
conf = config.IniBasedConfig(file_name='foo.conf')
2740
self.assertEquals(unicode_user, conf.get_user_option('user'))
2742
def test_load_badly_encoded_content(self):
2743
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2744
with open('foo.conf', 'wb') as f:
2745
f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2746
conf = config.IniBasedConfig(file_name='foo.conf')
2747
self.assertRaises(errors.ConfigContentError, conf._get_parser)
2749
def test_load_erroneous_content(self):
2750
"""Ensure we display a proper error on content that can't be parsed."""
2751
with open('foo.conf', 'wb') as f:
2752
f.write('[open_section\n')
2753
conf = config.IniBasedConfig(file_name='foo.conf')
2754
self.assertRaises(errors.ParseConfigError, conf._get_parser)
2757
class TestMutableStore(TestStore):
2759
scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2760
in config.test_store_builder_registry.iteritems()]
2763
super(TestMutableStore, self).setUp()
2764
self.transport = self.get_transport()
2766
def has_store(self, store):
2767
store_basename = urlutils.relative_url(self.transport.external_url(),
2768
store.external_url())
2769
return self.transport.has(store_basename)
2771
def test_save_empty_creates_no_file(self):
2772
# FIXME: There should be a better way than relying on the test
2773
# parametrization to identify branch.conf -- vila 2011-0526
2774
if self.store_id in ('branch', 'remote_branch'):
2775
raise tests.TestNotApplicable(
2776
'branch.conf is *always* created when a branch is initialized')
2777
store = self.get_store(self)
2779
self.assertEquals(False, self.has_store(store))
2781
def test_save_emptied_succeeds(self):
2782
store = self.get_store(self)
2783
store._load_from_string('foo=bar\n')
2784
section = store.get_mutable_section(None)
2785
section.remove('foo')
2787
self.assertEquals(True, self.has_store(store))
2788
modified_store = self.get_store(self)
2789
sections = list(modified_store.get_sections())
2790
self.assertLength(0, sections)
2792
def test_save_with_content_succeeds(self):
2793
# FIXME: There should be a better way than relying on the test
2794
# parametrization to identify branch.conf -- vila 2011-0526
2795
if self.store_id in ('branch', 'remote_branch'):
2796
raise tests.TestNotApplicable(
2797
'branch.conf is *always* created when a branch is initialized')
2798
store = self.get_store(self)
2799
store._load_from_string('foo=bar\n')
2800
self.assertEquals(False, self.has_store(store))
2802
self.assertEquals(True, self.has_store(store))
2803
modified_store = self.get_store(self)
2804
sections = list(modified_store.get_sections())
2805
self.assertLength(1, sections)
2806
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2808
def test_set_option_in_empty_store(self):
2809
store = self.get_store(self)
2810
section = store.get_mutable_section(None)
2811
section.set('foo', 'bar')
2813
modified_store = self.get_store(self)
2814
sections = list(modified_store.get_sections())
2815
self.assertLength(1, sections)
2816
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2818
def test_set_option_in_default_section(self):
2819
store = self.get_store(self)
2820
store._load_from_string('')
2821
section = store.get_mutable_section(None)
2822
section.set('foo', 'bar')
2824
modified_store = self.get_store(self)
2825
sections = list(modified_store.get_sections())
2826
self.assertLength(1, sections)
2827
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2829
def test_set_option_in_named_section(self):
2830
store = self.get_store(self)
2831
store._load_from_string('')
2832
section = store.get_mutable_section('baz')
2833
section.set('foo', 'bar')
2835
modified_store = self.get_store(self)
2836
sections = list(modified_store.get_sections())
2837
self.assertLength(1, sections)
2838
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2840
def test_load_hook(self):
2841
# We first needs to ensure that the store exists
2842
store = self.get_store(self)
2843
section = store.get_mutable_section('baz')
2844
section.set('foo', 'bar')
2846
# Now we can try to load it
2847
store = self.get_store(self)
2851
config.ConfigHooks.install_named_hook('load', hook, None)
2852
self.assertLength(0, calls)
2854
self.assertLength(1, calls)
2855
self.assertEquals((store,), calls[0])
2857
def test_save_hook(self):
2861
config.ConfigHooks.install_named_hook('save', hook, None)
2862
self.assertLength(0, calls)
2863
store = self.get_store(self)
2864
section = store.get_mutable_section('baz')
2865
section.set('foo', 'bar')
2867
self.assertLength(1, calls)
2868
self.assertEquals((store,), calls[0])
2871
class TestIniFileStore(TestStore):
2873
def test_loading_unknown_file_fails(self):
2874
store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
2875
self.assertRaises(errors.NoSuchFile, store.load)
2877
def test_invalid_content(self):
2878
store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2879
self.assertEquals(False, store.is_loaded())
2880
exc = self.assertRaises(
2881
errors.ParseConfigError, store._load_from_string,
2882
'this is invalid !')
2883
self.assertEndsWith(exc.filename, 'foo.conf')
2884
# And the load failed
2885
self.assertEquals(False, store.is_loaded())
2887
def test_get_embedded_sections(self):
2888
# A more complicated example (which also shows that section names and
2889
# option names share the same name space...)
2890
# FIXME: This should be fixed by forbidding dicts as values ?
2891
# -- vila 2011-04-05
2892
store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2893
store._load_from_string('''
2897
foo_in_DEFAULT=foo_DEFAULT
2905
sections = list(store.get_sections())
2906
self.assertLength(4, sections)
2907
# The default section has no name.
2908
# List values are provided as strings and need to be explicitly
2909
# converted by specifying from_unicode=list_from_store at option
2911
self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
2913
self.assertSectionContent(
2914
('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2915
self.assertSectionContent(
2916
('bar', {'foo_in_bar': 'barbar'}), sections[2])
2917
# sub sections are provided as embedded dicts.
2918
self.assertSectionContent(
2919
('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2923
class TestLockableIniFileStore(TestStore):
2925
def test_create_store_in_created_dir(self):
2926
self.assertPathDoesNotExist('dir')
2927
t = self.get_transport('dir/subdir')
2928
store = config.LockableIniFileStore(t, 'foo.conf')
2929
store.get_mutable_section(None).set('foo', 'bar')
2931
self.assertPathExists('dir/subdir')
2934
class TestConcurrentStoreUpdates(TestStore):
2935
"""Test that Stores properly handle conccurent updates.
2937
New Store implementation may fail some of these tests but until such
2938
implementations exist it's hard to properly filter them from the scenarios
2939
applied here. If you encounter such a case, contact the bzr devs.
2942
scenarios = [(key, {'get_stack': builder}) for key, builder
2943
in config.test_stack_builder_registry.iteritems()]
2946
super(TestConcurrentStoreUpdates, self).setUp()
2947
self._content = 'one=1\ntwo=2\n'
2948
self.stack = self.get_stack(self)
2949
if not isinstance(self.stack, config._CompatibleStack):
2950
raise tests.TestNotApplicable(
2951
'%s is not meant to be compatible with the old config design'
2953
self.stack.store._load_from_string(self._content)
2955
self.stack.store.save()
2957
def test_simple_read_access(self):
2958
self.assertEquals('1', self.stack.get('one'))
2960
def test_simple_write_access(self):
2961
self.stack.set('one', 'one')
2962
self.assertEquals('one', self.stack.get('one'))
2964
def test_listen_to_the_last_speaker(self):
2966
c2 = self.get_stack(self)
2967
c1.set('one', 'ONE')
2968
c2.set('two', 'TWO')
2969
self.assertEquals('ONE', c1.get('one'))
2970
self.assertEquals('TWO', c2.get('two'))
2971
# The second update respect the first one
2972
self.assertEquals('ONE', c2.get('one'))
2974
def test_last_speaker_wins(self):
2975
# If the same config is not shared, the same variable modified twice
2976
# can only see a single result.
2978
c2 = self.get_stack(self)
2981
self.assertEquals('c2', c2.get('one'))
2982
# The first modification is still available until another refresh
2984
self.assertEquals('c1', c1.get('one'))
2985
c1.set('two', 'done')
2986
self.assertEquals('c2', c1.get('one'))
2988
def test_writes_are_serialized(self):
2990
c2 = self.get_stack(self)
2992
# We spawn a thread that will pause *during* the config saving.
2993
before_writing = threading.Event()
2994
after_writing = threading.Event()
2995
writing_done = threading.Event()
2996
c1_save_without_locking_orig = c1.store.save_without_locking
2997
def c1_save_without_locking():
2998
before_writing.set()
2999
c1_save_without_locking_orig()
3000
# The lock is held. We wait for the main thread to decide when to
3002
after_writing.wait()
3003
c1.store.save_without_locking = c1_save_without_locking
3007
t1 = threading.Thread(target=c1_set)
3008
# Collect the thread after the test
3009
self.addCleanup(t1.join)
3010
# Be ready to unblock the thread if the test goes wrong
3011
self.addCleanup(after_writing.set)
3013
before_writing.wait()
3014
self.assertRaises(errors.LockContention,
3015
c2.set, 'one', 'c2')
3016
self.assertEquals('c1', c1.get('one'))
3017
# Let the lock be released
3021
self.assertEquals('c2', c2.get('one'))
3023
def test_read_while_writing(self):
3025
# We spawn a thread that will pause *during* the write
3026
ready_to_write = threading.Event()
3027
do_writing = threading.Event()
3028
writing_done = threading.Event()
3029
# We override the _save implementation so we know the store is locked
3030
c1_save_without_locking_orig = c1.store.save_without_locking
3031
def c1_save_without_locking():
3032
ready_to_write.set()
3033
# The lock is held. We wait for the main thread to decide when to
3036
c1_save_without_locking_orig()
3038
c1.store.save_without_locking = c1_save_without_locking
3041
t1 = threading.Thread(target=c1_set)
3042
# Collect the thread after the test
3043
self.addCleanup(t1.join)
3044
# Be ready to unblock the thread if the test goes wrong
3045
self.addCleanup(do_writing.set)
3047
# Ensure the thread is ready to write
3048
ready_to_write.wait()
3049
self.assertEquals('c1', c1.get('one'))
3050
# If we read during the write, we get the old value
3051
c2 = self.get_stack(self)
3052
self.assertEquals('1', c2.get('one'))
3053
# Let the writing occur and ensure it occurred
3056
# Now we get the updated value
3057
c3 = self.get_stack(self)
3058
self.assertEquals('c1', c3.get('one'))
3060
# FIXME: It may be worth looking into removing the lock dir when it's not
3061
# needed anymore and look at possible fallouts for concurrent lockers. This
3062
# will matter if/when we use config files outside of bazaar directories
3063
# (.bazaar or .bzr) -- vila 20110-04-111
3066
class TestSectionMatcher(TestStore):
3068
scenarios = [('location', {'matcher': config.LocationMatcher}),
3069
('id', {'matcher': config.NameMatcher}),]
3071
def get_store(self, file_name):
3072
return config.IniFileStore(self.get_readonly_transport(), file_name)
3074
def test_no_matches_for_empty_stores(self):
3075
store = self.get_store('foo.conf')
3076
store._load_from_string('')
3077
matcher = self.matcher(store, '/bar')
3078
self.assertEquals([], list(matcher.get_sections()))
3080
def test_build_doesnt_load_store(self):
3081
store = self.get_store('foo.conf')
3082
matcher = self.matcher(store, '/bar')
3083
self.assertFalse(store.is_loaded())
3086
class TestLocationSection(tests.TestCase):
3088
def get_section(self, options, extra_path):
3089
section = config.Section('foo', options)
3090
# We don't care about the length so we use '0'
3091
return config.LocationSection(section, 0, extra_path)
3093
def test_simple_option(self):
3094
section = self.get_section({'foo': 'bar'}, '')
3095
self.assertEquals('bar', section.get('foo'))
3097
def test_option_with_extra_path(self):
3098
section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
3100
self.assertEquals('bar/baz', section.get('foo'))
3102
def test_invalid_policy(self):
3103
section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
3105
# invalid policies are ignored
3106
self.assertEquals('bar', section.get('foo'))
3109
class TestLocationMatcher(TestStore):
3111
def get_store(self, file_name):
3112
return config.IniFileStore(self.get_readonly_transport(), file_name)
3114
def test_unrelated_section_excluded(self):
3115
store = self.get_store('foo.conf')
3116
store._load_from_string('''
3124
section=/foo/bar/baz
3128
self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3130
[section.id for section in store.get_sections()])
3131
matcher = config.LocationMatcher(store, '/foo/bar/quux')
3132
sections = list(matcher.get_sections())
3133
self.assertEquals([3, 2],
3134
[section.length for section in sections])
3135
self.assertEquals(['/foo/bar', '/foo'],
3136
[section.id for section in sections])
3137
self.assertEquals(['quux', 'bar/quux'],
3138
[section.extra_path for section in sections])
3140
def test_more_specific_sections_first(self):
3141
store = self.get_store('foo.conf')
3142
store._load_from_string('''
3148
self.assertEquals(['/foo', '/foo/bar'],
3149
[section.id for section in store.get_sections()])
3150
matcher = config.LocationMatcher(store, '/foo/bar/baz')
3151
sections = list(matcher.get_sections())
3152
self.assertEquals([3, 2],
3153
[section.length for section in sections])
3154
self.assertEquals(['/foo/bar', '/foo'],
3155
[section.id for section in sections])
3156
self.assertEquals(['baz', 'bar/baz'],
3157
[section.extra_path for section in sections])
3159
def test_appendpath_in_no_name_section(self):
3160
# It's a bit weird to allow appendpath in a no-name section, but
3161
# someone may found a use for it
3162
store = self.get_store('foo.conf')
3163
store._load_from_string('''
3165
foo:policy = appendpath
3167
matcher = config.LocationMatcher(store, 'dir/subdir')
3168
sections = list(matcher.get_sections())
3169
self.assertLength(1, sections)
3170
self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
3172
def test_file_urls_are_normalized(self):
3173
store = self.get_store('foo.conf')
3174
if sys.platform == 'win32':
3175
expected_url = 'file:///C:/dir/subdir'
3176
expected_location = 'C:/dir/subdir'
3178
expected_url = 'file:///dir/subdir'
3179
expected_location = '/dir/subdir'
3180
matcher = config.LocationMatcher(store, expected_url)
3181
self.assertEquals(expected_location, matcher.location)
3184
class TestNameMatcher(TestStore):
3187
super(TestNameMatcher, self).setUp()
3188
self.store = config.IniFileStore(self.get_readonly_transport(),
3190
self.store._load_from_string('''
3199
def get_matching_sections(self, name):
3200
matcher = config.NameMatcher(self.store, name)
3201
return list(matcher.get_sections())
3203
def test_matching(self):
3204
sections = self.get_matching_sections('foo')
3205
self.assertLength(1, sections)
3206
self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3208
def test_not_matching(self):
3209
sections = self.get_matching_sections('baz')
3210
self.assertLength(0, sections)
3213
class TestStackGet(tests.TestCase):
3215
# FIXME: This should be parametrized for all known Stack or dedicated
3216
# paramerized tests created to avoid bloating -- vila 2011-03-31
3218
def overrideOptionRegistry(self):
3219
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3221
def test_single_config_get(self):
3222
conf = dict(foo='bar')
3223
conf_stack = config.Stack([conf])
3224
self.assertEquals('bar', conf_stack.get('foo'))
3226
def test_get_with_registered_default_value(self):
3227
conf_stack = config.Stack([dict()])
3228
opt = config.Option('foo', default='bar')
3229
self.overrideOptionRegistry()
3230
config.option_registry.register('foo', opt)
3231
self.assertEquals('bar', conf_stack.get('foo'))
3233
def test_get_without_registered_default_value(self):
3234
conf_stack = config.Stack([dict()])
3235
opt = config.Option('foo')
3236
self.overrideOptionRegistry()
3237
config.option_registry.register('foo', opt)
3238
self.assertEquals(None, conf_stack.get('foo'))
3240
def test_get_without_default_value_for_not_registered(self):
3241
conf_stack = config.Stack([dict()])
3242
opt = config.Option('foo')
3243
self.overrideOptionRegistry()
3244
self.assertEquals(None, conf_stack.get('foo'))
3246
def test_get_first_definition(self):
3247
conf1 = dict(foo='bar')
3248
conf2 = dict(foo='baz')
3249
conf_stack = config.Stack([conf1, conf2])
3250
self.assertEquals('bar', conf_stack.get('foo'))
3252
def test_get_embedded_definition(self):
3253
conf1 = dict(yy='12')
3254
conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
3255
conf_stack = config.Stack([conf1, conf2])
3256
self.assertEquals('baz', conf_stack.get('foo'))
3258
def test_get_for_empty_section_callable(self):
3259
conf_stack = config.Stack([lambda : []])
3260
self.assertEquals(None, conf_stack.get('foo'))
3262
def test_get_for_broken_callable(self):
3263
# Trying to use and invalid callable raises an exception on first use
3264
conf_stack = config.Stack([lambda : object()])
3265
self.assertRaises(TypeError, conf_stack.get, 'foo')
3268
class TestStackWithTransport(tests.TestCaseWithTransport):
3270
scenarios = [(key, {'get_stack': builder}) for key, builder
3271
in config.test_stack_builder_registry.iteritems()]
3274
class TestConcreteStacks(TestStackWithTransport):
3276
def test_build_stack(self):
3277
# Just a smoke test to help debug builders
3278
stack = self.get_stack(self)
3281
class TestStackGet(TestStackWithTransport):
3284
super(TestStackGet, self).setUp()
3285
self.conf = self.get_stack(self)
3287
def test_get_for_empty_stack(self):
3288
self.assertEquals(None, self.conf.get('foo'))
3290
def test_get_hook(self):
3291
self.conf.store._load_from_string('foo=bar')
3295
config.ConfigHooks.install_named_hook('get', hook, None)
3296
self.assertLength(0, calls)
3297
value = self.conf.get('foo')
3298
self.assertEquals('bar', value)
3299
self.assertLength(1, calls)
3300
self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3303
class TestStackGetWithConverter(TestStackGet):
3306
super(TestStackGetWithConverter, self).setUp()
3307
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3308
self.registry = config.option_registry
3310
def register_bool_option(self, name, default=None, default_from_env=None):
3311
b = config.Option(name, help='A boolean.',
3312
default=default, default_from_env=default_from_env,
3313
from_unicode=config.bool_from_store)
3314
self.registry.register(b)
3316
def test_get_default_bool_None(self):
3317
self.register_bool_option('foo')
3318
self.assertEquals(None, self.conf.get('foo'))
3320
def test_get_default_bool_True(self):
3321
self.register_bool_option('foo', u'True')
3322
self.assertEquals(True, self.conf.get('foo'))
3324
def test_get_default_bool_False(self):
3325
self.register_bool_option('foo', False)
3326
self.assertEquals(False, self.conf.get('foo'))
3328
def test_get_default_bool_False_as_string(self):
3329
self.register_bool_option('foo', u'False')
3330
self.assertEquals(False, self.conf.get('foo'))
3332
def test_get_default_bool_from_env_converted(self):
3333
self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3334
self.overrideEnv('FOO', 'False')
3335
self.assertEquals(False, self.conf.get('foo'))
3337
def test_get_default_bool_when_conversion_fails(self):
3338
self.register_bool_option('foo', default='True')
3339
self.conf.store._load_from_string('foo=invalid boolean')
3340
self.assertEquals(True, self.conf.get('foo'))
3342
def register_integer_option(self, name,
3343
default=None, default_from_env=None):
3344
i = config.Option(name, help='An integer.',
3345
default=default, default_from_env=default_from_env,
3346
from_unicode=config.int_from_store)
3347
self.registry.register(i)
3349
def test_get_default_integer_None(self):
3350
self.register_integer_option('foo')
3351
self.assertEquals(None, self.conf.get('foo'))
3353
def test_get_default_integer(self):
3354
self.register_integer_option('foo', 42)
3355
self.assertEquals(42, self.conf.get('foo'))
3357
def test_get_default_integer_as_string(self):
3358
self.register_integer_option('foo', u'42')
3359
self.assertEquals(42, self.conf.get('foo'))
3361
def test_get_default_integer_from_env(self):
3362
self.register_integer_option('foo', default_from_env=['FOO'])
3363
self.overrideEnv('FOO', '18')
3364
self.assertEquals(18, self.conf.get('foo'))
3366
def test_get_default_integer_when_conversion_fails(self):
3367
self.register_integer_option('foo', default='12')
3368
self.conf.store._load_from_string('foo=invalid integer')
3369
self.assertEquals(12, self.conf.get('foo'))
3371
def register_list_option(self, name, default=None, default_from_env=None):
3372
l = config.Option(name, help='A list.',
3373
default=default, default_from_env=default_from_env,
3374
from_unicode=config.list_from_store)
3375
self.registry.register(l)
3377
def test_get_default_list_None(self):
3378
self.register_list_option('foo')
3379
self.assertEquals(None, self.conf.get('foo'))
3381
def test_get_default_list_empty(self):
3382
self.register_list_option('foo', '')
3383
self.assertEquals([], self.conf.get('foo'))
3385
def test_get_default_list_from_env(self):
3386
self.register_list_option('foo', default_from_env=['FOO'])
3387
self.overrideEnv('FOO', '')
3388
self.assertEquals([], self.conf.get('foo'))
3390
def test_get_with_list_converter_no_item(self):
3391
self.register_list_option('foo', None)
3392
self.conf.store._load_from_string('foo=,')
3393
self.assertEquals([], self.conf.get('foo'))
3395
def test_get_with_list_converter_many_items(self):
3396
self.register_list_option('foo', None)
3397
self.conf.store._load_from_string('foo=m,o,r,e')
3398
self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
3400
def test_get_with_list_converter_embedded_spaces_many_items(self):
3401
self.register_list_option('foo', None)
3402
self.conf.store._load_from_string('foo=" bar", "baz "')
3403
self.assertEquals([' bar', 'baz '], self.conf.get('foo'))
3405
def test_get_with_list_converter_stripped_spaces_many_items(self):
3406
self.register_list_option('foo', None)
3407
self.conf.store._load_from_string('foo= bar , baz ')
3408
self.assertEquals(['bar', 'baz'], self.conf.get('foo'))
3411
class TestStackExpandOptions(tests.TestCaseWithTransport):
3414
super(TestStackExpandOptions, self).setUp()
3415
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3416
self.registry = config.option_registry
3417
self.conf = build_branch_stack(self)
3419
def assertExpansion(self, expected, string, env=None):
3420
self.assertEquals(expected, self.conf.expand_options(string, env))
3422
def test_no_expansion(self):
3423
self.assertExpansion('foo', 'foo')
3425
def test_expand_default_value(self):
3426
self.conf.store._load_from_string('bar=baz')
3427
self.registry.register(config.Option('foo', default=u'{bar}'))
3428
self.assertEquals('baz', self.conf.get('foo', expand=True))
3430
def test_expand_default_from_env(self):
3431
self.conf.store._load_from_string('bar=baz')
3432
self.registry.register(config.Option('foo', default_from_env=['FOO']))
3433
self.overrideEnv('FOO', '{bar}')
3434
self.assertEquals('baz', self.conf.get('foo', expand=True))
3436
def test_expand_default_on_failed_conversion(self):
3437
self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
3438
self.registry.register(
3439
config.Option('foo', default=u'{bar}',
3440
from_unicode=config.int_from_store))
3441
self.assertEquals(42, self.conf.get('foo', expand=True))
3443
def test_env_adding_options(self):
3444
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3446
def test_env_overriding_options(self):
3447
self.conf.store._load_from_string('foo=baz')
3448
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3450
def test_simple_ref(self):
3451
self.conf.store._load_from_string('foo=xxx')
3452
self.assertExpansion('xxx', '{foo}')
3454
def test_unknown_ref(self):
3455
self.assertRaises(errors.ExpandingUnknownOption,
3456
self.conf.expand_options, '{foo}')
3458
def test_indirect_ref(self):
3459
self.conf.store._load_from_string('''
3463
self.assertExpansion('xxx', '{bar}')
3465
def test_embedded_ref(self):
3466
self.conf.store._load_from_string('''
3470
self.assertExpansion('xxx', '{{bar}}')
3472
def test_simple_loop(self):
3473
self.conf.store._load_from_string('foo={foo}')
3474
self.assertRaises(errors.OptionExpansionLoop,
3475
self.conf.expand_options, '{foo}')
3477
def test_indirect_loop(self):
3478
self.conf.store._load_from_string('''
3482
e = self.assertRaises(errors.OptionExpansionLoop,
3483
self.conf.expand_options, '{foo}')
3484
self.assertEquals('foo->bar->baz', e.refs)
3485
self.assertEquals('{foo}', e.string)
3487
def test_list(self):
3488
self.conf.store._load_from_string('''
3492
list={foo},{bar},{baz}
3494
self.registry.register(
3495
config.Option('list', from_unicode=config.list_from_store))
3496
self.assertEquals(['start', 'middle', 'end'],
3497
self.conf.get('list', expand=True))
3499
def test_cascading_list(self):
3500
self.conf.store._load_from_string('''
3506
self.registry.register(
3507
config.Option('list', from_unicode=config.list_from_store))
3508
self.assertEquals(['start', 'middle', 'end'],
3509
self.conf.get('list', expand=True))
3511
def test_pathologically_hidden_list(self):
3512
self.conf.store._load_from_string('''
3518
hidden={start}{middle}{end}
3520
# What matters is what the registration says, the conversion happens
3521
# only after all expansions have been performed
3522
self.registry.register(
3523
config.Option('hidden', from_unicode=config.list_from_store))
3524
self.assertEquals(['bin', 'go'],
3525
self.conf.get('hidden', expand=True))
3528
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3531
super(TestStackCrossSectionsExpand, self).setUp()
3533
def get_config(self, location, string):
3536
# Since we don't save the config we won't strictly require to inherit
3537
# from TestCaseInTempDir, but an error occurs so quickly...
3538
c = config.LocationStack(location)
3539
c.store._load_from_string(string)
3542
def test_dont_cross_unrelated_section(self):
3543
c = self.get_config('/another/branch/path','''
3548
[/another/branch/path]
3551
self.assertRaises(errors.ExpandingUnknownOption,
3552
c.get, 'bar', expand=True)
3554
def test_cross_related_sections(self):
3555
c = self.get_config('/project/branch/path','''
3559
[/project/branch/path]
3562
self.assertEquals('quux', c.get('bar', expand=True))
3565
class TestStackSet(TestStackWithTransport):
3567
def test_simple_set(self):
3568
conf = self.get_stack(self)
3569
conf.store._load_from_string('foo=bar')
3570
self.assertEquals('bar', conf.get('foo'))
3571
conf.set('foo', 'baz')
3572
# Did we get it back ?
3573
self.assertEquals('baz', conf.get('foo'))
3575
def test_set_creates_a_new_section(self):
3576
conf = self.get_stack(self)
3577
conf.set('foo', 'baz')
3578
self.assertEquals, 'baz', conf.get('foo')
3580
def test_set_hook(self):
3584
config.ConfigHooks.install_named_hook('set', hook, None)
3585
self.assertLength(0, calls)
3586
conf = self.get_stack(self)
3587
conf.set('foo', 'bar')
3588
self.assertLength(1, calls)
3589
self.assertEquals((conf, 'foo', 'bar'), calls[0])
3592
class TestStackRemove(TestStackWithTransport):
3594
def test_remove_existing(self):
3595
conf = self.get_stack(self)
3596
conf.store._load_from_string('foo=bar')
3597
self.assertEquals('bar', conf.get('foo'))
3599
# Did we get it back ?
3600
self.assertEquals(None, conf.get('foo'))
3602
def test_remove_unknown(self):
3603
conf = self.get_stack(self)
3604
self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3606
def test_remove_hook(self):
3610
config.ConfigHooks.install_named_hook('remove', hook, None)
3611
self.assertLength(0, calls)
3612
conf = self.get_stack(self)
3613
conf.store._load_from_string('foo=bar')
3615
self.assertLength(1, calls)
3616
self.assertEquals((conf, 'foo'), calls[0])
3619
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3622
super(TestConfigGetOptions, self).setUp()
3623
create_configs(self)
3625
def test_no_variable(self):
3626
# Using branch should query branch, locations and bazaar
3627
self.assertOptions([], self.branch_config)
3629
def test_option_in_bazaar(self):
3630
self.bazaar_config.set_user_option('file', 'bazaar')
3631
self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
3634
def test_option_in_locations(self):
3635
self.locations_config.set_user_option('file', 'locations')
3637
[('file', 'locations', self.tree.basedir, 'locations')],
3638
self.locations_config)
3640
def test_option_in_branch(self):
3641
self.branch_config.set_user_option('file', 'branch')
3642
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
3645
def test_option_in_bazaar_and_branch(self):
3646
self.bazaar_config.set_user_option('file', 'bazaar')
3647
self.branch_config.set_user_option('file', 'branch')
3648
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
3649
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3652
def test_option_in_branch_and_locations(self):
3653
# Hmm, locations override branch :-/
3654
self.locations_config.set_user_option('file', 'locations')
3655
self.branch_config.set_user_option('file', 'branch')
3657
[('file', 'locations', self.tree.basedir, 'locations'),
3658
('file', 'branch', 'DEFAULT', 'branch'),],
3661
def test_option_in_bazaar_locations_and_branch(self):
3662
self.bazaar_config.set_user_option('file', 'bazaar')
3663
self.locations_config.set_user_option('file', 'locations')
3664
self.branch_config.set_user_option('file', 'branch')
3666
[('file', 'locations', self.tree.basedir, 'locations'),
3667
('file', 'branch', 'DEFAULT', 'branch'),
3668
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3672
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
3675
super(TestConfigRemoveOption, self).setUp()
3676
create_configs_with_file_option(self)
3678
def test_remove_in_locations(self):
3679
self.locations_config.remove_user_option('file', self.tree.basedir)
3681
[('file', 'branch', 'DEFAULT', 'branch'),
3682
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3685
def test_remove_in_branch(self):
3686
self.branch_config.remove_user_option('file')
3688
[('file', 'locations', self.tree.basedir, 'locations'),
3689
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3692
def test_remove_in_bazaar(self):
3693
self.bazaar_config.remove_user_option('file')
3695
[('file', 'locations', self.tree.basedir, 'locations'),
3696
('file', 'branch', 'DEFAULT', 'branch'),],
3700
class TestConfigGetSections(tests.TestCaseWithTransport):
3703
super(TestConfigGetSections, self).setUp()
3704
create_configs(self)
3706
def assertSectionNames(self, expected, conf, name=None):
3707
"""Check which sections are returned for a given config.
3709
If fallback configurations exist their sections can be included.
3711
:param expected: A list of section names.
3713
:param conf: The configuration that will be queried.
3715
:param name: An optional section name that will be passed to
3718
sections = list(conf._get_sections(name))
3719
self.assertLength(len(expected), sections)
3720
self.assertEqual(expected, [name for name, _, _ in sections])
3722
def test_bazaar_default_section(self):
3723
self.assertSectionNames(['DEFAULT'], self.bazaar_config)
3725
def test_locations_default_section(self):
3726
# No sections are defined in an empty file
3727
self.assertSectionNames([], self.locations_config)
3729
def test_locations_named_section(self):
3730
self.locations_config.set_user_option('file', 'locations')
3731
self.assertSectionNames([self.tree.basedir], self.locations_config)
3733
def test_locations_matching_sections(self):
3734
loc_config = self.locations_config
3735
loc_config.set_user_option('file', 'locations')
3736
# We need to cheat a bit here to create an option in sections above and
3737
# below the 'location' one.
3738
parser = loc_config._get_parser()
3739
# locations.cong deals with '/' ignoring native os.sep
3740
location_names = self.tree.basedir.split('/')
3741
parent = '/'.join(location_names[:-1])
3742
child = '/'.join(location_names + ['child'])
3744
parser[parent]['file'] = 'parent'
3746
parser[child]['file'] = 'child'
3747
self.assertSectionNames([self.tree.basedir, parent], loc_config)
3749
def test_branch_data_default_section(self):
3750
self.assertSectionNames([None],
3751
self.branch_config._get_branch_data_config())
3753
def test_branch_default_sections(self):
3754
# No sections are defined in an empty locations file
3755
self.assertSectionNames([None, 'DEFAULT'],
3757
# Unless we define an option
3758
self.branch_config._get_location_config().set_user_option(
3759
'file', 'locations')
3760
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
3763
def test_bazaar_named_section(self):
3764
# We need to cheat as the API doesn't give direct access to sections
3765
# other than DEFAULT.
3766
self.bazaar_config.set_alias('bazaar', 'bzr')
3767
self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
1474
3770
class TestAuthenticationConfigFile(tests.TestCase):
1475
3771
"""Test the authentication.conf file matching"""