1312
1723
self.assertIs(None, bzrdir_config.get_default_stack_on())
1726
class TestOldConfigHooks(tests.TestCaseWithTransport):
1729
super(TestOldConfigHooks, self).setUp()
1730
create_configs_with_file_option(self)
1732
def assertGetHook(self, conf, name, value):
1737
config.OldConfigHooks.install_named_hook('get', hook, None)
1739
config.OldConfigHooks.uninstall_named_hook, 'get', None)
1740
self.assertLength(0, calls)
1741
actual_value = conf.get_user_option(name)
1742
self.assertEqual(value, actual_value)
1743
self.assertLength(1, calls)
1744
self.assertEqual((conf, name, value), calls[0])
1746
def test_get_hook_breezy(self):
1747
self.assertGetHook(self.breezy_config, 'file', 'breezy')
1749
def test_get_hook_locations(self):
1750
self.assertGetHook(self.locations_config, 'file', 'locations')
1752
def test_get_hook_branch(self):
1753
# Since locations masks branch, we define a different option
1754
self.branch_config.set_user_option('file2', 'branch')
1755
self.assertGetHook(self.branch_config, 'file2', 'branch')
1757
def assertSetHook(self, conf, name, value):
1762
config.OldConfigHooks.install_named_hook('set', hook, None)
1764
config.OldConfigHooks.uninstall_named_hook, 'set', None)
1765
self.assertLength(0, calls)
1766
conf.set_user_option(name, value)
1767
self.assertLength(1, calls)
1768
# We can't assert the conf object below as different configs use
1769
# different means to implement set_user_option and we care only about
1771
self.assertEqual((name, value), calls[0][1:])
1773
def test_set_hook_breezy(self):
1774
self.assertSetHook(self.breezy_config, 'foo', 'breezy')
1776
def test_set_hook_locations(self):
1777
self.assertSetHook(self.locations_config, 'foo', 'locations')
1779
def test_set_hook_branch(self):
1780
self.assertSetHook(self.branch_config, 'foo', 'branch')
1782
def assertRemoveHook(self, conf, name, section_name=None):
1787
config.OldConfigHooks.install_named_hook('remove', hook, None)
1789
config.OldConfigHooks.uninstall_named_hook, 'remove', None)
1790
self.assertLength(0, calls)
1791
conf.remove_user_option(name, section_name)
1792
self.assertLength(1, calls)
1793
# We can't assert the conf object below as different configs use
1794
# different means to implement remove_user_option and we care only about
1796
self.assertEqual((name,), calls[0][1:])
1798
def test_remove_hook_breezy(self):
1799
self.assertRemoveHook(self.breezy_config, 'file')
1801
def test_remove_hook_locations(self):
1802
self.assertRemoveHook(self.locations_config, 'file',
1803
self.locations_config.location)
1805
def test_remove_hook_branch(self):
1806
self.assertRemoveHook(self.branch_config, 'file')
1808
def assertLoadHook(self, name, conf_class, *conf_args):
1813
config.OldConfigHooks.install_named_hook('load', hook, None)
1815
config.OldConfigHooks.uninstall_named_hook, 'load', None)
1816
self.assertLength(0, calls)
1818
conf = conf_class(*conf_args)
1819
# Access an option to trigger a load
1820
conf.get_user_option(name)
1821
self.assertLength(1, calls)
1822
# Since we can't assert about conf, we just use the number of calls ;-/
1824
def test_load_hook_breezy(self):
1825
self.assertLoadHook('file', config.GlobalConfig)
1827
def test_load_hook_locations(self):
1828
self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
1830
def test_load_hook_branch(self):
1831
self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
1833
def assertSaveHook(self, conf):
1838
config.OldConfigHooks.install_named_hook('save', hook, None)
1840
config.OldConfigHooks.uninstall_named_hook, 'save', None)
1841
self.assertLength(0, calls)
1842
# Setting an option triggers a save
1843
conf.set_user_option('foo', 'bar')
1844
self.assertLength(1, calls)
1845
# Since we can't assert about conf, we just use the number of calls ;-/
1847
def test_save_hook_breezy(self):
1848
self.assertSaveHook(self.breezy_config)
1850
def test_save_hook_locations(self):
1851
self.assertSaveHook(self.locations_config)
1853
def test_save_hook_branch(self):
1854
self.assertSaveHook(self.branch_config)
1857
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
1858
"""Tests config hooks for remote configs.
1860
No tests for the remove hook as this is not implemented there.
1864
super(TestOldConfigHooksForRemote, self).setUp()
1865
self.transport_server = test_server.SmartTCPServer_for_testing
1866
create_configs_with_file_option(self)
1868
def assertGetHook(self, conf, name, value):
1873
config.OldConfigHooks.install_named_hook('get', hook, None)
1875
config.OldConfigHooks.uninstall_named_hook, 'get', None)
1876
self.assertLength(0, calls)
1877
actual_value = conf.get_option(name)
1878
self.assertEqual(value, actual_value)
1879
self.assertLength(1, calls)
1880
self.assertEqual((conf, name, value), calls[0])
1882
def test_get_hook_remote_branch(self):
1883
remote_branch = branch.Branch.open(self.get_url('tree'))
1884
self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
1886
def test_get_hook_remote_bzrdir(self):
1887
remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1888
conf = remote_bzrdir._get_config()
1889
conf.set_option('remotedir', 'file')
1890
self.assertGetHook(conf, 'file', 'remotedir')
1892
def assertSetHook(self, conf, name, value):
1897
config.OldConfigHooks.install_named_hook('set', hook, None)
1899
config.OldConfigHooks.uninstall_named_hook, 'set', None)
1900
self.assertLength(0, calls)
1901
conf.set_option(value, name)
1902
self.assertLength(1, calls)
1903
# We can't assert the conf object below as different configs use
1904
# different means to implement set_user_option and we care only about
1906
self.assertEqual((name, value), calls[0][1:])
1908
def test_set_hook_remote_branch(self):
1909
remote_branch = branch.Branch.open(self.get_url('tree'))
1910
self.addCleanup(remote_branch.lock_write().unlock)
1911
self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
1913
def test_set_hook_remote_bzrdir(self):
1914
remote_branch = branch.Branch.open(self.get_url('tree'))
1915
self.addCleanup(remote_branch.lock_write().unlock)
1916
remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1917
self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
1919
def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
1924
config.OldConfigHooks.install_named_hook('load', hook, None)
1926
config.OldConfigHooks.uninstall_named_hook, 'load', None)
1927
self.assertLength(0, calls)
1929
conf = conf_class(*conf_args)
1930
# Access an option to trigger a load
1931
conf.get_option(name)
1932
self.assertLength(expected_nb_calls, calls)
1933
# Since we can't assert about conf, we just use the number of calls ;-/
1935
def test_load_hook_remote_branch(self):
1936
remote_branch = branch.Branch.open(self.get_url('tree'))
1937
self.assertLoadHook(
1938
1, 'file', remote.RemoteBranchConfig, remote_branch)
1940
def test_load_hook_remote_bzrdir(self):
1941
remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1942
# The config file doesn't exist, set an option to force its creation
1943
conf = remote_bzrdir._get_config()
1944
conf.set_option('remotedir', 'file')
1945
# We get one call for the server and one call for the client, this is
1946
# caused by the differences in implementations betwen
1947
# SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
1948
# SmartServerBranchGetConfigFile (in smart/branch.py)
1949
self.assertLoadHook(
1950
2, 'file', remote.RemoteBzrDirConfig, remote_bzrdir)
1952
def assertSaveHook(self, conf):
1957
config.OldConfigHooks.install_named_hook('save', hook, None)
1959
config.OldConfigHooks.uninstall_named_hook, 'save', None)
1960
self.assertLength(0, calls)
1961
# Setting an option triggers a save
1962
conf.set_option('foo', 'bar')
1963
self.assertLength(1, calls)
1964
# Since we can't assert about conf, we just use the number of calls ;-/
1966
def test_save_hook_remote_branch(self):
1967
remote_branch = branch.Branch.open(self.get_url('tree'))
1968
self.addCleanup(remote_branch.lock_write().unlock)
1969
self.assertSaveHook(remote_branch._get_config())
1971
def test_save_hook_remote_bzrdir(self):
1972
remote_branch = branch.Branch.open(self.get_url('tree'))
1973
self.addCleanup(remote_branch.lock_write().unlock)
1974
remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1975
self.assertSaveHook(remote_bzrdir._get_config())
1978
class TestOptionNames(tests.TestCase):
1980
def is_valid(self, name):
1981
return config._option_ref_re.match('{%s}' % name) is not None
1983
def test_valid_names(self):
1984
self.assertTrue(self.is_valid('foo'))
1985
self.assertTrue(self.is_valid('foo.bar'))
1986
self.assertTrue(self.is_valid('f1'))
1987
self.assertTrue(self.is_valid('_'))
1988
self.assertTrue(self.is_valid('__bar__'))
1989
self.assertTrue(self.is_valid('a_'))
1990
self.assertTrue(self.is_valid('a1'))
1991
# Don't break bzr-svn for no good reason
1992
self.assertTrue(self.is_valid('guessed-layout'))
1994
def test_invalid_names(self):
1995
self.assertFalse(self.is_valid(' foo'))
1996
self.assertFalse(self.is_valid('foo '))
1997
self.assertFalse(self.is_valid('1'))
1998
self.assertFalse(self.is_valid('1,2'))
1999
self.assertFalse(self.is_valid('foo$'))
2000
self.assertFalse(self.is_valid('!foo'))
2001
self.assertFalse(self.is_valid('foo.'))
2002
self.assertFalse(self.is_valid('foo..bar'))
2003
self.assertFalse(self.is_valid('{}'))
2004
self.assertFalse(self.is_valid('{a}'))
2005
self.assertFalse(self.is_valid('a\n'))
2006
self.assertFalse(self.is_valid('-'))
2007
self.assertFalse(self.is_valid('-a'))
2008
self.assertFalse(self.is_valid('a-'))
2009
self.assertFalse(self.is_valid('a--a'))
2011
def assertSingleGroup(self, reference):
2012
# the regexp is used with split and as such should match the reference
2013
# *only*, if more groups needs to be defined, (?:...) should be used.
2014
m = config._option_ref_re.match('{a}')
2015
self.assertLength(1, m.groups())
2017
def test_valid_references(self):
2018
self.assertSingleGroup('{a}')
2019
self.assertSingleGroup('{{a}}')
2022
class TestOption(tests.TestCase):
2024
def test_default_value(self):
2025
opt = config.Option('foo', default='bar')
2026
self.assertEqual('bar', opt.get_default())
2028
def test_callable_default_value(self):
2029
def bar_as_unicode():
2031
opt = config.Option('foo', default=bar_as_unicode)
2032
self.assertEqual('bar', opt.get_default())
2034
def test_default_value_from_env(self):
2035
opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2036
self.overrideEnv('FOO', 'quux')
2037
# Env variable provides a default taking over the option one
2038
self.assertEqual('quux', opt.get_default())
2040
def test_first_default_value_from_env_wins(self):
2041
opt = config.Option('foo', default='bar',
2042
default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2043
self.overrideEnv('FOO', 'foo')
2044
self.overrideEnv('BAZ', 'baz')
2045
# The first env var set wins
2046
self.assertEqual('foo', opt.get_default())
2048
def test_not_supported_list_default_value(self):
2049
self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2051
def test_not_supported_object_default_value(self):
2052
self.assertRaises(AssertionError, config.Option, 'foo',
2055
def test_not_supported_callable_default_value_not_unicode(self):
2056
def bar_not_unicode():
2058
opt = config.Option('foo', default=bar_not_unicode)
2059
self.assertRaises(AssertionError, opt.get_default)
2061
def test_get_help_topic(self):
2062
opt = config.Option('foo')
2063
self.assertEqual('foo', opt.get_help_topic())
2066
class TestOptionConverter(tests.TestCase):
2068
def assertConverted(self, expected, opt, value):
2069
self.assertEqual(expected, opt.convert_from_unicode(None, value))
2071
def assertCallsWarning(self, opt, value):
2075
warnings.append(args[0] % args[1:])
2076
self.overrideAttr(trace, 'warning', warning)
2077
self.assertEqual(None, opt.convert_from_unicode(None, value))
2078
self.assertLength(1, warnings)
2080
'Value "%s" is not valid for "%s"' % (value, opt.name),
2083
def assertCallsError(self, opt, value):
2084
self.assertRaises(config.ConfigOptionValueError,
2085
opt.convert_from_unicode, None, value)
2087
def assertConvertInvalid(self, opt, invalid_value):
2089
self.assertEqual(None, opt.convert_from_unicode(None, invalid_value))
2090
opt.invalid = 'warning'
2091
self.assertCallsWarning(opt, invalid_value)
2092
opt.invalid = 'error'
2093
self.assertCallsError(opt, invalid_value)
2096
class TestOptionWithBooleanConverter(TestOptionConverter):
2098
def get_option(self):
2099
return config.Option('foo', help='A boolean.',
2100
from_unicode=config.bool_from_store)
2102
def test_convert_invalid(self):
2103
opt = self.get_option()
2104
# A string that is not recognized as a boolean
2105
self.assertConvertInvalid(opt, u'invalid-boolean')
2106
# A list of strings is never recognized as a boolean
2107
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2109
def test_convert_valid(self):
2110
opt = self.get_option()
2111
self.assertConverted(True, opt, u'True')
2112
self.assertConverted(True, opt, u'1')
2113
self.assertConverted(False, opt, u'False')
2116
class TestOptionWithIntegerConverter(TestOptionConverter):
2118
def get_option(self):
2119
return config.Option('foo', help='An integer.',
2120
from_unicode=config.int_from_store)
2122
def test_convert_invalid(self):
2123
opt = self.get_option()
2124
# A string that is not recognized as an integer
2125
self.assertConvertInvalid(opt, u'forty-two')
2126
# A list of strings is never recognized as an integer
2127
self.assertConvertInvalid(opt, [u'a', u'list'])
2129
def test_convert_valid(self):
2130
opt = self.get_option()
2131
self.assertConverted(16, opt, u'16')
2134
class TestOptionWithSIUnitConverter(TestOptionConverter):
2136
def get_option(self):
2137
return config.Option('foo', help='An integer in SI units.',
2138
from_unicode=config.int_SI_from_store)
2140
def test_convert_invalid(self):
2141
opt = self.get_option()
2142
self.assertConvertInvalid(opt, u'not-a-unit')
2143
self.assertConvertInvalid(opt, u'Gb') # Forgot the value
2144
self.assertConvertInvalid(opt, u'1b') # Forgot the unit
2145
self.assertConvertInvalid(opt, u'1GG')
2146
self.assertConvertInvalid(opt, u'1Mbb')
2147
self.assertConvertInvalid(opt, u'1MM')
2149
def test_convert_valid(self):
2150
opt = self.get_option()
2151
self.assertConverted(int(5e3), opt, u'5kb')
2152
self.assertConverted(int(5e6), opt, u'5M')
2153
self.assertConverted(int(5e6), opt, u'5MB')
2154
self.assertConverted(int(5e9), opt, u'5g')
2155
self.assertConverted(int(5e9), opt, u'5gB')
2156
self.assertConverted(100, opt, u'100')
2159
class TestListOption(TestOptionConverter):
2161
def get_option(self):
2162
return config.ListOption('foo', help='A list.')
2164
def test_convert_invalid(self):
2165
opt = self.get_option()
2166
# We don't even try to convert a list into a list, we only expect
2168
self.assertConvertInvalid(opt, [1])
2169
# No string is invalid as all forms can be converted to a list
2171
def test_convert_valid(self):
2172
opt = self.get_option()
2173
# An empty string is an empty list
2174
self.assertConverted([], opt, '') # Using a bare str() just in case
2175
self.assertConverted([], opt, u'')
2177
self.assertConverted([u'True'], opt, u'True')
2179
self.assertConverted([u'42'], opt, u'42')
2181
self.assertConverted([u'bar'], opt, u'bar')
2184
class TestRegistryOption(TestOptionConverter):
2186
def get_option(self, registry):
2187
return config.RegistryOption('foo', registry,
2188
help='A registry option.')
2190
def test_convert_invalid(self):
2191
registry = _mod_registry.Registry()
2192
opt = self.get_option(registry)
2193
self.assertConvertInvalid(opt, [1])
2194
self.assertConvertInvalid(opt, u"notregistered")
2196
def test_convert_valid(self):
2197
registry = _mod_registry.Registry()
2198
registry.register("someval", 1234)
2199
opt = self.get_option(registry)
2200
# Using a bare str() just in case
2201
self.assertConverted(1234, opt, "someval")
2202
self.assertConverted(1234, opt, u'someval')
2203
self.assertConverted(None, opt, None)
2205
def test_help(self):
2206
registry = _mod_registry.Registry()
2207
registry.register("someval", 1234, help="some option")
2208
registry.register("dunno", 1234, help="some other option")
2209
opt = self.get_option(registry)
2211
'A registry option.\n'
2213
'The following values are supported:\n'
2214
' dunno - some other option\n'
2215
' someval - some option\n',
2218
def test_get_help_text(self):
2219
registry = _mod_registry.Registry()
2220
registry.register("someval", 1234, help="some option")
2221
registry.register("dunno", 1234, help="some other option")
2222
opt = self.get_option(registry)
2224
'A registry option.\n'
2226
'The following values are supported:\n'
2227
' dunno - some other option\n'
2228
' someval - some option\n',
2229
opt.get_help_text())
2232
class TestOptionRegistry(tests.TestCase):
2235
super(TestOptionRegistry, self).setUp()
2236
# Always start with an empty registry
2237
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2238
self.registry = config.option_registry
2240
def test_register(self):
2241
opt = config.Option('foo')
2242
self.registry.register(opt)
2243
self.assertIs(opt, self.registry.get('foo'))
2245
def test_registered_help(self):
2246
opt = config.Option('foo', help='A simple option')
2247
self.registry.register(opt)
2248
self.assertEqual('A simple option', self.registry.get_help('foo'))
2250
def test_dont_register_illegal_name(self):
2251
self.assertRaises(config.IllegalOptionName,
2252
self.registry.register, config.Option(' foo'))
2253
self.assertRaises(config.IllegalOptionName,
2254
self.registry.register, config.Option('bar,'))
2256
lazy_option = config.Option('lazy_foo', help='Lazy help')
2258
def test_register_lazy(self):
2259
self.registry.register_lazy('lazy_foo', self.__module__,
2260
'TestOptionRegistry.lazy_option')
2261
self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2263
def test_registered_lazy_help(self):
2264
self.registry.register_lazy('lazy_foo', self.__module__,
2265
'TestOptionRegistry.lazy_option')
2266
self.assertEqual('Lazy help', self.registry.get_help('lazy_foo'))
2268
def test_dont_lazy_register_illegal_name(self):
2269
# This is where the root cause of http://pad.lv/1235099 is better
2270
# understood: 'register_lazy' doc string mentions that key should match
2271
# the option name which indirectly requires that the option name is a
2272
# valid python identifier. We violate that rule here (using a key that
2273
# doesn't match the option name) to test the option name checking.
2274
self.assertRaises(config.IllegalOptionName,
2275
self.registry.register_lazy, ' foo', self.__module__,
2276
'TestOptionRegistry.lazy_option')
2277
self.assertRaises(config.IllegalOptionName,
2278
self.registry.register_lazy, '1,2', self.__module__,
2279
'TestOptionRegistry.lazy_option')
2282
class TestRegisteredOptions(tests.TestCase):
2283
"""All registered options should verify some constraints."""
2285
scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2286
in config.option_registry.iteritems()]
2289
super(TestRegisteredOptions, self).setUp()
2290
self.registry = config.option_registry
2292
def test_proper_name(self):
2293
# An option should be registered under its own name, this can't be
2294
# checked at registration time for the lazy ones.
2295
self.assertEqual(self.option_name, self.option.name)
2297
def test_help_is_set(self):
2298
option_help = self.registry.get_help(self.option_name)
2299
# Come on, think about the user, he really wants to know what the
2301
self.assertIsNot(None, option_help)
2302
self.assertNotEqual('', option_help)
2305
class TestSection(tests.TestCase):
2307
# FIXME: Parametrize so that all sections produced by Stores run these
2308
# tests -- vila 2011-04-01
2310
def test_get_a_value(self):
2311
a_dict = dict(foo='bar')
2312
section = config.Section('myID', a_dict)
2313
self.assertEqual('bar', section.get('foo'))
2315
def test_get_unknown_option(self):
2317
section = config.Section(None, a_dict)
2318
self.assertEqual('out of thin air',
2319
section.get('foo', 'out of thin air'))
2321
def test_options_is_shared(self):
2323
section = config.Section(None, a_dict)
2324
self.assertIs(a_dict, section.options)
2327
class TestMutableSection(tests.TestCase):
2329
scenarios = [('mutable',
2331
lambda opts: config.MutableSection('myID', opts)},),
2335
a_dict = dict(foo='bar')
2336
section = self.get_section(a_dict)
2337
section.set('foo', 'new_value')
2338
self.assertEqual('new_value', section.get('foo'))
2339
# The change appears in the shared section
2340
self.assertEqual('new_value', a_dict.get('foo'))
2341
# We keep track of the change
2342
self.assertTrue('foo' in section.orig)
2343
self.assertEqual('bar', section.orig.get('foo'))
2345
def test_set_preserve_original_once(self):
2346
a_dict = dict(foo='bar')
2347
section = self.get_section(a_dict)
2348
section.set('foo', 'first_value')
2349
section.set('foo', 'second_value')
2350
# We keep track of the original value
2351
self.assertTrue('foo' in section.orig)
2352
self.assertEqual('bar', section.orig.get('foo'))
2354
def test_remove(self):
2355
a_dict = dict(foo='bar')
2356
section = self.get_section(a_dict)
2357
section.remove('foo')
2358
# We get None for unknown options via the default value
2359
self.assertEqual(None, section.get('foo'))
2360
# Or we just get the default value
2361
self.assertEqual('unknown', section.get('foo', 'unknown'))
2362
self.assertFalse('foo' in section.options)
2363
# We keep track of the deletion
2364
self.assertTrue('foo' in section.orig)
2365
self.assertEqual('bar', section.orig.get('foo'))
2367
def test_remove_new_option(self):
2369
section = self.get_section(a_dict)
2370
section.set('foo', 'bar')
2371
section.remove('foo')
2372
self.assertFalse('foo' in section.options)
2373
# The option didn't exist initially so it we need to keep track of it
2374
# with a special value
2375
self.assertTrue('foo' in section.orig)
2376
self.assertEqual(config._NewlyCreatedOption, section.orig['foo'])
2379
class TestCommandLineStore(tests.TestCase):
2382
super(TestCommandLineStore, self).setUp()
2383
self.store = config.CommandLineStore()
2384
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2386
def get_section(self):
2387
"""Get the unique section for the command line overrides."""
2388
sections = list(self.store.get_sections())
2389
self.assertLength(1, sections)
2390
store, section = sections[0]
2391
self.assertEqual(self.store, store)
2394
def test_no_override(self):
2395
self.store._from_cmdline([])
2396
section = self.get_section()
2397
self.assertLength(0, list(section.iter_option_names()))
2399
def test_simple_override(self):
2400
self.store._from_cmdline(['a=b'])
2401
section = self.get_section()
2402
self.assertEqual('b', section.get('a'))
2404
def test_list_override(self):
2405
opt = config.ListOption('l')
2406
config.option_registry.register(opt)
2407
self.store._from_cmdline(['l=1,2,3'])
2408
val = self.get_section().get('l')
2409
self.assertEqual('1,2,3', val)
2410
# Reminder: lists should be registered as such explicitely, otherwise
2411
# the conversion needs to be done afterwards.
2412
self.assertEqual(['1', '2', '3'],
2413
opt.convert_from_unicode(self.store, val))
2415
def test_multiple_overrides(self):
2416
self.store._from_cmdline(['a=b', 'x=y'])
2417
section = self.get_section()
2418
self.assertEqual('b', section.get('a'))
2419
self.assertEqual('y', section.get('x'))
2421
def test_wrong_syntax(self):
2422
self.assertRaises(errors.BzrCommandError,
2423
self.store._from_cmdline, ['a=b', 'c'])
2426
class TestStoreMinimalAPI(tests.TestCaseWithTransport):
2428
scenarios = [(key, {'get_store': builder}) for key, builder
2429
in config.test_store_builder_registry.iteritems()] + [
2430
('cmdline', {'get_store': lambda test: config.CommandLineStore()})]
2433
store = self.get_store(self)
2434
if isinstance(store, config.TransportIniFileStore):
2435
raise tests.TestNotApplicable(
2436
"%s is not a concrete Store implementation"
2437
" so it doesn't need an id" % (store.__class__.__name__,))
2438
self.assertIsNot(None, store.id)
2441
class TestStore(tests.TestCaseWithTransport):
2443
def assertSectionContent(self, expected, store_and_section):
2444
"""Assert that some options have the proper values in a section."""
2445
_, section = store_and_section
2446
expected_name, expected_options = expected
2447
self.assertEqual(expected_name, section.id)
2450
dict([(k, section.get(k)) for k in expected_options.keys()]))
2453
class TestReadonlyStore(TestStore):
2455
scenarios = [(key, {'get_store': builder}) for key, builder
2456
in config.test_store_builder_registry.iteritems()]
2458
def test_building_delays_load(self):
2459
store = self.get_store(self)
2460
self.assertEqual(False, store.is_loaded())
2461
store._load_from_string(b'')
2462
self.assertEqual(True, store.is_loaded())
2464
def test_get_no_sections_for_empty(self):
2465
store = self.get_store(self)
2466
store._load_from_string(b'')
2467
self.assertEqual([], list(store.get_sections()))
2469
def test_get_default_section(self):
2470
store = self.get_store(self)
2471
store._load_from_string(b'foo=bar')
2472
sections = list(store.get_sections())
2473
self.assertLength(1, sections)
2474
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2476
def test_get_named_section(self):
2477
store = self.get_store(self)
2478
store._load_from_string(b'[baz]\nfoo=bar')
2479
sections = list(store.get_sections())
2480
self.assertLength(1, sections)
2481
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2483
def test_load_from_string_fails_for_non_empty_store(self):
2484
store = self.get_store(self)
2485
store._load_from_string(b'foo=bar')
2486
self.assertRaises(AssertionError, store._load_from_string, b'bar=baz')
2489
class TestStoreQuoting(TestStore):
2491
scenarios = [(key, {'get_store': builder}) for key, builder
2492
in config.test_store_builder_registry.iteritems()]
2495
super(TestStoreQuoting, self).setUp()
2496
self.store = self.get_store(self)
2497
# We need a loaded store but any content will do
2498
self.store._load_from_string(b'')
2500
def assertIdempotent(self, s):
2501
"""Assert that quoting an unquoted string is a no-op and vice-versa.
2503
What matters here is that option values, as they appear in a store, can
2504
be safely round-tripped out of the store and back.
2506
:param s: A string, quoted if required.
2508
self.assertEqual(s, self.store.quote(self.store.unquote(s)))
2509
self.assertEqual(s, self.store.unquote(self.store.quote(s)))
2511
def test_empty_string(self):
2512
if isinstance(self.store, config.IniFileStore):
2513
# configobj._quote doesn't handle empty values
2514
self.assertRaises(AssertionError,
2515
self.assertIdempotent, '')
2517
self.assertIdempotent('')
2518
# But quoted empty strings are ok
2519
self.assertIdempotent('""')
2521
def test_embedded_spaces(self):
2522
self.assertIdempotent('" a b c "')
2524
def test_embedded_commas(self):
2525
self.assertIdempotent('" a , b c "')
2527
def test_simple_comma(self):
2528
if isinstance(self.store, config.IniFileStore):
2529
# configobj requires that lists are special-cased
2530
self.assertRaises(AssertionError,
2531
self.assertIdempotent, ',')
2533
self.assertIdempotent(',')
2534
# When a single comma is required, quoting is also required
2535
self.assertIdempotent('","')
2537
def test_list(self):
2538
if isinstance(self.store, config.IniFileStore):
2539
# configobj requires that lists are special-cased
2540
self.assertRaises(AssertionError,
2541
self.assertIdempotent, 'a,b')
2543
self.assertIdempotent('a,b')
2546
class TestDictFromStore(tests.TestCase):
2548
def test_unquote_not_string(self):
2549
conf = config.MemoryStack(b'x=2\n[a_section]\na=1\n')
2550
value = conf.get('a_section')
2551
# Urgh, despite 'conf' asking for the no-name section, we get the
2552
# content of another section as a dict o_O
2553
self.assertEqual({'a': '1'}, value)
2554
unquoted = conf.store.unquote(value)
2555
# Which cannot be unquoted but shouldn't crash either (the use cases
2556
# are getting the value or displaying it. In the later case, '%s' will
2558
self.assertEqual({'a': '1'}, unquoted)
2559
self.assertIn('%s' % (unquoted,), ("{u'a': u'1'}", "{'a': '1'}"))
2562
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2563
"""Simulate loading a config store with content of various encodings.
2565
All files produced by bzr are in utf8 content.
2567
Users may modify them manually and end up with a file that can't be
2568
loaded. We need to issue proper error messages in this case.
2571
invalid_utf8_char = b'\xff'
2573
def test_load_utf8(self):
2574
"""Ensure we can load an utf8-encoded file."""
2575
t = self.get_transport()
2576
# From http://pad.lv/799212
2577
unicode_user = u'b\N{Euro Sign}ar'
2578
unicode_content = u'user=%s' % (unicode_user,)
2579
utf8_content = unicode_content.encode('utf8')
2580
# Store the raw content in the config file
2581
t.put_bytes('foo.conf', utf8_content)
2582
store = config.TransportIniFileStore(t, 'foo.conf')
2584
stack = config.Stack([store.get_sections], store)
2585
self.assertEqual(unicode_user, stack.get('user'))
2587
def test_load_non_ascii(self):
2588
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2589
t = self.get_transport()
2590
t.put_bytes('foo.conf', b'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2591
store = config.TransportIniFileStore(t, 'foo.conf')
2592
self.assertRaises(config.ConfigContentError, store.load)
2594
def test_load_erroneous_content(self):
2595
"""Ensure we display a proper error on content that can't be parsed."""
2596
t = self.get_transport()
2597
t.put_bytes('foo.conf', b'[open_section\n')
2598
store = config.TransportIniFileStore(t, 'foo.conf')
2599
self.assertRaises(config.ParseConfigError, store.load)
2601
def test_load_permission_denied(self):
2602
"""Ensure we get warned when trying to load an inaccessible file."""
2606
warnings.append(args[0] % args[1:])
2607
self.overrideAttr(trace, 'warning', warning)
2609
t = self.get_transport()
2611
def get_bytes(relpath):
2612
raise errors.PermissionDenied(relpath, "")
2613
t.get_bytes = get_bytes
2614
store = config.TransportIniFileStore(t, 'foo.conf')
2615
self.assertRaises(errors.PermissionDenied, store.load)
2618
[u'Permission denied while trying to load configuration store %s.'
2619
% store.external_url()])
2622
class TestIniConfigContent(tests.TestCaseWithTransport):
2623
"""Simulate loading a IniBasedConfig with content of various encodings.
2625
All files produced by bzr are in utf8 content.
2627
Users may modify them manually and end up with a file that can't be
2628
loaded. We need to issue proper error messages in this case.
2631
invalid_utf8_char = b'\xff'
2633
def test_load_utf8(self):
2634
"""Ensure we can load an utf8-encoded file."""
2635
# From http://pad.lv/799212
2636
unicode_user = u'b\N{Euro Sign}ar'
2637
unicode_content = u'user=%s' % (unicode_user,)
2638
utf8_content = unicode_content.encode('utf8')
2639
# Store the raw content in the config file
2640
with open('foo.conf', 'wb') as f:
2641
f.write(utf8_content)
2642
conf = config.IniBasedConfig(file_name='foo.conf')
2643
self.assertEqual(unicode_user, conf.get_user_option('user'))
2645
def test_load_badly_encoded_content(self):
2646
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2647
with open('foo.conf', 'wb') as f:
2648
f.write(b'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2649
conf = config.IniBasedConfig(file_name='foo.conf')
2650
self.assertRaises(config.ConfigContentError, conf._get_parser)
2652
def test_load_erroneous_content(self):
2653
"""Ensure we display a proper error on content that can't be parsed."""
2654
with open('foo.conf', 'wb') as f:
2655
f.write(b'[open_section\n')
2656
conf = config.IniBasedConfig(file_name='foo.conf')
2657
self.assertRaises(config.ParseConfigError, conf._get_parser)
2660
class TestMutableStore(TestStore):
2662
scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2663
in config.test_store_builder_registry.iteritems()]
2666
super(TestMutableStore, self).setUp()
2667
self.transport = self.get_transport()
2669
def has_store(self, store):
2670
store_basename = urlutils.relative_url(self.transport.external_url(),
2671
store.external_url())
2672
return self.transport.has(store_basename)
2674
def test_save_empty_creates_no_file(self):
2675
# FIXME: There should be a better way than relying on the test
2676
# parametrization to identify branch.conf -- vila 2011-0526
2677
if self.store_id in ('branch', 'remote_branch'):
2678
raise tests.TestNotApplicable(
2679
'branch.conf is *always* created when a branch is initialized')
2680
store = self.get_store(self)
2682
self.assertEqual(False, self.has_store(store))
2684
def test_mutable_section_shared(self):
2685
store = self.get_store(self)
2686
store._load_from_string(b'foo=bar\n')
2687
# FIXME: There should be a better way than relying on the test
2688
# parametrization to identify branch.conf -- vila 2011-0526
2689
if self.store_id in ('branch', 'remote_branch'):
2690
# branch stores requires write locked branches
2691
self.addCleanup(store.branch.lock_write().unlock)
2692
section1 = store.get_mutable_section(None)
2693
section2 = store.get_mutable_section(None)
2694
# If we get different sections, different callers won't share the
2696
self.assertIs(section1, section2)
2698
def test_save_emptied_succeeds(self):
2699
store = self.get_store(self)
2700
store._load_from_string(b'foo=bar\n')
2701
# FIXME: There should be a better way than relying on the test
2702
# parametrization to identify branch.conf -- vila 2011-0526
2703
if self.store_id in ('branch', 'remote_branch'):
2704
# branch stores requires write locked branches
2705
self.addCleanup(store.branch.lock_write().unlock)
2706
section = store.get_mutable_section(None)
2707
section.remove('foo')
2709
self.assertEqual(True, self.has_store(store))
2710
modified_store = self.get_store(self)
2711
sections = list(modified_store.get_sections())
2712
self.assertLength(0, sections)
2714
def test_save_with_content_succeeds(self):
2715
# FIXME: There should be a better way than relying on the test
2716
# parametrization to identify branch.conf -- vila 2011-0526
2717
if self.store_id in ('branch', 'remote_branch'):
2718
raise tests.TestNotApplicable(
2719
'branch.conf is *always* created when a branch is initialized')
2720
store = self.get_store(self)
2721
store._load_from_string(b'foo=bar\n')
2722
self.assertEqual(False, self.has_store(store))
2724
self.assertEqual(True, self.has_store(store))
2725
modified_store = self.get_store(self)
2726
sections = list(modified_store.get_sections())
2727
self.assertLength(1, sections)
2728
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2730
def test_set_option_in_empty_store(self):
2731
store = self.get_store(self)
2732
# FIXME: There should be a better way than relying on the test
2733
# parametrization to identify branch.conf -- vila 2011-0526
2734
if self.store_id in ('branch', 'remote_branch'):
2735
# branch stores requires write locked branches
2736
self.addCleanup(store.branch.lock_write().unlock)
2737
section = store.get_mutable_section(None)
2738
section.set('foo', 'bar')
2740
modified_store = self.get_store(self)
2741
sections = list(modified_store.get_sections())
2742
self.assertLength(1, sections)
2743
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2745
def test_set_option_in_default_section(self):
2746
store = self.get_store(self)
2747
store._load_from_string(b'')
2748
# FIXME: There should be a better way than relying on the test
2749
# parametrization to identify branch.conf -- vila 2011-0526
2750
if self.store_id in ('branch', 'remote_branch'):
2751
# branch stores requires write locked branches
2752
self.addCleanup(store.branch.lock_write().unlock)
2753
section = store.get_mutable_section(None)
2754
section.set('foo', 'bar')
2756
modified_store = self.get_store(self)
2757
sections = list(modified_store.get_sections())
2758
self.assertLength(1, sections)
2759
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2761
def test_set_option_in_named_section(self):
2762
store = self.get_store(self)
2763
store._load_from_string(b'')
2764
# FIXME: There should be a better way than relying on the test
2765
# parametrization to identify branch.conf -- vila 2011-0526
2766
if self.store_id in ('branch', 'remote_branch'):
2767
# branch stores requires write locked branches
2768
self.addCleanup(store.branch.lock_write().unlock)
2769
section = store.get_mutable_section('baz')
2770
section.set('foo', 'bar')
2772
modified_store = self.get_store(self)
2773
sections = list(modified_store.get_sections())
2774
self.assertLength(1, sections)
2775
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2777
def test_load_hook(self):
2778
# First, we need to ensure that the store exists
2779
store = self.get_store(self)
2780
# FIXME: There should be a better way than relying on the test
2781
# parametrization to identify branch.conf -- vila 2011-0526
2782
if self.store_id in ('branch', 'remote_branch'):
2783
# branch stores requires write locked branches
2784
self.addCleanup(store.branch.lock_write().unlock)
2785
section = store.get_mutable_section('baz')
2786
section.set('foo', 'bar')
2788
# Now we can try to load it
2789
store = self.get_store(self)
2794
config.ConfigHooks.install_named_hook('load', hook, None)
2795
self.assertLength(0, calls)
2797
self.assertLength(1, calls)
2798
self.assertEqual((store,), calls[0])
2800
def test_save_hook(self):
2805
config.ConfigHooks.install_named_hook('save', hook, None)
2806
self.assertLength(0, calls)
2807
store = self.get_store(self)
2808
# FIXME: There should be a better way than relying on the test
2809
# parametrization to identify branch.conf -- vila 2011-0526
2810
if self.store_id in ('branch', 'remote_branch'):
2811
# branch stores requires write locked branches
2812
self.addCleanup(store.branch.lock_write().unlock)
2813
section = store.get_mutable_section('baz')
2814
section.set('foo', 'bar')
2816
self.assertLength(1, calls)
2817
self.assertEqual((store,), calls[0])
2819
def test_set_mark_dirty(self):
2820
stack = config.MemoryStack(b'')
2821
self.assertLength(0, stack.store.dirty_sections)
2822
stack.set('foo', 'baz')
2823
self.assertLength(1, stack.store.dirty_sections)
2824
self.assertTrue(stack.store._need_saving())
2826
def test_remove_mark_dirty(self):
2827
stack = config.MemoryStack(b'foo=bar')
2828
self.assertLength(0, stack.store.dirty_sections)
2830
self.assertLength(1, stack.store.dirty_sections)
2831
self.assertTrue(stack.store._need_saving())
2834
class TestStoreSaveChanges(tests.TestCaseWithTransport):
2835
"""Tests that config changes are kept in memory and saved on-demand."""
2838
super(TestStoreSaveChanges, self).setUp()
2839
self.transport = self.get_transport()
2840
# Most of the tests involve two stores pointing to the same persistent
2841
# storage to observe the effects of concurrent changes
2842
self.st1 = config.TransportIniFileStore(self.transport, 'foo.conf')
2843
self.st2 = config.TransportIniFileStore(self.transport, 'foo.conf')
2847
self.warnings.append(args[0] % args[1:])
2848
self.overrideAttr(trace, 'warning', warning)
2850
def has_store(self, store):
2851
store_basename = urlutils.relative_url(self.transport.external_url(),
2852
store.external_url())
2853
return self.transport.has(store_basename)
2855
def get_stack(self, store):
2856
# Any stack will do as long as it uses the right store, just a single
2857
# no-name section is enough
2858
return config.Stack([store.get_sections], store)
2860
def test_no_changes_no_save(self):
2861
s = self.get_stack(self.st1)
2862
s.store.save_changes()
2863
self.assertEqual(False, self.has_store(self.st1))
2865
def test_unrelated_concurrent_update(self):
2866
s1 = self.get_stack(self.st1)
2867
s2 = self.get_stack(self.st2)
2868
s1.set('foo', 'bar')
2869
s2.set('baz', 'quux')
2871
# Changes don't propagate magically
2872
self.assertEqual(None, s1.get('baz'))
2873
s2.store.save_changes()
2874
self.assertEqual('quux', s2.get('baz'))
2875
# Changes are acquired when saving
2876
self.assertEqual('bar', s2.get('foo'))
2877
# Since there is no overlap, no warnings are emitted
2878
self.assertLength(0, self.warnings)
2880
def test_concurrent_update_modified(self):
2881
s1 = self.get_stack(self.st1)
2882
s2 = self.get_stack(self.st2)
2883
s1.set('foo', 'bar')
2884
s2.set('foo', 'baz')
2887
s2.store.save_changes()
2888
self.assertEqual('baz', s2.get('foo'))
2889
# But the user get a warning
2890
self.assertLength(1, self.warnings)
2891
warning = self.warnings[0]
2892
self.assertStartsWith(warning, 'Option foo in section None')
2893
self.assertEndsWith(warning, 'was changed from <CREATED> to bar.'
2894
' The baz value will be saved.')
2896
def test_concurrent_deletion(self):
2897
self.st1._load_from_string(b'foo=bar')
2899
s1 = self.get_stack(self.st1)
2900
s2 = self.get_stack(self.st2)
2903
s1.store.save_changes()
2905
self.assertLength(0, self.warnings)
2906
s2.store.save_changes()
2908
self.assertLength(1, self.warnings)
2909
warning = self.warnings[0]
2910
self.assertStartsWith(warning, 'Option foo in section None')
2911
self.assertEndsWith(warning, 'was changed from bar to <CREATED>.'
2912
' The <DELETED> value will be saved.')
2915
class TestQuotingIniFileStore(tests.TestCaseWithTransport):
2917
def get_store(self):
2918
return config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2920
def test_get_quoted_string(self):
2921
store = self.get_store()
2922
store._load_from_string(b'foo= " abc "')
2923
stack = config.Stack([store.get_sections])
2924
self.assertEqual(' abc ', stack.get('foo'))
2926
def test_set_quoted_string(self):
2927
store = self.get_store()
2928
stack = config.Stack([store.get_sections], store)
2929
stack.set('foo', ' a b c ')
2931
self.assertFileEqual(b'foo = " a b c "' +
2932
os.linesep.encode('ascii'), 'foo.conf')
2935
class TestTransportIniFileStore(TestStore):
2937
def test_loading_unknown_file_fails(self):
2938
store = config.TransportIniFileStore(self.get_transport(),
2940
self.assertRaises(errors.NoSuchFile, store.load)
2942
def test_invalid_content(self):
2943
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2944
self.assertEqual(False, store.is_loaded())
2945
exc = self.assertRaises(
2946
config.ParseConfigError, store._load_from_string,
2947
b'this is invalid !')
2948
self.assertEndsWith(exc.filename, 'foo.conf')
2949
# And the load failed
2950
self.assertEqual(False, store.is_loaded())
2952
def test_get_embedded_sections(self):
2953
# A more complicated example (which also shows that section names and
2954
# option names share the same name space...)
2955
# FIXME: This should be fixed by forbidding dicts as values ?
2956
# -- vila 2011-04-05
2957
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2958
store._load_from_string(b'''
2962
foo_in_DEFAULT=foo_DEFAULT
2970
sections = list(store.get_sections())
2971
self.assertLength(4, sections)
2972
# The default section has no name.
2973
# List values are provided as strings and need to be explicitly
2974
# converted by specifying from_unicode=list_from_store at option
2976
self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
2978
self.assertSectionContent(
2979
('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2980
self.assertSectionContent(
2981
('bar', {'foo_in_bar': 'barbar'}), sections[2])
2982
# sub sections are provided as embedded dicts.
2983
self.assertSectionContent(
2984
('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2988
class TestLockableIniFileStore(TestStore):
2990
def test_create_store_in_created_dir(self):
2991
self.assertPathDoesNotExist('dir')
2992
t = self.get_transport('dir/subdir')
2993
store = config.LockableIniFileStore(t, 'foo.conf')
2994
store.get_mutable_section(None).set('foo', 'bar')
2996
self.assertPathExists('dir/subdir')
2999
class TestConcurrentStoreUpdates(TestStore):
3000
"""Test that Stores properly handle conccurent updates.
3002
New Store implementation may fail some of these tests but until such
3003
implementations exist it's hard to properly filter them from the scenarios
3004
applied here. If you encounter such a case, contact the bzr devs.
3007
scenarios = [(key, {'get_stack': builder}) for key, builder
3008
in config.test_stack_builder_registry.iteritems()]
3011
super(TestConcurrentStoreUpdates, self).setUp()
3012
self.stack = self.get_stack(self)
3013
if not isinstance(self.stack, config._CompatibleStack):
3014
raise tests.TestNotApplicable(
3015
'%s is not meant to be compatible with the old config design'
3017
self.stack.set('one', '1')
3018
self.stack.set('two', '2')
3020
self.stack.store.save()
3022
def test_simple_read_access(self):
3023
self.assertEqual('1', self.stack.get('one'))
3025
def test_simple_write_access(self):
3026
self.stack.set('one', 'one')
3027
self.assertEqual('one', self.stack.get('one'))
3029
def test_listen_to_the_last_speaker(self):
3031
c2 = self.get_stack(self)
3032
c1.set('one', 'ONE')
3033
c2.set('two', 'TWO')
3034
self.assertEqual('ONE', c1.get('one'))
3035
self.assertEqual('TWO', c2.get('two'))
3036
# The second update respect the first one
3037
self.assertEqual('ONE', c2.get('one'))
3039
def test_last_speaker_wins(self):
3040
# If the same config is not shared, the same variable modified twice
3041
# can only see a single result.
3043
c2 = self.get_stack(self)
3046
self.assertEqual('c2', c2.get('one'))
3047
# The first modification is still available until another refresh
3049
self.assertEqual('c1', c1.get('one'))
3050
c1.set('two', 'done')
3051
self.assertEqual('c2', c1.get('one'))
3053
def test_writes_are_serialized(self):
3055
c2 = self.get_stack(self)
3057
# We spawn a thread that will pause *during* the config saving.
3058
before_writing = threading.Event()
3059
after_writing = threading.Event()
3060
writing_done = threading.Event()
3061
c1_save_without_locking_orig = c1.store.save_without_locking
3063
def c1_save_without_locking():
3064
before_writing.set()
3065
c1_save_without_locking_orig()
3066
# The lock is held. We wait for the main thread to decide when to
3068
after_writing.wait()
3069
c1.store.save_without_locking = c1_save_without_locking
3074
t1 = threading.Thread(target=c1_set)
3075
# Collect the thread after the test
3076
self.addCleanup(t1.join)
3077
# Be ready to unblock the thread if the test goes wrong
3078
self.addCleanup(after_writing.set)
3080
before_writing.wait()
3081
self.assertRaises(errors.LockContention,
3082
c2.set, 'one', 'c2')
3083
self.assertEqual('c1', c1.get('one'))
3084
# Let the lock be released
3088
self.assertEqual('c2', c2.get('one'))
3090
def test_read_while_writing(self):
3092
# We spawn a thread that will pause *during* the write
3093
ready_to_write = threading.Event()
3094
do_writing = threading.Event()
3095
writing_done = threading.Event()
3096
# We override the _save implementation so we know the store is locked
3097
c1_save_without_locking_orig = c1.store.save_without_locking
3099
def c1_save_without_locking():
3100
ready_to_write.set()
3101
# The lock is held. We wait for the main thread to decide when to
3104
c1_save_without_locking_orig()
3106
c1.store.save_without_locking = c1_save_without_locking
3110
t1 = threading.Thread(target=c1_set)
3111
# Collect the thread after the test
3112
self.addCleanup(t1.join)
3113
# Be ready to unblock the thread if the test goes wrong
3114
self.addCleanup(do_writing.set)
3116
# Ensure the thread is ready to write
3117
ready_to_write.wait()
3118
self.assertEqual('c1', c1.get('one'))
3119
# If we read during the write, we get the old value
3120
c2 = self.get_stack(self)
3121
self.assertEqual('1', c2.get('one'))
3122
# Let the writing occur and ensure it occurred
3125
# Now we get the updated value
3126
c3 = self.get_stack(self)
3127
self.assertEqual('c1', c3.get('one'))
3129
# FIXME: It may be worth looking into removing the lock dir when it's not
3130
# needed anymore and look at possible fallouts for concurrent lockers. This
3131
# will matter if/when we use config files outside of breezy directories
3132
# (.config/breezy or .bzr) -- vila 20110-04-111
3135
class TestSectionMatcher(TestStore):
3137
scenarios = [('location', {'matcher': config.LocationMatcher}),
3138
('id', {'matcher': config.NameMatcher}), ]
3141
super(TestSectionMatcher, self).setUp()
3142
# Any simple store is good enough
3143
self.get_store = config.test_store_builder_registry.get('configobj')
3145
def test_no_matches_for_empty_stores(self):
3146
store = self.get_store(self)
3147
store._load_from_string(b'')
3148
matcher = self.matcher(store, '/bar')
3149
self.assertEqual([], list(matcher.get_sections()))
3151
def test_build_doesnt_load_store(self):
3152
store = self.get_store(self)
3153
self.matcher(store, '/bar')
3154
self.assertFalse(store.is_loaded())
3157
class TestLocationSection(tests.TestCase):
3159
def get_section(self, options, extra_path):
3160
section = config.Section('foo', options)
3161
return config.LocationSection(section, extra_path)
3163
def test_simple_option(self):
3164
section = self.get_section({'foo': 'bar'}, '')
3165
self.assertEqual('bar', section.get('foo'))
3167
def test_option_with_extra_path(self):
3168
section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
3170
self.assertEqual('bar/baz', section.get('foo'))
3172
def test_invalid_policy(self):
3173
section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
3175
# invalid policies are ignored
3176
self.assertEqual('bar', section.get('foo'))
3179
class TestLocationMatcher(TestStore):
3182
super(TestLocationMatcher, self).setUp()
3183
# Any simple store is good enough
3184
self.get_store = config.test_store_builder_registry.get('configobj')
3186
def test_unrelated_section_excluded(self):
3187
store = self.get_store(self)
3188
store._load_from_string(b'''
3196
section=/foo/bar/baz
3200
self.assertEqual(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3202
[section.id for _, section in store.get_sections()])
3203
matcher = config.LocationMatcher(store, '/foo/bar/quux')
3204
sections = [section for _, section in matcher.get_sections()]
3205
self.assertEqual(['/foo/bar', '/foo'],
3206
[section.id for section in sections])
3207
self.assertEqual(['quux', 'bar/quux'],
3208
[section.extra_path for section in sections])
3210
def test_more_specific_sections_first(self):
3211
store = self.get_store(self)
3212
store._load_from_string(b'''
3218
self.assertEqual(['/foo', '/foo/bar'],
3219
[section.id for _, section in store.get_sections()])
3220
matcher = config.LocationMatcher(store, '/foo/bar/baz')
3221
sections = [section for _, section in matcher.get_sections()]
3222
self.assertEqual(['/foo/bar', '/foo'],
3223
[section.id for section in sections])
3224
self.assertEqual(['baz', 'bar/baz'],
3225
[section.extra_path for section in sections])
3227
def test_appendpath_in_no_name_section(self):
3228
# It's a bit weird to allow appendpath in a no-name section, but
3229
# someone may found a use for it
3230
store = self.get_store(self)
3231
store._load_from_string(b'''
3233
foo:policy = appendpath
3235
matcher = config.LocationMatcher(store, 'dir/subdir')
3236
sections = list(matcher.get_sections())
3237
self.assertLength(1, sections)
3238
self.assertEqual('bar/dir/subdir', sections[0][1].get('foo'))
3240
def test_file_urls_are_normalized(self):
3241
store = self.get_store(self)
3242
if sys.platform == 'win32':
3243
expected_url = 'file:///C:/dir/subdir'
3244
expected_location = 'C:/dir/subdir'
3246
expected_url = 'file:///dir/subdir'
3247
expected_location = '/dir/subdir'
3248
matcher = config.LocationMatcher(store, expected_url)
3249
self.assertEqual(expected_location, matcher.location)
3251
def test_branch_name_colo(self):
3252
store = self.get_store(self)
3253
store._load_from_string(dedent("""\
3255
push_location=my{branchname}
3256
""").encode('ascii'))
3257
matcher = config.LocationMatcher(store, 'file:///,branch=example%3c')
3258
self.assertEqual('example<', matcher.branch_name)
3259
((_, section),) = matcher.get_sections()
3260
self.assertEqual('example<', section.locals['branchname'])
3262
def test_branch_name_basename(self):
3263
store = self.get_store(self)
3264
store._load_from_string(dedent("""\
3266
push_location=my{branchname}
3267
""").encode('ascii'))
3268
matcher = config.LocationMatcher(store, 'file:///parent/example%3c')
3269
self.assertEqual('example<', matcher.branch_name)
3270
((_, section),) = matcher.get_sections()
3271
self.assertEqual('example<', section.locals['branchname'])
3274
class TestStartingPathMatcher(TestStore):
3277
super(TestStartingPathMatcher, self).setUp()
3278
# Any simple store is good enough
3279
self.store = config.IniFileStore()
3281
def assertSectionIDs(self, expected, location, content):
3282
self.store._load_from_string(content)
3283
matcher = config.StartingPathMatcher(self.store, location)
3284
sections = list(matcher.get_sections())
3285
self.assertLength(len(expected), sections)
3286
self.assertEqual(expected, [section.id for _, section in sections])
3289
def test_empty(self):
3290
self.assertSectionIDs([], self.get_url(), b'')
3292
def test_url_vs_local_paths(self):
3293
# The matcher location is an url and the section names are local paths
3294
self.assertSectionIDs(['/foo/bar', '/foo'],
3295
'file:///foo/bar/baz', b'''\
3300
def test_local_path_vs_url(self):
3301
# The matcher location is a local path and the section names are urls
3302
self.assertSectionIDs(['file:///foo/bar', 'file:///foo'],
3303
'/foo/bar/baz', b'''\
3308
def test_no_name_section_included_when_present(self):
3309
# Note that other tests will cover the case where the no-name section
3310
# is empty and as such, not included.
3311
sections = self.assertSectionIDs(['/foo/bar', '/foo', None],
3312
'/foo/bar/baz', b'''\
3313
option = defined so the no-name section exists
3317
self.assertEqual(['baz', 'bar/baz', '/foo/bar/baz'],
3318
[s.locals['relpath'] for _, s in sections])
3320
def test_order_reversed(self):
3321
self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', b'''\
3326
def test_unrelated_section_excluded(self):
3327
self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', b'''\
3333
def test_glob_included(self):
3334
sections = self.assertSectionIDs(['/foo/*/baz', '/foo/b*', '/foo'],
3335
'/foo/bar/baz', b'''\
3341
# Note that 'baz' as a relpath for /foo/b* is not fully correct, but
3342
# nothing really is... as far using {relpath} to append it to something
3343
# else, this seems good enough though.
3344
self.assertEqual(['', 'baz', 'bar/baz'],
3345
[s.locals['relpath'] for _, s in sections])
3347
def test_respect_order(self):
3348
self.assertSectionIDs(['/foo', '/foo/b*', '/foo/*/baz'],
3349
'/foo/bar/baz', b'''\
3357
class TestNameMatcher(TestStore):
3360
super(TestNameMatcher, self).setUp()
3361
self.matcher = config.NameMatcher
3362
# Any simple store is good enough
3363
self.get_store = config.test_store_builder_registry.get('configobj')
3365
def get_matching_sections(self, name):
3366
store = self.get_store(self)
3367
store._load_from_string(b'''
3375
matcher = self.matcher(store, name)
3376
return list(matcher.get_sections())
3378
def test_matching(self):
3379
sections = self.get_matching_sections('foo')
3380
self.assertLength(1, sections)
3381
self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3383
def test_not_matching(self):
3384
sections = self.get_matching_sections('baz')
3385
self.assertLength(0, sections)
3388
class TestBaseStackGet(tests.TestCase):
3391
super(TestBaseStackGet, self).setUp()
3392
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3394
def test_get_first_definition(self):
3395
store1 = config.IniFileStore()
3396
store1._load_from_string(b'foo=bar')
3397
store2 = config.IniFileStore()
3398
store2._load_from_string(b'foo=baz')
3399
conf = config.Stack([store1.get_sections, store2.get_sections])
3400
self.assertEqual('bar', conf.get('foo'))
3402
def test_get_with_registered_default_value(self):
3403
config.option_registry.register(config.Option('foo', default='bar'))
3404
conf_stack = config.Stack([])
3405
self.assertEqual('bar', conf_stack.get('foo'))
3407
def test_get_without_registered_default_value(self):
3408
config.option_registry.register(config.Option('foo'))
3409
conf_stack = config.Stack([])
3410
self.assertEqual(None, conf_stack.get('foo'))
3412
def test_get_without_default_value_for_not_registered(self):
3413
conf_stack = config.Stack([])
3414
self.assertEqual(None, conf_stack.get('foo'))
3416
def test_get_for_empty_section_callable(self):
3417
conf_stack = config.Stack([lambda: []])
3418
self.assertEqual(None, conf_stack.get('foo'))
3420
def test_get_for_broken_callable(self):
3421
# Trying to use and invalid callable raises an exception on first use
3422
conf_stack = config.Stack([object])
3423
self.assertRaises(TypeError, conf_stack.get, 'foo')
3426
class TestStackWithSimpleStore(tests.TestCase):
3429
super(TestStackWithSimpleStore, self).setUp()
3430
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3431
self.registry = config.option_registry
3433
def get_conf(self, content=None):
3434
return config.MemoryStack(content)
3436
def test_override_value_from_env(self):
3437
self.overrideEnv('FOO', None)
3438
self.registry.register(
3439
config.Option('foo', default='bar', override_from_env=['FOO']))
3440
self.overrideEnv('FOO', 'quux')
3441
# Env variable provides a default taking over the option one
3442
conf = self.get_conf(b'foo=store')
3443
self.assertEqual('quux', conf.get('foo'))
3445
def test_first_override_value_from_env_wins(self):
3446
self.overrideEnv('NO_VALUE', None)
3447
self.overrideEnv('FOO', None)
3448
self.overrideEnv('BAZ', None)
3449
self.registry.register(
3450
config.Option('foo', default='bar',
3451
override_from_env=['NO_VALUE', 'FOO', 'BAZ']))
3452
self.overrideEnv('FOO', 'foo')
3453
self.overrideEnv('BAZ', 'baz')
3454
# The first env var set wins
3455
conf = self.get_conf(b'foo=store')
3456
self.assertEqual('foo', conf.get('foo'))
3459
class TestMemoryStack(tests.TestCase):
3462
conf = config.MemoryStack(b'foo=bar')
3463
self.assertEqual('bar', conf.get('foo'))
3466
conf = config.MemoryStack(b'foo=bar')
3467
conf.set('foo', 'baz')
3468
self.assertEqual('baz', conf.get('foo'))
3470
def test_no_content(self):
3471
conf = config.MemoryStack()
3472
# No content means no loading
3473
self.assertFalse(conf.store.is_loaded())
3474
self.assertRaises(NotImplementedError, conf.get, 'foo')
3475
# But a content can still be provided
3476
conf.store._load_from_string(b'foo=bar')
3477
self.assertEqual('bar', conf.get('foo'))
3480
class TestStackIterSections(tests.TestCase):
3482
def test_empty_stack(self):
3483
conf = config.Stack([])
3484
sections = list(conf.iter_sections())
3485
self.assertLength(0, sections)
3487
def test_empty_store(self):
3488
store = config.IniFileStore()
3489
store._load_from_string(b'')
3490
conf = config.Stack([store.get_sections])
3491
sections = list(conf.iter_sections())
3492
self.assertLength(0, sections)
3494
def test_simple_store(self):
3495
store = config.IniFileStore()
3496
store._load_from_string(b'foo=bar')
3497
conf = config.Stack([store.get_sections])
3498
tuples = list(conf.iter_sections())
3499
self.assertLength(1, tuples)
3500
(found_store, found_section) = tuples[0]
3501
self.assertIs(store, found_store)
3503
def test_two_stores(self):
3504
store1 = config.IniFileStore()
3505
store1._load_from_string(b'foo=bar')
3506
store2 = config.IniFileStore()
3507
store2._load_from_string(b'bar=qux')
3508
conf = config.Stack([store1.get_sections, store2.get_sections])
3509
tuples = list(conf.iter_sections())
3510
self.assertLength(2, tuples)
3511
self.assertIs(store1, tuples[0][0])
3512
self.assertIs(store2, tuples[1][0])
3515
class TestStackWithTransport(tests.TestCaseWithTransport):
3517
scenarios = [(key, {'get_stack': builder}) for key, builder
3518
in config.test_stack_builder_registry.iteritems()]
3521
class TestConcreteStacks(TestStackWithTransport):
3523
def test_build_stack(self):
3524
# Just a smoke test to help debug builders
3525
self.get_stack(self)
3528
class TestStackGet(TestStackWithTransport):
3531
super(TestStackGet, self).setUp()
3532
self.conf = self.get_stack(self)
3534
def test_get_for_empty_stack(self):
3535
self.assertEqual(None, self.conf.get('foo'))
3537
def test_get_hook(self):
3538
self.conf.set('foo', 'bar')
3543
config.ConfigHooks.install_named_hook('get', hook, None)
3544
self.assertLength(0, calls)
3545
value = self.conf.get('foo')
3546
self.assertEqual('bar', value)
3547
self.assertLength(1, calls)
3548
self.assertEqual((self.conf, 'foo', 'bar'), calls[0])
3551
class TestStackGetWithConverter(tests.TestCase):
3554
super(TestStackGetWithConverter, self).setUp()
3555
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3556
self.registry = config.option_registry
3558
def get_conf(self, content=None):
3559
return config.MemoryStack(content)
3561
def register_bool_option(self, name, default=None, default_from_env=None):
3562
b = config.Option(name, help='A boolean.',
3563
default=default, default_from_env=default_from_env,
3564
from_unicode=config.bool_from_store)
3565
self.registry.register(b)
3567
def test_get_default_bool_None(self):
3568
self.register_bool_option('foo')
3569
conf = self.get_conf(b'')
3570
self.assertEqual(None, conf.get('foo'))
3572
def test_get_default_bool_True(self):
3573
self.register_bool_option('foo', u'True')
3574
conf = self.get_conf(b'')
3575
self.assertEqual(True, conf.get('foo'))
3577
def test_get_default_bool_False(self):
3578
self.register_bool_option('foo', False)
3579
conf = self.get_conf(b'')
3580
self.assertEqual(False, conf.get('foo'))
3582
def test_get_default_bool_False_as_string(self):
3583
self.register_bool_option('foo', u'False')
3584
conf = self.get_conf(b'')
3585
self.assertEqual(False, conf.get('foo'))
3587
def test_get_default_bool_from_env_converted(self):
3588
self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3589
self.overrideEnv('FOO', 'False')
3590
conf = self.get_conf(b'')
3591
self.assertEqual(False, conf.get('foo'))
3593
def test_get_default_bool_when_conversion_fails(self):
3594
self.register_bool_option('foo', default='True')
3595
conf = self.get_conf(b'foo=invalid boolean')
3596
self.assertEqual(True, conf.get('foo'))
3598
def register_integer_option(self, name,
3599
default=None, default_from_env=None):
3600
i = config.Option(name, help='An integer.',
3601
default=default, default_from_env=default_from_env,
3602
from_unicode=config.int_from_store)
3603
self.registry.register(i)
3605
def test_get_default_integer_None(self):
3606
self.register_integer_option('foo')
3607
conf = self.get_conf(b'')
3608
self.assertEqual(None, conf.get('foo'))
3610
def test_get_default_integer(self):
3611
self.register_integer_option('foo', 42)
3612
conf = self.get_conf(b'')
3613
self.assertEqual(42, conf.get('foo'))
3615
def test_get_default_integer_as_string(self):
3616
self.register_integer_option('foo', u'42')
3617
conf = self.get_conf(b'')
3618
self.assertEqual(42, conf.get('foo'))
3620
def test_get_default_integer_from_env(self):
3621
self.register_integer_option('foo', default_from_env=['FOO'])
3622
self.overrideEnv('FOO', '18')
3623
conf = self.get_conf(b'')
3624
self.assertEqual(18, conf.get('foo'))
3626
def test_get_default_integer_when_conversion_fails(self):
3627
self.register_integer_option('foo', default='12')
3628
conf = self.get_conf(b'foo=invalid integer')
3629
self.assertEqual(12, conf.get('foo'))
3631
def register_list_option(self, name, default=None, default_from_env=None):
3632
l = config.ListOption(name, help='A list.', default=default,
3633
default_from_env=default_from_env)
3634
self.registry.register(l)
3636
def test_get_default_list_None(self):
3637
self.register_list_option('foo')
3638
conf = self.get_conf(b'')
3639
self.assertEqual(None, conf.get('foo'))
3641
def test_get_default_list_empty(self):
3642
self.register_list_option('foo', '')
3643
conf = self.get_conf(b'')
3644
self.assertEqual([], conf.get('foo'))
3646
def test_get_default_list_from_env(self):
3647
self.register_list_option('foo', default_from_env=['FOO'])
3648
self.overrideEnv('FOO', '')
3649
conf = self.get_conf(b'')
3650
self.assertEqual([], conf.get('foo'))
3652
def test_get_with_list_converter_no_item(self):
3653
self.register_list_option('foo', None)
3654
conf = self.get_conf(b'foo=,')
3655
self.assertEqual([], conf.get('foo'))
3657
def test_get_with_list_converter_many_items(self):
3658
self.register_list_option('foo', None)
3659
conf = self.get_conf(b'foo=m,o,r,e')
3660
self.assertEqual(['m', 'o', 'r', 'e'], conf.get('foo'))
3662
def test_get_with_list_converter_embedded_spaces_many_items(self):
3663
self.register_list_option('foo', None)
3664
conf = self.get_conf(b'foo=" bar", "baz "')
3665
self.assertEqual([' bar', 'baz '], conf.get('foo'))
3667
def test_get_with_list_converter_stripped_spaces_many_items(self):
3668
self.register_list_option('foo', None)
3669
conf = self.get_conf(b'foo= bar , baz ')
3670
self.assertEqual(['bar', 'baz'], conf.get('foo'))
3673
class TestIterOptionRefs(tests.TestCase):
3674
"""iter_option_refs is a bit unusual, document some cases."""
3676
def assertRefs(self, expected, string):
3677
self.assertEqual(expected, list(config.iter_option_refs(string)))
3679
def test_empty(self):
3680
self.assertRefs([(False, '')], '')
3682
def test_no_refs(self):
3683
self.assertRefs([(False, 'foo bar')], 'foo bar')
3685
def test_single_ref(self):
3686
self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
3688
def test_broken_ref(self):
3689
self.assertRefs([(False, '{foo')], '{foo')
3691
def test_embedded_ref(self):
3692
self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
3695
def test_two_refs(self):
3696
self.assertRefs([(False, ''), (True, '{foo}'),
3697
(False, ''), (True, '{bar}'),
3701
def test_newline_in_refs_are_not_matched(self):
3702
self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
3705
class TestStackExpandOptions(tests.TestCaseWithTransport):
3708
super(TestStackExpandOptions, self).setUp()
3709
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3710
self.registry = config.option_registry
3711
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3712
self.conf = config.Stack([store.get_sections], store)
3714
def assertExpansion(self, expected, string, env=None):
3715
self.assertEqual(expected, self.conf.expand_options(string, env))
3717
def test_no_expansion(self):
3718
self.assertExpansion('foo', 'foo')
3720
def test_expand_default_value(self):
3721
self.conf.store._load_from_string(b'bar=baz')
3722
self.registry.register(config.Option('foo', default=u'{bar}'))
3723
self.assertEqual('baz', self.conf.get('foo', expand=True))
3725
def test_expand_default_from_env(self):
3726
self.conf.store._load_from_string(b'bar=baz')
3727
self.registry.register(config.Option('foo', default_from_env=['FOO']))
3728
self.overrideEnv('FOO', '{bar}')
3729
self.assertEqual('baz', self.conf.get('foo', expand=True))
3731
def test_expand_default_on_failed_conversion(self):
3732
self.conf.store._load_from_string(b'baz=bogus\nbar=42\nfoo={baz}')
3733
self.registry.register(
3734
config.Option('foo', default=u'{bar}',
3735
from_unicode=config.int_from_store))
3736
self.assertEqual(42, self.conf.get('foo', expand=True))
3738
def test_env_adding_options(self):
3739
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3741
def test_env_overriding_options(self):
3742
self.conf.store._load_from_string(b'foo=baz')
3743
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3745
def test_simple_ref(self):
3746
self.conf.store._load_from_string(b'foo=xxx')
3747
self.assertExpansion('xxx', '{foo}')
3749
def test_unknown_ref(self):
3750
self.assertRaises(config.ExpandingUnknownOption,
3751
self.conf.expand_options, '{foo}')
3753
def test_illegal_def_is_ignored(self):
3754
self.assertExpansion('{1,2}', '{1,2}')
3755
self.assertExpansion('{ }', '{ }')
3756
self.assertExpansion('${Foo,f}', '${Foo,f}')
3758
def test_indirect_ref(self):
3759
self.conf.store._load_from_string(b'''
3763
self.assertExpansion('xxx', '{bar}')
3765
def test_embedded_ref(self):
3766
self.conf.store._load_from_string(b'''
3770
self.assertExpansion('xxx', '{{bar}}')
3772
def test_simple_loop(self):
3773
self.conf.store._load_from_string(b'foo={foo}')
3774
self.assertRaises(config.OptionExpansionLoop,
3775
self.conf.expand_options, '{foo}')
3777
def test_indirect_loop(self):
3778
self.conf.store._load_from_string(b'''
3782
e = self.assertRaises(config.OptionExpansionLoop,
3783
self.conf.expand_options, '{foo}')
3784
self.assertEqual('foo->bar->baz', e.refs)
3785
self.assertEqual('{foo}', e.string)
3787
def test_list(self):
3788
self.conf.store._load_from_string(b'''
3792
list={foo},{bar},{baz}
3794
self.registry.register(
3795
config.ListOption('list'))
3796
self.assertEqual(['start', 'middle', 'end'],
3797
self.conf.get('list', expand=True))
3799
def test_cascading_list(self):
3800
self.conf.store._load_from_string(b'''
3806
self.registry.register(config.ListOption('list'))
3807
# Register an intermediate option as a list to ensure no conversion
3808
# happen while expanding. Conversion should only occur for the original
3809
# option ('list' here).
3810
self.registry.register(config.ListOption('baz'))
3811
self.assertEqual(['start', 'middle', 'end'],
3812
self.conf.get('list', expand=True))
3814
def test_pathologically_hidden_list(self):
3815
self.conf.store._load_from_string(b'''
3821
hidden={start}{middle}{end}
3823
# What matters is what the registration says, the conversion happens
3824
# only after all expansions have been performed
3825
self.registry.register(config.ListOption('hidden'))
3826
self.assertEqual(['bin', 'go'],
3827
self.conf.get('hidden', expand=True))
3830
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3833
super(TestStackCrossSectionsExpand, self).setUp()
3835
def get_config(self, location, string):
3838
# Since we don't save the config we won't strictly require to inherit
3839
# from TestCaseInTempDir, but an error occurs so quickly...
3840
c = config.LocationStack(location)
3841
c.store._load_from_string(string)
3844
def test_dont_cross_unrelated_section(self):
3845
c = self.get_config('/another/branch/path', b'''
3850
[/another/branch/path]
3853
self.assertRaises(config.ExpandingUnknownOption,
3854
c.get, 'bar', expand=True)
3856
def test_cross_related_sections(self):
3857
c = self.get_config('/project/branch/path', b'''
3861
[/project/branch/path]
3864
self.assertEqual('quux', c.get('bar', expand=True))
3867
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
3869
def test_cross_global_locations(self):
3870
l_store = config.LocationStore()
3871
l_store._load_from_string(b'''
3877
g_store = config.GlobalStore()
3878
g_store._load_from_string(b'''
3884
stack = config.LocationStack('/branch')
3885
self.assertEqual('glob-bar', stack.get('lbar', expand=True))
3886
self.assertEqual('loc-foo', stack.get('gfoo', expand=True))
3889
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
3891
def test_expand_locals_empty(self):
3892
l_store = config.LocationStore()
3893
l_store._load_from_string(b'''
3894
[/home/user/project]
3899
stack = config.LocationStack('/home/user/project/')
3900
self.assertEqual('', stack.get('base', expand=True))
3901
self.assertEqual('', stack.get('rel', expand=True))
3903
def test_expand_basename_locally(self):
3904
l_store = config.LocationStore()
3905
l_store._load_from_string(b'''
3906
[/home/user/project]
3910
stack = config.LocationStack('/home/user/project/branch')
3911
self.assertEqual('branch', stack.get('bfoo', expand=True))
3913
def test_expand_basename_locally_longer_path(self):
3914
l_store = config.LocationStore()
3915
l_store._load_from_string(b'''
3920
stack = config.LocationStack('/home/user/project/dir/branch')
3921
self.assertEqual('branch', stack.get('bfoo', expand=True))
3923
def test_expand_relpath_locally(self):
3924
l_store = config.LocationStore()
3925
l_store._load_from_string(b'''
3926
[/home/user/project]
3927
lfoo = loc-foo/{relpath}
3930
stack = config.LocationStack('/home/user/project/branch')
3931
self.assertEqual('loc-foo/branch', stack.get('lfoo', expand=True))
3933
def test_expand_relpath_unknonw_in_global(self):
3934
g_store = config.GlobalStore()
3935
g_store._load_from_string(b'''
3940
stack = config.LocationStack('/home/user/project/branch')
3941
self.assertRaises(config.ExpandingUnknownOption,
3942
stack.get, 'gfoo', expand=True)
3944
def test_expand_local_option_locally(self):
3945
l_store = config.LocationStore()
3946
l_store._load_from_string(b'''
3947
[/home/user/project]
3948
lfoo = loc-foo/{relpath}
3952
g_store = config.GlobalStore()
3953
g_store._load_from_string(b'''
3959
stack = config.LocationStack('/home/user/project/branch')
3960
self.assertEqual('glob-bar', stack.get('lbar', expand=True))
3961
self.assertEqual('loc-foo/branch', stack.get('gfoo', expand=True))
3963
def test_locals_dont_leak(self):
3964
"""Make sure we chose the right local in presence of several sections.
3966
l_store = config.LocationStore()
3967
l_store._load_from_string(b'''
3969
lfoo = loc-foo/{relpath}
3970
[/home/user/project]
3971
lfoo = loc-foo/{relpath}
3974
stack = config.LocationStack('/home/user/project/branch')
3975
self.assertEqual('loc-foo/branch', stack.get('lfoo', expand=True))
3976
stack = config.LocationStack('/home/user/bar/baz')
3977
self.assertEqual('loc-foo/bar/baz', stack.get('lfoo', expand=True))
3980
class TestStackSet(TestStackWithTransport):
3982
def test_simple_set(self):
3983
conf = self.get_stack(self)
3984
self.assertEqual(None, conf.get('foo'))
3985
conf.set('foo', 'baz')
3986
# Did we get it back ?
3987
self.assertEqual('baz', conf.get('foo'))
3989
def test_set_creates_a_new_section(self):
3990
conf = self.get_stack(self)
3991
conf.set('foo', 'baz')
3992
self.assertEqual, 'baz', conf.get('foo')
3994
def test_set_hook(self):
3999
config.ConfigHooks.install_named_hook('set', hook, None)
4000
self.assertLength(0, calls)
4001
conf = self.get_stack(self)
4002
conf.set('foo', 'bar')
4003
self.assertLength(1, calls)
4004
self.assertEqual((conf, 'foo', 'bar'), calls[0])
4007
class TestStackRemove(TestStackWithTransport):
4009
def test_remove_existing(self):
4010
conf = self.get_stack(self)
4011
conf.set('foo', 'bar')
4012
self.assertEqual('bar', conf.get('foo'))
4014
# Did we get it back ?
4015
self.assertEqual(None, conf.get('foo'))
4017
def test_remove_unknown(self):
4018
conf = self.get_stack(self)
4019
self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
4021
def test_remove_hook(self):
4026
config.ConfigHooks.install_named_hook('remove', hook, None)
4027
self.assertLength(0, calls)
4028
conf = self.get_stack(self)
4029
conf.set('foo', 'bar')
4031
self.assertLength(1, calls)
4032
self.assertEqual((conf, 'foo'), calls[0])
4035
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
4038
super(TestConfigGetOptions, self).setUp()
4039
create_configs(self)
4041
def test_no_variable(self):
4042
# Using branch should query branch, locations and breezy
4043
self.assertOptions([], self.branch_config)
4045
def test_option_in_breezy(self):
4046
self.breezy_config.set_user_option('file', 'breezy')
4047
self.assertOptions([('file', 'breezy', 'DEFAULT', 'breezy')],
4050
def test_option_in_locations(self):
4051
self.locations_config.set_user_option('file', 'locations')
4053
[('file', 'locations', self.tree.basedir, 'locations')],
4054
self.locations_config)
4056
def test_option_in_branch(self):
4057
self.branch_config.set_user_option('file', 'branch')
4058
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
4061
def test_option_in_breezy_and_branch(self):
4062
self.breezy_config.set_user_option('file', 'breezy')
4063
self.branch_config.set_user_option('file', 'branch')
4064
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
4065
('file', 'breezy', 'DEFAULT', 'breezy'), ],
4068
def test_option_in_branch_and_locations(self):
4069
# Hmm, locations override branch :-/
4070
self.locations_config.set_user_option('file', 'locations')
4071
self.branch_config.set_user_option('file', 'branch')
4073
[('file', 'locations', self.tree.basedir, 'locations'),
4074
('file', 'branch', 'DEFAULT', 'branch'), ],
4077
def test_option_in_breezy_locations_and_branch(self):
4078
self.breezy_config.set_user_option('file', 'breezy')
4079
self.locations_config.set_user_option('file', 'locations')
4080
self.branch_config.set_user_option('file', 'branch')
4082
[('file', 'locations', self.tree.basedir, 'locations'),
4083
('file', 'branch', 'DEFAULT', 'branch'),
4084
('file', 'breezy', 'DEFAULT', 'breezy'), ],
4088
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
4091
super(TestConfigRemoveOption, self).setUp()
4092
create_configs_with_file_option(self)
4094
def test_remove_in_locations(self):
4095
self.locations_config.remove_user_option('file', self.tree.basedir)
4097
[('file', 'branch', 'DEFAULT', 'branch'),
4098
('file', 'breezy', 'DEFAULT', 'breezy'), ],
4101
def test_remove_in_branch(self):
4102
self.branch_config.remove_user_option('file')
4104
[('file', 'locations', self.tree.basedir, 'locations'),
4105
('file', 'breezy', 'DEFAULT', 'breezy'), ],
4108
def test_remove_in_breezy(self):
4109
self.breezy_config.remove_user_option('file')
4111
[('file', 'locations', self.tree.basedir, 'locations'),
4112
('file', 'branch', 'DEFAULT', 'branch'), ],
4116
class TestConfigGetSections(tests.TestCaseWithTransport):
4119
super(TestConfigGetSections, self).setUp()
4120
create_configs(self)
4122
def assertSectionNames(self, expected, conf, name=None):
4123
"""Check which sections are returned for a given config.
4125
If fallback configurations exist their sections can be included.
4127
:param expected: A list of section names.
4129
:param conf: The configuration that will be queried.
4131
:param name: An optional section name that will be passed to
4134
sections = list(conf._get_sections(name))
4135
self.assertLength(len(expected), sections)
4136
self.assertEqual(expected, [n for n, _, _ in sections])
4138
def test_breezy_default_section(self):
4139
self.assertSectionNames(['DEFAULT'], self.breezy_config)
4141
def test_locations_default_section(self):
4142
# No sections are defined in an empty file
4143
self.assertSectionNames([], self.locations_config)
4145
def test_locations_named_section(self):
4146
self.locations_config.set_user_option('file', 'locations')
4147
self.assertSectionNames([self.tree.basedir], self.locations_config)
4149
def test_locations_matching_sections(self):
4150
loc_config = self.locations_config
4151
loc_config.set_user_option('file', 'locations')
4152
# We need to cheat a bit here to create an option in sections above and
4153
# below the 'location' one.
4154
parser = loc_config._get_parser()
4155
# locations.cong deals with '/' ignoring native os.sep
4156
location_names = self.tree.basedir.split('/')
4157
parent = '/'.join(location_names[:-1])
4158
child = '/'.join(location_names + ['child'])
4160
parser[parent]['file'] = 'parent'
4162
parser[child]['file'] = 'child'
4163
self.assertSectionNames([self.tree.basedir, parent], loc_config)
4165
def test_branch_data_default_section(self):
4166
self.assertSectionNames([None],
4167
self.branch_config._get_branch_data_config())
4169
def test_branch_default_sections(self):
4170
# No sections are defined in an empty locations file
4171
self.assertSectionNames([None, 'DEFAULT'],
4173
# Unless we define an option
4174
self.branch_config._get_location_config().set_user_option(
4175
'file', 'locations')
4176
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
4179
def test_breezy_named_section(self):
4180
# We need to cheat as the API doesn't give direct access to sections
4181
# other than DEFAULT.
4182
self.breezy_config.set_alias('breezy', 'bzr')
4183
self.assertSectionNames(['ALIASES'], self.breezy_config, 'ALIASES')
4186
class TestSharedStores(tests.TestCaseInTempDir):
4188
def test_breezy_conf_shared(self):
4189
g1 = config.GlobalStack()
4190
g2 = config.GlobalStack()
4191
# The two stacks share the same store
4192
self.assertIs(g1.store, g2.store)
4195
class TestAuthenticationConfigFilePermissions(tests.TestCaseInTempDir):
4196
"""Test warning for permissions of authentication.conf."""
4199
super(TestAuthenticationConfigFilePermissions, self).setUp()
4200
self.path = osutils.pathjoin(self.test_dir, 'authentication.conf')
4201
with open(self.path, 'wb') as f:
4202
f.write(b"""[broken]
4205
port=port # Error: Not an int
4207
self.overrideAttr(config, 'authentication_config_filename',
4209
osutils.chmod_if_possible(self.path, 0o755)
4211
def test_check_warning(self):
4212
conf = config.AuthenticationConfig()
4213
self.assertEqual(conf._filename, self.path)
4214
self.assertContainsRe(self.get_log(),
4215
'Saved passwords may be accessible by other users.')
4217
def test_check_suppressed_warning(self):
4218
global_config = config.GlobalConfig()
4219
global_config.set_user_option('suppress_warnings',
4220
'insecure_permissions')
4221
conf = config.AuthenticationConfig()
4222
self.assertEqual(conf._filename, self.path)
4223
self.assertNotContainsRe(self.get_log(),
4224
'Saved passwords may be accessible by other users.')
1315
4227
class TestAuthenticationConfigFile(tests.TestCase):
1316
4228
"""Test the authentication.conf file matching"""