1493
1512
self.get_branch_config('http://www.example.com',
1494
1513
global_config=sample_ignore_signatures)
1495
1514
self.assertEqual(config.CHECK_ALWAYS,
1496
self.my_config.signature_checking())
1515
self.applyDeprecated(deprecated_in((2, 5, 0)),
1516
self.my_config.signature_checking))
1497
1517
self.assertEqual(config.SIGN_NEVER,
1498
self.my_config.signing_policy())
1518
self.applyDeprecated(deprecated_in((2, 5, 0)),
1519
self.my_config.signing_policy))
1500
1521
def test_signatures_never(self):
1501
1522
self.get_branch_config('/a/c')
1502
1523
self.assertEqual(config.CHECK_NEVER,
1503
self.my_config.signature_checking())
1524
self.applyDeprecated(deprecated_in((2, 5, 0)),
1525
self.my_config.signature_checking))
1505
1527
def test_signatures_when_available(self):
1506
1528
self.get_branch_config('/a/', global_config=sample_ignore_signatures)
1507
1529
self.assertEqual(config.CHECK_IF_POSSIBLE,
1508
self.my_config.signature_checking())
1530
self.applyDeprecated(deprecated_in((2, 5, 0)),
1531
self.my_config.signature_checking))
1510
1533
def test_signatures_always(self):
1511
1534
self.get_branch_config('/b')
1512
1535
self.assertEqual(config.CHECK_ALWAYS,
1513
self.my_config.signature_checking())
1536
self.applyDeprecated(deprecated_in((2, 5, 0)),
1537
self.my_config.signature_checking))
1515
1539
def test_gpg_signing_command(self):
1516
1540
self.get_branch_config('/b')
1517
self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
1541
self.assertEqual("gnome-gpg",
1542
self.applyDeprecated(deprecated_in((2, 5, 0)),
1543
self.my_config.gpg_signing_command))
1519
1545
def test_gpg_signing_command_missing(self):
1520
1546
self.get_branch_config('/a')
1521
self.assertEqual("false", self.my_config.gpg_signing_command())
1547
self.assertEqual("false",
1548
self.applyDeprecated(deprecated_in((2, 5, 0)),
1549
self.my_config.gpg_signing_command))
1551
def test_gpg_signing_key(self):
1552
self.get_branch_config('/b')
1553
self.assertEqual("DD4D5088", self.applyDeprecated(deprecated_in((2, 5, 0)),
1554
self.my_config.gpg_signing_key))
1556
def test_gpg_signing_key_default(self):
1557
self.get_branch_config('/a')
1558
self.assertEqual("erik@bagfors.nu",
1559
self.applyDeprecated(deprecated_in((2, 5, 0)),
1560
self.my_config.gpg_signing_key))
1523
1562
def test_get_user_option_global(self):
1524
1563
self.get_branch_config('/a')
2199
2226
opt = config.Option('foo', default='bar')
2200
2227
self.assertEquals('bar', opt.get_default())
2229
def test_callable_default_value(self):
2230
def bar_as_unicode():
2232
opt = config.Option('foo', default=bar_as_unicode)
2233
self.assertEquals('bar', opt.get_default())
2235
def test_default_value_from_env(self):
2236
opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2237
self.overrideEnv('FOO', 'quux')
2238
# Env variable provides a default taking over the option one
2239
self.assertEquals('quux', opt.get_default())
2241
def test_first_default_value_from_env_wins(self):
2242
opt = config.Option('foo', default='bar',
2243
default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2244
self.overrideEnv('FOO', 'foo')
2245
self.overrideEnv('BAZ', 'baz')
2246
# The first env var set wins
2247
self.assertEquals('foo', opt.get_default())
2249
def test_not_supported_list_default_value(self):
2250
self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2252
def test_not_supported_object_default_value(self):
2253
self.assertRaises(AssertionError, config.Option, 'foo',
2256
def test_not_supported_callable_default_value_not_unicode(self):
2257
def bar_not_unicode():
2259
opt = config.Option('foo', default=bar_not_unicode)
2260
self.assertRaises(AssertionError, opt.get_default)
2262
def test_get_help_topic(self):
2263
opt = config.Option('foo')
2264
self.assertEquals('foo', opt.get_help_topic())
2267
class TestOptionConverterMixin(object):
2269
def assertConverted(self, expected, opt, value):
2270
self.assertEquals(expected, opt.convert_from_unicode(None, value))
2272
def assertWarns(self, opt, value):
2275
warnings.append(args[0] % args[1:])
2276
self.overrideAttr(trace, 'warning', warning)
2277
self.assertEquals(None, opt.convert_from_unicode(None, value))
2278
self.assertLength(1, warnings)
2280
'Value "%s" is not valid for "%s"' % (value, opt.name),
2283
def assertErrors(self, opt, value):
2284
self.assertRaises(errors.ConfigOptionValueError,
2285
opt.convert_from_unicode, None, value)
2287
def assertConvertInvalid(self, opt, invalid_value):
2289
self.assertEquals(None, opt.convert_from_unicode(None, invalid_value))
2290
opt.invalid = 'warning'
2291
self.assertWarns(opt, invalid_value)
2292
opt.invalid = 'error'
2293
self.assertErrors(opt, invalid_value)
2296
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2298
def get_option(self):
2299
return config.Option('foo', help='A boolean.',
2300
from_unicode=config.bool_from_store)
2302
def test_convert_invalid(self):
2303
opt = self.get_option()
2304
# A string that is not recognized as a boolean
2305
self.assertConvertInvalid(opt, u'invalid-boolean')
2306
# A list of strings is never recognized as a boolean
2307
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2309
def test_convert_valid(self):
2310
opt = self.get_option()
2311
self.assertConverted(True, opt, u'True')
2312
self.assertConverted(True, opt, u'1')
2313
self.assertConverted(False, opt, u'False')
2316
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2318
def get_option(self):
2319
return config.Option('foo', help='An integer.',
2320
from_unicode=config.int_from_store)
2322
def test_convert_invalid(self):
2323
opt = self.get_option()
2324
# A string that is not recognized as an integer
2325
self.assertConvertInvalid(opt, u'forty-two')
2326
# A list of strings is never recognized as an integer
2327
self.assertConvertInvalid(opt, [u'a', u'list'])
2329
def test_convert_valid(self):
2330
opt = self.get_option()
2331
self.assertConverted(16, opt, u'16')
2334
class TestOptionWithSIUnitConverter(tests.TestCase, TestOptionConverterMixin):
2336
def get_option(self):
2337
return config.Option('foo', help='An integer in SI units.',
2338
from_unicode=config.int_SI_from_store)
2340
def test_convert_invalid(self):
2341
opt = self.get_option()
2342
self.assertConvertInvalid(opt, u'not-a-unit')
2343
self.assertConvertInvalid(opt, u'Gb') # Forgot the int
2344
self.assertConvertInvalid(opt, u'1b') # Forgot the unit
2345
self.assertConvertInvalid(opt, u'1GG')
2346
self.assertConvertInvalid(opt, u'1Mbb')
2347
self.assertConvertInvalid(opt, u'1MM')
2349
def test_convert_valid(self):
2350
opt = self.get_option()
2351
self.assertConverted(int(5e3), opt, u'5kb')
2352
self.assertConverted(int(5e6), opt, u'5M')
2353
self.assertConverted(int(5e6), opt, u'5MB')
2354
self.assertConverted(int(5e9), opt, u'5g')
2355
self.assertConverted(int(5e9), opt, u'5gB')
2356
self.assertConverted(100, opt, u'100')
2359
class TestListOption(tests.TestCase, TestOptionConverterMixin):
2361
def get_option(self):
2362
return config.ListOption('foo', help='A list.')
2364
def test_convert_invalid(self):
2365
opt = self.get_option()
2366
# We don't even try to convert a list into a list, we only expect
2368
self.assertConvertInvalid(opt, [1])
2369
# No string is invalid as all forms can be converted to a list
2371
def test_convert_valid(self):
2372
opt = self.get_option()
2373
# An empty string is an empty list
2374
self.assertConverted([], opt, '') # Using a bare str() just in case
2375
self.assertConverted([], opt, u'')
2377
self.assertConverted([u'True'], opt, u'True')
2379
self.assertConverted([u'42'], opt, u'42')
2381
self.assertConverted([u'bar'], opt, u'bar')
2384
class TestRegistryOption(tests.TestCase, TestOptionConverterMixin):
2386
def get_option(self, registry):
2387
return config.RegistryOption('foo', registry,
2388
help='A registry option.')
2390
def test_convert_invalid(self):
2391
registry = _mod_registry.Registry()
2392
opt = self.get_option(registry)
2393
self.assertConvertInvalid(opt, [1])
2394
self.assertConvertInvalid(opt, u"notregistered")
2396
def test_convert_valid(self):
2397
registry = _mod_registry.Registry()
2398
registry.register("someval", 1234)
2399
opt = self.get_option(registry)
2400
# Using a bare str() just in case
2401
self.assertConverted(1234, opt, "someval")
2402
self.assertConverted(1234, opt, u'someval')
2403
self.assertConverted(None, opt, None)
2405
def test_help(self):
2406
registry = _mod_registry.Registry()
2407
registry.register("someval", 1234, help="some option")
2408
registry.register("dunno", 1234, help="some other option")
2409
opt = self.get_option(registry)
2411
'A registry option.\n'
2413
'The following values are supported:\n'
2414
' dunno - some other option\n'
2415
' someval - some option\n',
2418
def test_get_help_text(self):
2419
registry = _mod_registry.Registry()
2420
registry.register("someval", 1234, help="some option")
2421
registry.register("dunno", 1234, help="some other option")
2422
opt = self.get_option(registry)
2424
'A registry option.\n'
2426
'The following values are supported:\n'
2427
' dunno - some other option\n'
2428
' someval - some option\n',
2429
opt.get_help_text())
2203
2432
class TestOptionRegistry(tests.TestCase):
2205
2434
def setUp(self):
2206
2435
super(TestOptionRegistry, self).setUp()
2207
2436
# Always start with an empty registry
2208
self.overrideAttr(config, 'option_registry', registry.Registry())
2437
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2209
2438
self.registry = config.option_registry
2211
2440
def test_register(self):
2212
2441
opt = config.Option('foo')
2213
self.registry.register('foo', opt)
2442
self.registry.register(opt)
2214
2443
self.assertIs(opt, self.registry.get('foo'))
2216
lazy_option = config.Option('lazy_foo')
2218
def test_register_lazy(self):
2219
self.registry.register_lazy('foo', self.__module__,
2220
'TestOptionRegistry.lazy_option')
2221
self.assertIs(self.lazy_option, self.registry.get('foo'))
2223
2445
def test_registered_help(self):
2224
opt = config.Option('foo')
2225
self.registry.register('foo', opt, help='A simple option')
2446
opt = config.Option('foo', help='A simple option')
2447
self.registry.register(opt)
2226
2448
self.assertEquals('A simple option', self.registry.get_help('foo'))
2450
lazy_option = config.Option('lazy_foo', help='Lazy help')
2452
def test_register_lazy(self):
2453
self.registry.register_lazy('lazy_foo', self.__module__,
2454
'TestOptionRegistry.lazy_option')
2455
self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2457
def test_registered_lazy_help(self):
2458
self.registry.register_lazy('lazy_foo', self.__module__,
2459
'TestOptionRegistry.lazy_option')
2460
self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2229
2463
class TestRegisteredOptions(tests.TestCase):
2230
2464
"""All registered options should verify some constraints."""
2321
2558
self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2561
class TestCommandLineStore(tests.TestCase):
2564
super(TestCommandLineStore, self).setUp()
2565
self.store = config.CommandLineStore()
2566
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2568
def get_section(self):
2569
"""Get the unique section for the command line overrides."""
2570
sections = list(self.store.get_sections())
2571
self.assertLength(1, sections)
2572
store, section = sections[0]
2573
self.assertEquals(self.store, store)
2576
def test_no_override(self):
2577
self.store._from_cmdline([])
2578
section = self.get_section()
2579
self.assertLength(0, list(section.iter_option_names()))
2581
def test_simple_override(self):
2582
self.store._from_cmdline(['a=b'])
2583
section = self.get_section()
2584
self.assertEqual('b', section.get('a'))
2586
def test_list_override(self):
2587
opt = config.ListOption('l')
2588
config.option_registry.register(opt)
2589
self.store._from_cmdline(['l=1,2,3'])
2590
val = self.get_section().get('l')
2591
self.assertEqual('1,2,3', val)
2592
# Reminder: lists should be registered as such explicitely, otherwise
2593
# the conversion needs to be done afterwards.
2594
self.assertEqual(['1', '2', '3'],
2595
opt.convert_from_unicode(self.store, val))
2597
def test_multiple_overrides(self):
2598
self.store._from_cmdline(['a=b', 'x=y'])
2599
section = self.get_section()
2600
self.assertEquals('b', section.get('a'))
2601
self.assertEquals('y', section.get('x'))
2603
def test_wrong_syntax(self):
2604
self.assertRaises(errors.BzrCommandError,
2605
self.store._from_cmdline, ['a=b', 'c'])
2607
class TestStoreMinimalAPI(tests.TestCaseWithTransport):
2609
scenarios = [(key, {'get_store': builder}) for key, builder
2610
in config.test_store_builder_registry.iteritems()] + [
2611
('cmdline', {'get_store': lambda test: config.CommandLineStore()})]
2614
store = self.get_store(self)
2615
if type(store) == config.TransportIniFileStore:
2616
raise tests.TestNotApplicable(
2617
"%s is not a concrete Store implementation"
2618
" so it doesn't need an id" % (store.__class__.__name__,))
2619
self.assertIsNot(None, store.id)
2324
2622
class TestStore(tests.TestCaseWithTransport):
2326
def assertSectionContent(self, expected, section):
2624
def assertSectionContent(self, expected, (store, section)):
2327
2625
"""Assert that some options have the proper values in a section."""
2328
2626
expected_name, expected_options = expected
2329
2627
self.assertEquals(expected_name, section.id)
2371
2666
self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2669
class TestStoreQuoting(TestStore):
2671
scenarios = [(key, {'get_store': builder}) for key, builder
2672
in config.test_store_builder_registry.iteritems()]
2675
super(TestStoreQuoting, self).setUp()
2676
self.store = self.get_store(self)
2677
# We need a loaded store but any content will do
2678
self.store._load_from_string('')
2680
def assertIdempotent(self, s):
2681
"""Assert that quoting an unquoted string is a no-op and vice-versa.
2683
What matters here is that option values, as they appear in a store, can
2684
be safely round-tripped out of the store and back.
2686
:param s: A string, quoted if required.
2688
self.assertEquals(s, self.store.quote(self.store.unquote(s)))
2689
self.assertEquals(s, self.store.unquote(self.store.quote(s)))
2691
def test_empty_string(self):
2692
if isinstance(self.store, config.IniFileStore):
2693
# configobj._quote doesn't handle empty values
2694
self.assertRaises(AssertionError,
2695
self.assertIdempotent, '')
2697
self.assertIdempotent('')
2698
# But quoted empty strings are ok
2699
self.assertIdempotent('""')
2701
def test_embedded_spaces(self):
2702
self.assertIdempotent('" a b c "')
2704
def test_embedded_commas(self):
2705
self.assertIdempotent('" a , b c "')
2707
def test_simple_comma(self):
2708
if isinstance(self.store, config.IniFileStore):
2709
# configobj requires that lists are special-cased
2710
self.assertRaises(AssertionError,
2711
self.assertIdempotent, ',')
2713
self.assertIdempotent(',')
2714
# When a single comma is required, quoting is also required
2715
self.assertIdempotent('","')
2717
def test_list(self):
2718
if isinstance(self.store, config.IniFileStore):
2719
# configobj requires that lists are special-cased
2720
self.assertRaises(AssertionError,
2721
self.assertIdempotent, 'a,b')
2723
self.assertIdempotent('a,b')
2726
class TestDictFromStore(tests.TestCase):
2728
def test_unquote_not_string(self):
2729
conf = config.MemoryStack('x=2\n[a_section]\na=1\n')
2730
value = conf.get('a_section')
2731
# Urgh, despite 'conf' asking for the no-name section, we get the
2732
# content of another section as a dict o_O
2733
self.assertEquals({'a': '1'}, value)
2734
unquoted = conf.store.unquote(value)
2735
# Which cannot be unquoted but shouldn't crash either (the use cases
2736
# are getting the value or displaying it. In the later case, '%s' will
2738
self.assertEquals({'a': '1'}, unquoted)
2739
self.assertEquals("{u'a': u'1'}", '%s' % (unquoted,))
2374
2742
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2375
"""Simulate loading a config store without content of various encodings.
2743
"""Simulate loading a config store with content of various encodings.
2377
2745
All files produced by bzr are in utf8 content.
2556
2968
config.ConfigHooks.install_named_hook('save', hook, None)
2557
2969
self.assertLength(0, calls)
2558
2970
store = self.get_store(self)
2971
# FIXME: There should be a better way than relying on the test
2972
# parametrization to identify branch.conf -- vila 2011-0526
2973
if self.store_id in ('branch', 'remote_branch'):
2974
# branch stores requires write locked branches
2975
self.addCleanup(store.branch.lock_write().unlock)
2559
2976
section = store.get_mutable_section('baz')
2560
2977
section.set('foo', 'bar')
2562
2979
self.assertLength(1, calls)
2563
2980
self.assertEquals((store,), calls[0])
2566
class TestIniFileStore(TestStore):
2982
def test_set_mark_dirty(self):
2983
stack = config.MemoryStack('')
2984
self.assertLength(0, stack.store.dirty_sections)
2985
stack.set('foo', 'baz')
2986
self.assertLength(1, stack.store.dirty_sections)
2987
self.assertTrue(stack.store._need_saving())
2989
def test_remove_mark_dirty(self):
2990
stack = config.MemoryStack('foo=bar')
2991
self.assertLength(0, stack.store.dirty_sections)
2993
self.assertLength(1, stack.store.dirty_sections)
2994
self.assertTrue(stack.store._need_saving())
2997
class TestStoreSaveChanges(tests.TestCaseWithTransport):
2998
"""Tests that config changes are kept in memory and saved on-demand."""
3001
super(TestStoreSaveChanges, self).setUp()
3002
self.transport = self.get_transport()
3003
# Most of the tests involve two stores pointing to the same persistent
3004
# storage to observe the effects of concurrent changes
3005
self.st1 = config.TransportIniFileStore(self.transport, 'foo.conf')
3006
self.st2 = config.TransportIniFileStore(self.transport, 'foo.conf')
3009
self.warnings.append(args[0] % args[1:])
3010
self.overrideAttr(trace, 'warning', warning)
3012
def has_store(self, store):
3013
store_basename = urlutils.relative_url(self.transport.external_url(),
3014
store.external_url())
3015
return self.transport.has(store_basename)
3017
def get_stack(self, store):
3018
# Any stack will do as long as it uses the right store, just a single
3019
# no-name section is enough
3020
return config.Stack([store.get_sections], store)
3022
def test_no_changes_no_save(self):
3023
s = self.get_stack(self.st1)
3024
s.store.save_changes()
3025
self.assertEquals(False, self.has_store(self.st1))
3027
def test_unrelated_concurrent_update(self):
3028
s1 = self.get_stack(self.st1)
3029
s2 = self.get_stack(self.st2)
3030
s1.set('foo', 'bar')
3031
s2.set('baz', 'quux')
3033
# Changes don't propagate magically
3034
self.assertEquals(None, s1.get('baz'))
3035
s2.store.save_changes()
3036
self.assertEquals('quux', s2.get('baz'))
3037
# Changes are acquired when saving
3038
self.assertEquals('bar', s2.get('foo'))
3039
# Since there is no overlap, no warnings are emitted
3040
self.assertLength(0, self.warnings)
3042
def test_concurrent_update_modified(self):
3043
s1 = self.get_stack(self.st1)
3044
s2 = self.get_stack(self.st2)
3045
s1.set('foo', 'bar')
3046
s2.set('foo', 'baz')
3049
s2.store.save_changes()
3050
self.assertEquals('baz', s2.get('foo'))
3051
# But the user get a warning
3052
self.assertLength(1, self.warnings)
3053
warning = self.warnings[0]
3054
self.assertStartsWith(warning, 'Option foo in section None')
3055
self.assertEndsWith(warning, 'was changed from <CREATED> to bar.'
3056
' The baz value will be saved.')
3058
def test_concurrent_deletion(self):
3059
self.st1._load_from_string('foo=bar')
3061
s1 = self.get_stack(self.st1)
3062
s2 = self.get_stack(self.st2)
3065
s1.store.save_changes()
3067
self.assertLength(0, self.warnings)
3068
s2.store.save_changes()
3070
self.assertLength(1, self.warnings)
3071
warning = self.warnings[0]
3072
self.assertStartsWith(warning, 'Option foo in section None')
3073
self.assertEndsWith(warning, 'was changed from bar to <CREATED>.'
3074
' The <DELETED> value will be saved.')
3077
class TestQuotingIniFileStore(tests.TestCaseWithTransport):
3079
def get_store(self):
3080
return config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3082
def test_get_quoted_string(self):
3083
store = self.get_store()
3084
store._load_from_string('foo= " abc "')
3085
stack = config.Stack([store.get_sections])
3086
self.assertEquals(' abc ', stack.get('foo'))
3088
def test_set_quoted_string(self):
3089
store = self.get_store()
3090
stack = config.Stack([store.get_sections], store)
3091
stack.set('foo', ' a b c ')
3093
self.assertFileEqual('foo = " a b c "' + os.linesep, 'foo.conf')
3096
class TestTransportIniFileStore(TestStore):
2568
3098
def test_loading_unknown_file_fails(self):
2569
store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
3099
store = config.TransportIniFileStore(self.get_transport(),
2570
3101
self.assertRaises(errors.NoSuchFile, store.load)
2572
3103
def test_invalid_content(self):
2573
store = config.IniFileStore(self.get_transport(), 'foo.conf', )
3104
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2574
3105
self.assertEquals(False, store.is_loaded())
2575
3106
exc = self.assertRaises(
2576
3107
errors.ParseConfigError, store._load_from_string,
2847
3406
self.assertEquals(expected_location, matcher.location)
2850
class TestStackGet(tests.TestCase):
2852
# FIXME: This should be parametrized for all known Stack or dedicated
2853
# paramerized tests created to avoid bloating -- vila 2011-03-31
2855
def test_single_config_get(self):
2856
conf = dict(foo='bar')
2857
conf_stack = config.Stack([conf])
2858
self.assertEquals('bar', conf_stack.get('foo'))
3409
class TestStartingPathMatcher(TestStore):
3412
super(TestStartingPathMatcher, self).setUp()
3413
# Any simple store is good enough
3414
self.store = config.IniFileStore()
3416
def assertSectionIDs(self, expected, location, content):
3417
self.store._load_from_string(content)
3418
matcher = config.StartingPathMatcher(self.store, location)
3419
sections = list(matcher.get_sections())
3420
self.assertLength(len(expected), sections)
3421
self.assertEqual(expected, [section.id for _, section in sections])
3424
def test_empty(self):
3425
self.assertSectionIDs([], self.get_url(), '')
3427
def test_url_vs_local_paths(self):
3428
# The matcher location is an url and the section names are local paths
3429
sections = self.assertSectionIDs(['/foo/bar', '/foo'],
3430
'file:///foo/bar/baz', '''\
3435
def test_local_path_vs_url(self):
3436
# The matcher location is a local path and the section names are urls
3437
sections = self.assertSectionIDs(['file:///foo/bar', 'file:///foo'],
3438
'/foo/bar/baz', '''\
3444
def test_no_name_section_included_when_present(self):
3445
# Note that other tests will cover the case where the no-name section
3446
# is empty and as such, not included.
3447
sections = self.assertSectionIDs(['/foo/bar', '/foo', None],
3448
'/foo/bar/baz', '''\
3449
option = defined so the no-name section exists
3453
self.assertEquals(['baz', 'bar/baz', '/foo/bar/baz'],
3454
[s.locals['relpath'] for _, s in sections])
3456
def test_order_reversed(self):
3457
self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
3462
def test_unrelated_section_excluded(self):
3463
self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
3469
def test_glob_included(self):
3470
sections = self.assertSectionIDs(['/foo/*/baz', '/foo/b*', '/foo'],
3471
'/foo/bar/baz', '''\
3477
# Note that 'baz' as a relpath for /foo/b* is not fully correct, but
3478
# nothing really is... as far using {relpath} to append it to something
3479
# else, this seems good enough though.
3480
self.assertEquals(['', 'baz', 'bar/baz'],
3481
[s.locals['relpath'] for _, s in sections])
3483
def test_respect_order(self):
3484
self.assertSectionIDs(['/foo', '/foo/b*', '/foo/*/baz'],
3485
'/foo/bar/baz', '''\
3493
class TestNameMatcher(TestStore):
3496
super(TestNameMatcher, self).setUp()
3497
self.matcher = config.NameMatcher
3498
# Any simple store is good enough
3499
self.get_store = config.test_store_builder_registry.get('configobj')
3501
def get_matching_sections(self, name):
3502
store = self.get_store(self)
3503
store._load_from_string('''
3511
matcher = self.matcher(store, name)
3512
return list(matcher.get_sections())
3514
def test_matching(self):
3515
sections = self.get_matching_sections('foo')
3516
self.assertLength(1, sections)
3517
self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3519
def test_not_matching(self):
3520
sections = self.get_matching_sections('baz')
3521
self.assertLength(0, sections)
3524
class TestBaseStackGet(tests.TestCase):
3527
super(TestBaseStackGet, self).setUp()
3528
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3530
def test_get_first_definition(self):
3531
store1 = config.IniFileStore()
3532
store1._load_from_string('foo=bar')
3533
store2 = config.IniFileStore()
3534
store2._load_from_string('foo=baz')
3535
conf = config.Stack([store1.get_sections, store2.get_sections])
3536
self.assertEquals('bar', conf.get('foo'))
2860
3538
def test_get_with_registered_default_value(self):
2861
conf_stack = config.Stack([dict()])
2862
opt = config.Option('foo', default='bar')
2863
self.overrideAttr(config, 'option_registry', registry.Registry())
2864
config.option_registry.register('foo', opt)
3539
config.option_registry.register(config.Option('foo', default='bar'))
3540
conf_stack = config.Stack([])
2865
3541
self.assertEquals('bar', conf_stack.get('foo'))
2867
3543
def test_get_without_registered_default_value(self):
2868
conf_stack = config.Stack([dict()])
2869
opt = config.Option('foo')
2870
self.overrideAttr(config, 'option_registry', registry.Registry())
2871
config.option_registry.register('foo', opt)
3544
config.option_registry.register(config.Option('foo'))
3545
conf_stack = config.Stack([])
2872
3546
self.assertEquals(None, conf_stack.get('foo'))
2874
3548
def test_get_without_default_value_for_not_registered(self):
2875
conf_stack = config.Stack([dict()])
2876
opt = config.Option('foo')
2877
self.overrideAttr(config, 'option_registry', registry.Registry())
3549
conf_stack = config.Stack([])
2878
3550
self.assertEquals(None, conf_stack.get('foo'))
2880
def test_get_first_definition(self):
2881
conf1 = dict(foo='bar')
2882
conf2 = dict(foo='baz')
2883
conf_stack = config.Stack([conf1, conf2])
2884
self.assertEquals('bar', conf_stack.get('foo'))
2886
def test_get_embedded_definition(self):
2887
conf1 = dict(yy='12')
2888
conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
2889
conf_stack = config.Stack([conf1, conf2])
2890
self.assertEquals('baz', conf_stack.get('foo'))
2892
3552
def test_get_for_empty_section_callable(self):
2893
3553
conf_stack = config.Stack([lambda : []])
2894
3554
self.assertEquals(None, conf_stack.get('foo'))
2896
3556
def test_get_for_broken_callable(self):
2897
3557
# Trying to use and invalid callable raises an exception on first use
2898
conf_stack = config.Stack([lambda : object()])
3558
conf_stack = config.Stack([object])
2899
3559
self.assertRaises(TypeError, conf_stack.get, 'foo')
3562
class TestStackWithSimpleStore(tests.TestCase):
3565
super(TestStackWithSimpleStore, self).setUp()
3566
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3567
self.registry = config.option_registry
3569
def get_conf(self, content=None):
3570
return config.MemoryStack(content)
3572
def test_override_value_from_env(self):
3573
self.registry.register(
3574
config.Option('foo', default='bar', override_from_env=['FOO']))
3575
self.overrideEnv('FOO', 'quux')
3576
# Env variable provides a default taking over the option one
3577
conf = self.get_conf('foo=store')
3578
self.assertEquals('quux', conf.get('foo'))
3580
def test_first_override_value_from_env_wins(self):
3581
self.registry.register(
3582
config.Option('foo', default='bar',
3583
override_from_env=['NO_VALUE', 'FOO', 'BAZ']))
3584
self.overrideEnv('FOO', 'foo')
3585
self.overrideEnv('BAZ', 'baz')
3586
# The first env var set wins
3587
conf = self.get_conf('foo=store')
3588
self.assertEquals('foo', conf.get('foo'))
3591
class TestMemoryStack(tests.TestCase):
3594
conf = config.MemoryStack('foo=bar')
3595
self.assertEquals('bar', conf.get('foo'))
3598
conf = config.MemoryStack('foo=bar')
3599
conf.set('foo', 'baz')
3600
self.assertEquals('baz', conf.get('foo'))
3602
def test_no_content(self):
3603
conf = config.MemoryStack()
3604
# No content means no loading
3605
self.assertFalse(conf.store.is_loaded())
3606
self.assertRaises(NotImplementedError, conf.get, 'foo')
3607
# But a content can still be provided
3608
conf.store._load_from_string('foo=bar')
3609
self.assertEquals('bar', conf.get('foo'))
3612
class TestStackIterSections(tests.TestCase):
3614
def test_empty_stack(self):
3615
conf = config.Stack([])
3616
sections = list(conf.iter_sections())
3617
self.assertLength(0, sections)
3619
def test_empty_store(self):
3620
store = config.IniFileStore()
3621
store._load_from_string('')
3622
conf = config.Stack([store.get_sections])
3623
sections = list(conf.iter_sections())
3624
self.assertLength(0, sections)
3626
def test_simple_store(self):
3627
store = config.IniFileStore()
3628
store._load_from_string('foo=bar')
3629
conf = config.Stack([store.get_sections])
3630
tuples = list(conf.iter_sections())
3631
self.assertLength(1, tuples)
3632
(found_store, found_section) = tuples[0]
3633
self.assertIs(store, found_store)
3635
def test_two_stores(self):
3636
store1 = config.IniFileStore()
3637
store1._load_from_string('foo=bar')
3638
store2 = config.IniFileStore()
3639
store2._load_from_string('bar=qux')
3640
conf = config.Stack([store1.get_sections, store2.get_sections])
3641
tuples = list(conf.iter_sections())
3642
self.assertLength(2, tuples)
3643
self.assertIs(store1, tuples[0][0])
3644
self.assertIs(store2, tuples[1][0])
2902
3647
class TestStackWithTransport(tests.TestCaseWithTransport):
2904
3649
scenarios = [(key, {'get_stack': builder}) for key, builder
2915
3660
class TestStackGet(TestStackWithTransport):
3663
super(TestStackGet, self).setUp()
3664
self.conf = self.get_stack(self)
2917
3666
def test_get_for_empty_stack(self):
2918
conf = self.get_stack(self)
2919
self.assertEquals(None, conf.get('foo'))
3667
self.assertEquals(None, self.conf.get('foo'))
2921
3669
def test_get_hook(self):
2922
conf = self.get_stack(self)
2923
conf.store._load_from_string('foo=bar')
3670
self.conf.set('foo', 'bar')
2925
3672
def hook(*args):
2926
3673
calls.append(args)
2927
3674
config.ConfigHooks.install_named_hook('get', hook, None)
2928
3675
self.assertLength(0, calls)
2929
value = conf.get('foo')
3676
value = self.conf.get('foo')
2930
3677
self.assertEquals('bar', value)
2931
3678
self.assertLength(1, calls)
2932
self.assertEquals((conf, 'foo', 'bar'), calls[0])
3679
self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3682
class TestStackGetWithConverter(tests.TestCase):
3685
super(TestStackGetWithConverter, self).setUp()
3686
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3687
self.registry = config.option_registry
3689
def get_conf(self, content=None):
3690
return config.MemoryStack(content)
3692
def register_bool_option(self, name, default=None, default_from_env=None):
3693
b = config.Option(name, help='A boolean.',
3694
default=default, default_from_env=default_from_env,
3695
from_unicode=config.bool_from_store)
3696
self.registry.register(b)
3698
def test_get_default_bool_None(self):
3699
self.register_bool_option('foo')
3700
conf = self.get_conf('')
3701
self.assertEquals(None, conf.get('foo'))
3703
def test_get_default_bool_True(self):
3704
self.register_bool_option('foo', u'True')
3705
conf = self.get_conf('')
3706
self.assertEquals(True, conf.get('foo'))
3708
def test_get_default_bool_False(self):
3709
self.register_bool_option('foo', False)
3710
conf = self.get_conf('')
3711
self.assertEquals(False, conf.get('foo'))
3713
def test_get_default_bool_False_as_string(self):
3714
self.register_bool_option('foo', u'False')
3715
conf = self.get_conf('')
3716
self.assertEquals(False, conf.get('foo'))
3718
def test_get_default_bool_from_env_converted(self):
3719
self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3720
self.overrideEnv('FOO', 'False')
3721
conf = self.get_conf('')
3722
self.assertEquals(False, conf.get('foo'))
3724
def test_get_default_bool_when_conversion_fails(self):
3725
self.register_bool_option('foo', default='True')
3726
conf = self.get_conf('foo=invalid boolean')
3727
self.assertEquals(True, conf.get('foo'))
3729
def register_integer_option(self, name,
3730
default=None, default_from_env=None):
3731
i = config.Option(name, help='An integer.',
3732
default=default, default_from_env=default_from_env,
3733
from_unicode=config.int_from_store)
3734
self.registry.register(i)
3736
def test_get_default_integer_None(self):
3737
self.register_integer_option('foo')
3738
conf = self.get_conf('')
3739
self.assertEquals(None, conf.get('foo'))
3741
def test_get_default_integer(self):
3742
self.register_integer_option('foo', 42)
3743
conf = self.get_conf('')
3744
self.assertEquals(42, conf.get('foo'))
3746
def test_get_default_integer_as_string(self):
3747
self.register_integer_option('foo', u'42')
3748
conf = self.get_conf('')
3749
self.assertEquals(42, conf.get('foo'))
3751
def test_get_default_integer_from_env(self):
3752
self.register_integer_option('foo', default_from_env=['FOO'])
3753
self.overrideEnv('FOO', '18')
3754
conf = self.get_conf('')
3755
self.assertEquals(18, conf.get('foo'))
3757
def test_get_default_integer_when_conversion_fails(self):
3758
self.register_integer_option('foo', default='12')
3759
conf = self.get_conf('foo=invalid integer')
3760
self.assertEquals(12, conf.get('foo'))
3762
def register_list_option(self, name, default=None, default_from_env=None):
3763
l = config.ListOption(name, help='A list.', default=default,
3764
default_from_env=default_from_env)
3765
self.registry.register(l)
3767
def test_get_default_list_None(self):
3768
self.register_list_option('foo')
3769
conf = self.get_conf('')
3770
self.assertEquals(None, conf.get('foo'))
3772
def test_get_default_list_empty(self):
3773
self.register_list_option('foo', '')
3774
conf = self.get_conf('')
3775
self.assertEquals([], conf.get('foo'))
3777
def test_get_default_list_from_env(self):
3778
self.register_list_option('foo', default_from_env=['FOO'])
3779
self.overrideEnv('FOO', '')
3780
conf = self.get_conf('')
3781
self.assertEquals([], conf.get('foo'))
3783
def test_get_with_list_converter_no_item(self):
3784
self.register_list_option('foo', None)
3785
conf = self.get_conf('foo=,')
3786
self.assertEquals([], conf.get('foo'))
3788
def test_get_with_list_converter_many_items(self):
3789
self.register_list_option('foo', None)
3790
conf = self.get_conf('foo=m,o,r,e')
3791
self.assertEquals(['m', 'o', 'r', 'e'], conf.get('foo'))
3793
def test_get_with_list_converter_embedded_spaces_many_items(self):
3794
self.register_list_option('foo', None)
3795
conf = self.get_conf('foo=" bar", "baz "')
3796
self.assertEquals([' bar', 'baz '], conf.get('foo'))
3798
def test_get_with_list_converter_stripped_spaces_many_items(self):
3799
self.register_list_option('foo', None)
3800
conf = self.get_conf('foo= bar , baz ')
3801
self.assertEquals(['bar', 'baz'], conf.get('foo'))
3804
class TestIterOptionRefs(tests.TestCase):
3805
"""iter_option_refs is a bit unusual, document some cases."""
3807
def assertRefs(self, expected, string):
3808
self.assertEquals(expected, list(config.iter_option_refs(string)))
3810
def test_empty(self):
3811
self.assertRefs([(False, '')], '')
3813
def test_no_refs(self):
3814
self.assertRefs([(False, 'foo bar')], 'foo bar')
3816
def test_single_ref(self):
3817
self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
3819
def test_broken_ref(self):
3820
self.assertRefs([(False, '{foo')], '{foo')
3822
def test_embedded_ref(self):
3823
self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
3826
def test_two_refs(self):
3827
self.assertRefs([(False, ''), (True, '{foo}'),
3828
(False, ''), (True, '{bar}'),
3832
def test_newline_in_refs_are_not_matched(self):
3833
self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
3836
class TestStackExpandOptions(tests.TestCaseWithTransport):
3839
super(TestStackExpandOptions, self).setUp()
3840
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3841
self.registry = config.option_registry
3842
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3843
self.conf = config.Stack([store.get_sections], store)
3845
def assertExpansion(self, expected, string, env=None):
3846
self.assertEquals(expected, self.conf.expand_options(string, env))
3848
def test_no_expansion(self):
3849
self.assertExpansion('foo', 'foo')
3851
def test_expand_default_value(self):
3852
self.conf.store._load_from_string('bar=baz')
3853
self.registry.register(config.Option('foo', default=u'{bar}'))
3854
self.assertEquals('baz', self.conf.get('foo', expand=True))
3856
def test_expand_default_from_env(self):
3857
self.conf.store._load_from_string('bar=baz')
3858
self.registry.register(config.Option('foo', default_from_env=['FOO']))
3859
self.overrideEnv('FOO', '{bar}')
3860
self.assertEquals('baz', self.conf.get('foo', expand=True))
3862
def test_expand_default_on_failed_conversion(self):
3863
self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
3864
self.registry.register(
3865
config.Option('foo', default=u'{bar}',
3866
from_unicode=config.int_from_store))
3867
self.assertEquals(42, self.conf.get('foo', expand=True))
3869
def test_env_adding_options(self):
3870
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3872
def test_env_overriding_options(self):
3873
self.conf.store._load_from_string('foo=baz')
3874
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3876
def test_simple_ref(self):
3877
self.conf.store._load_from_string('foo=xxx')
3878
self.assertExpansion('xxx', '{foo}')
3880
def test_unknown_ref(self):
3881
self.assertRaises(errors.ExpandingUnknownOption,
3882
self.conf.expand_options, '{foo}')
3884
def test_indirect_ref(self):
3885
self.conf.store._load_from_string('''
3889
self.assertExpansion('xxx', '{bar}')
3891
def test_embedded_ref(self):
3892
self.conf.store._load_from_string('''
3896
self.assertExpansion('xxx', '{{bar}}')
3898
def test_simple_loop(self):
3899
self.conf.store._load_from_string('foo={foo}')
3900
self.assertRaises(errors.OptionExpansionLoop,
3901
self.conf.expand_options, '{foo}')
3903
def test_indirect_loop(self):
3904
self.conf.store._load_from_string('''
3908
e = self.assertRaises(errors.OptionExpansionLoop,
3909
self.conf.expand_options, '{foo}')
3910
self.assertEquals('foo->bar->baz', e.refs)
3911
self.assertEquals('{foo}', e.string)
3913
def test_list(self):
3914
self.conf.store._load_from_string('''
3918
list={foo},{bar},{baz}
3920
self.registry.register(
3921
config.ListOption('list'))
3922
self.assertEquals(['start', 'middle', 'end'],
3923
self.conf.get('list', expand=True))
3925
def test_cascading_list(self):
3926
self.conf.store._load_from_string('''
3932
self.registry.register(config.ListOption('list'))
3933
# Register an intermediate option as a list to ensure no conversion
3934
# happen while expanding. Conversion should only occur for the original
3935
# option ('list' here).
3936
self.registry.register(config.ListOption('baz'))
3937
self.assertEquals(['start', 'middle', 'end'],
3938
self.conf.get('list', expand=True))
3940
def test_pathologically_hidden_list(self):
3941
self.conf.store._load_from_string('''
3947
hidden={start}{middle}{end}
3949
# What matters is what the registration says, the conversion happens
3950
# only after all expansions have been performed
3951
self.registry.register(config.ListOption('hidden'))
3952
self.assertEquals(['bin', 'go'],
3953
self.conf.get('hidden', expand=True))
3956
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3959
super(TestStackCrossSectionsExpand, self).setUp()
3961
def get_config(self, location, string):
3964
# Since we don't save the config we won't strictly require to inherit
3965
# from TestCaseInTempDir, but an error occurs so quickly...
3966
c = config.LocationStack(location)
3967
c.store._load_from_string(string)
3970
def test_dont_cross_unrelated_section(self):
3971
c = self.get_config('/another/branch/path','''
3976
[/another/branch/path]
3979
self.assertRaises(errors.ExpandingUnknownOption,
3980
c.get, 'bar', expand=True)
3982
def test_cross_related_sections(self):
3983
c = self.get_config('/project/branch/path','''
3987
[/project/branch/path]
3990
self.assertEquals('quux', c.get('bar', expand=True))
3993
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
3995
def test_cross_global_locations(self):
3996
l_store = config.LocationStore()
3997
l_store._load_from_string('''
4003
g_store = config.GlobalStore()
4004
g_store._load_from_string('''
4010
stack = config.LocationStack('/branch')
4011
self.assertEquals('glob-bar', stack.get('lbar', expand=True))
4012
self.assertEquals('loc-foo', stack.get('gfoo', expand=True))
4015
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
4017
def test_expand_locals_empty(self):
4018
l_store = config.LocationStore()
4019
l_store._load_from_string('''
4020
[/home/user/project]
4025
stack = config.LocationStack('/home/user/project/')
4026
self.assertEquals('', stack.get('base', expand=True))
4027
self.assertEquals('', stack.get('rel', expand=True))
4029
def test_expand_basename_locally(self):
4030
l_store = config.LocationStore()
4031
l_store._load_from_string('''
4032
[/home/user/project]
4036
stack = config.LocationStack('/home/user/project/branch')
4037
self.assertEquals('branch', stack.get('bfoo', expand=True))
4039
def test_expand_basename_locally_longer_path(self):
4040
l_store = config.LocationStore()
4041
l_store._load_from_string('''
4046
stack = config.LocationStack('/home/user/project/dir/branch')
4047
self.assertEquals('branch', stack.get('bfoo', expand=True))
4049
def test_expand_relpath_locally(self):
4050
l_store = config.LocationStore()
4051
l_store._load_from_string('''
4052
[/home/user/project]
4053
lfoo = loc-foo/{relpath}
4056
stack = config.LocationStack('/home/user/project/branch')
4057
self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
4059
def test_expand_relpath_unknonw_in_global(self):
4060
g_store = config.GlobalStore()
4061
g_store._load_from_string('''
4066
stack = config.LocationStack('/home/user/project/branch')
4067
self.assertRaises(errors.ExpandingUnknownOption,
4068
stack.get, 'gfoo', expand=True)
4070
def test_expand_local_option_locally(self):
4071
l_store = config.LocationStore()
4072
l_store._load_from_string('''
4073
[/home/user/project]
4074
lfoo = loc-foo/{relpath}
4078
g_store = config.GlobalStore()
4079
g_store._load_from_string('''
4085
stack = config.LocationStack('/home/user/project/branch')
4086
self.assertEquals('glob-bar', stack.get('lbar', expand=True))
4087
self.assertEquals('loc-foo/branch', stack.get('gfoo', expand=True))
4089
def test_locals_dont_leak(self):
4090
"""Make sure we chose the right local in presence of several sections.
4092
l_store = config.LocationStore()
4093
l_store._load_from_string('''
4095
lfoo = loc-foo/{relpath}
4096
[/home/user/project]
4097
lfoo = loc-foo/{relpath}
4100
stack = config.LocationStack('/home/user/project/branch')
4101
self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
4102
stack = config.LocationStack('/home/user/bar/baz')
4103
self.assertEquals('loc-foo/bar/baz', stack.get('lfoo', expand=True))
2935
4107
class TestStackSet(TestStackWithTransport):
2937
4109
def test_simple_set(self):
2938
4110
conf = self.get_stack(self)
2939
conf.store._load_from_string('foo=bar')
2940
self.assertEquals('bar', conf.get('foo'))
4111
self.assertEquals(None, conf.get('foo'))
2941
4112
conf.set('foo', 'baz')
2942
4113
# Did we get it back ?
2943
4114
self.assertEquals('baz', conf.get('foo'))