1312
1698
self.assertIs(None, bzrdir_config.get_default_stack_on())
1701
class TestOldConfigHooks(tests.TestCaseWithTransport):
1704
super(TestOldConfigHooks, self).setUp()
1705
create_configs_with_file_option(self)
1707
def assertGetHook(self, conf, name, value):
1711
config.OldConfigHooks.install_named_hook('get', hook, None)
1713
config.OldConfigHooks.uninstall_named_hook, 'get', None)
1714
self.assertLength(0, calls)
1715
actual_value = conf.get_user_option(name)
1716
self.assertEqual(value, actual_value)
1717
self.assertLength(1, calls)
1718
self.assertEqual((conf, name, value), calls[0])
1720
def test_get_hook_breezy(self):
1721
self.assertGetHook(self.breezy_config, 'file', 'breezy')
1723
def test_get_hook_locations(self):
1724
self.assertGetHook(self.locations_config, 'file', 'locations')
1726
def test_get_hook_branch(self):
1727
# Since locations masks branch, we define a different option
1728
self.branch_config.set_user_option('file2', 'branch')
1729
self.assertGetHook(self.branch_config, 'file2', 'branch')
1731
def assertSetHook(self, conf, name, value):
1735
config.OldConfigHooks.install_named_hook('set', hook, None)
1737
config.OldConfigHooks.uninstall_named_hook, 'set', None)
1738
self.assertLength(0, calls)
1739
conf.set_user_option(name, value)
1740
self.assertLength(1, calls)
1741
# We can't assert the conf object below as different configs use
1742
# different means to implement set_user_option and we care only about
1744
self.assertEqual((name, value), calls[0][1:])
1746
def test_set_hook_breezy(self):
1747
self.assertSetHook(self.breezy_config, 'foo', 'breezy')
1749
def test_set_hook_locations(self):
1750
self.assertSetHook(self.locations_config, 'foo', 'locations')
1752
def test_set_hook_branch(self):
1753
self.assertSetHook(self.branch_config, 'foo', 'branch')
1755
def assertRemoveHook(self, conf, name, section_name=None):
1759
config.OldConfigHooks.install_named_hook('remove', hook, None)
1761
config.OldConfigHooks.uninstall_named_hook, 'remove', None)
1762
self.assertLength(0, calls)
1763
conf.remove_user_option(name, section_name)
1764
self.assertLength(1, calls)
1765
# We can't assert the conf object below as different configs use
1766
# different means to implement remove_user_option and we care only about
1768
self.assertEqual((name,), calls[0][1:])
1770
def test_remove_hook_breezy(self):
1771
self.assertRemoveHook(self.breezy_config, 'file')
1773
def test_remove_hook_locations(self):
1774
self.assertRemoveHook(self.locations_config, 'file',
1775
self.locations_config.location)
1777
def test_remove_hook_branch(self):
1778
self.assertRemoveHook(self.branch_config, 'file')
1780
def assertLoadHook(self, name, conf_class, *conf_args):
1784
config.OldConfigHooks.install_named_hook('load', hook, None)
1786
config.OldConfigHooks.uninstall_named_hook, 'load', None)
1787
self.assertLength(0, calls)
1789
conf = conf_class(*conf_args)
1790
# Access an option to trigger a load
1791
conf.get_user_option(name)
1792
self.assertLength(1, calls)
1793
# Since we can't assert about conf, we just use the number of calls ;-/
1795
def test_load_hook_breezy(self):
1796
self.assertLoadHook('file', config.GlobalConfig)
1798
def test_load_hook_locations(self):
1799
self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
1801
def test_load_hook_branch(self):
1802
self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
1804
def assertSaveHook(self, conf):
1808
config.OldConfigHooks.install_named_hook('save', hook, None)
1810
config.OldConfigHooks.uninstall_named_hook, 'save', None)
1811
self.assertLength(0, calls)
1812
# Setting an option triggers a save
1813
conf.set_user_option('foo', 'bar')
1814
self.assertLength(1, calls)
1815
# Since we can't assert about conf, we just use the number of calls ;-/
1817
def test_save_hook_breezy(self):
1818
self.assertSaveHook(self.breezy_config)
1820
def test_save_hook_locations(self):
1821
self.assertSaveHook(self.locations_config)
1823
def test_save_hook_branch(self):
1824
self.assertSaveHook(self.branch_config)
1827
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
1828
"""Tests config hooks for remote configs.
1830
No tests for the remove hook as this is not implemented there.
1834
super(TestOldConfigHooksForRemote, self).setUp()
1835
self.transport_server = test_server.SmartTCPServer_for_testing
1836
create_configs_with_file_option(self)
1838
def assertGetHook(self, conf, name, value):
1842
config.OldConfigHooks.install_named_hook('get', hook, None)
1844
config.OldConfigHooks.uninstall_named_hook, 'get', None)
1845
self.assertLength(0, calls)
1846
actual_value = conf.get_option(name)
1847
self.assertEqual(value, actual_value)
1848
self.assertLength(1, calls)
1849
self.assertEqual((conf, name, value), calls[0])
1851
def test_get_hook_remote_branch(self):
1852
remote_branch = branch.Branch.open(self.get_url('tree'))
1853
self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
1855
def test_get_hook_remote_bzrdir(self):
1856
remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1857
conf = remote_bzrdir._get_config()
1858
conf.set_option('remotedir', 'file')
1859
self.assertGetHook(conf, 'file', 'remotedir')
1861
def assertSetHook(self, conf, name, value):
1865
config.OldConfigHooks.install_named_hook('set', hook, None)
1867
config.OldConfigHooks.uninstall_named_hook, 'set', None)
1868
self.assertLength(0, calls)
1869
conf.set_option(value, name)
1870
self.assertLength(1, calls)
1871
# We can't assert the conf object below as different configs use
1872
# different means to implement set_user_option and we care only about
1874
self.assertEqual((name, value), calls[0][1:])
1876
def test_set_hook_remote_branch(self):
1877
remote_branch = branch.Branch.open(self.get_url('tree'))
1878
self.addCleanup(remote_branch.lock_write().unlock)
1879
self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
1881
def test_set_hook_remote_bzrdir(self):
1882
remote_branch = branch.Branch.open(self.get_url('tree'))
1883
self.addCleanup(remote_branch.lock_write().unlock)
1884
remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1885
self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
1887
def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
1891
config.OldConfigHooks.install_named_hook('load', hook, None)
1893
config.OldConfigHooks.uninstall_named_hook, 'load', None)
1894
self.assertLength(0, calls)
1896
conf = conf_class(*conf_args)
1897
# Access an option to trigger a load
1898
conf.get_option(name)
1899
self.assertLength(expected_nb_calls, calls)
1900
# Since we can't assert about conf, we just use the number of calls ;-/
1902
def test_load_hook_remote_branch(self):
1903
remote_branch = branch.Branch.open(self.get_url('tree'))
1904
self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
1906
def test_load_hook_remote_bzrdir(self):
1907
remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1908
# The config file doesn't exist, set an option to force its creation
1909
conf = remote_bzrdir._get_config()
1910
conf.set_option('remotedir', 'file')
1911
# We get one call for the server and one call for the client, this is
1912
# caused by the differences in implementations betwen
1913
# SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
1914
# SmartServerBranchGetConfigFile (in smart/branch.py)
1915
self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
1917
def assertSaveHook(self, conf):
1921
config.OldConfigHooks.install_named_hook('save', hook, None)
1923
config.OldConfigHooks.uninstall_named_hook, 'save', None)
1924
self.assertLength(0, calls)
1925
# Setting an option triggers a save
1926
conf.set_option('foo', 'bar')
1927
self.assertLength(1, calls)
1928
# Since we can't assert about conf, we just use the number of calls ;-/
1930
def test_save_hook_remote_branch(self):
1931
remote_branch = branch.Branch.open(self.get_url('tree'))
1932
self.addCleanup(remote_branch.lock_write().unlock)
1933
self.assertSaveHook(remote_branch._get_config())
1935
def test_save_hook_remote_bzrdir(self):
1936
remote_branch = branch.Branch.open(self.get_url('tree'))
1937
self.addCleanup(remote_branch.lock_write().unlock)
1938
remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1939
self.assertSaveHook(remote_bzrdir._get_config())
1942
class TestOptionNames(tests.TestCase):
1944
def is_valid(self, name):
1945
return config._option_ref_re.match('{%s}' % name) is not None
1947
def test_valid_names(self):
1948
self.assertTrue(self.is_valid('foo'))
1949
self.assertTrue(self.is_valid('foo.bar'))
1950
self.assertTrue(self.is_valid('f1'))
1951
self.assertTrue(self.is_valid('_'))
1952
self.assertTrue(self.is_valid('__bar__'))
1953
self.assertTrue(self.is_valid('a_'))
1954
self.assertTrue(self.is_valid('a1'))
1955
# Don't break bzr-svn for no good reason
1956
self.assertTrue(self.is_valid('guessed-layout'))
1958
def test_invalid_names(self):
1959
self.assertFalse(self.is_valid(' foo'))
1960
self.assertFalse(self.is_valid('foo '))
1961
self.assertFalse(self.is_valid('1'))
1962
self.assertFalse(self.is_valid('1,2'))
1963
self.assertFalse(self.is_valid('foo$'))
1964
self.assertFalse(self.is_valid('!foo'))
1965
self.assertFalse(self.is_valid('foo.'))
1966
self.assertFalse(self.is_valid('foo..bar'))
1967
self.assertFalse(self.is_valid('{}'))
1968
self.assertFalse(self.is_valid('{a}'))
1969
self.assertFalse(self.is_valid('a\n'))
1970
self.assertFalse(self.is_valid('-'))
1971
self.assertFalse(self.is_valid('-a'))
1972
self.assertFalse(self.is_valid('a-'))
1973
self.assertFalse(self.is_valid('a--a'))
1975
def assertSingleGroup(self, reference):
1976
# the regexp is used with split and as such should match the reference
1977
# *only*, if more groups needs to be defined, (?:...) should be used.
1978
m = config._option_ref_re.match('{a}')
1979
self.assertLength(1, m.groups())
1981
def test_valid_references(self):
1982
self.assertSingleGroup('{a}')
1983
self.assertSingleGroup('{{a}}')
1986
class TestOption(tests.TestCase):
1988
def test_default_value(self):
1989
opt = config.Option('foo', default='bar')
1990
self.assertEqual('bar', opt.get_default())
1992
def test_callable_default_value(self):
1993
def bar_as_unicode():
1995
opt = config.Option('foo', default=bar_as_unicode)
1996
self.assertEqual('bar', opt.get_default())
1998
def test_default_value_from_env(self):
1999
opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2000
self.overrideEnv('FOO', 'quux')
2001
# Env variable provides a default taking over the option one
2002
self.assertEqual('quux', opt.get_default())
2004
def test_first_default_value_from_env_wins(self):
2005
opt = config.Option('foo', default='bar',
2006
default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2007
self.overrideEnv('FOO', 'foo')
2008
self.overrideEnv('BAZ', 'baz')
2009
# The first env var set wins
2010
self.assertEqual('foo', opt.get_default())
2012
def test_not_supported_list_default_value(self):
2013
self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2015
def test_not_supported_object_default_value(self):
2016
self.assertRaises(AssertionError, config.Option, 'foo',
2019
def test_not_supported_callable_default_value_not_unicode(self):
2020
def bar_not_unicode():
2022
opt = config.Option('foo', default=bar_not_unicode)
2023
self.assertRaises(AssertionError, opt.get_default)
2025
def test_get_help_topic(self):
2026
opt = config.Option('foo')
2027
self.assertEqual('foo', opt.get_help_topic())
2030
class TestOptionConverter(tests.TestCase):
2032
def assertConverted(self, expected, opt, value):
2033
self.assertEqual(expected, opt.convert_from_unicode(None, value))
2035
def assertCallsWarning(self, opt, value):
2039
warnings.append(args[0] % args[1:])
2040
self.overrideAttr(trace, 'warning', warning)
2041
self.assertEqual(None, opt.convert_from_unicode(None, value))
2042
self.assertLength(1, warnings)
2044
'Value "%s" is not valid for "%s"' % (value, opt.name),
2047
def assertCallsError(self, opt, value):
2048
self.assertRaises(config.ConfigOptionValueError,
2049
opt.convert_from_unicode, None, value)
2051
def assertConvertInvalid(self, opt, invalid_value):
2053
self.assertEqual(None, opt.convert_from_unicode(None, invalid_value))
2054
opt.invalid = 'warning'
2055
self.assertCallsWarning(opt, invalid_value)
2056
opt.invalid = 'error'
2057
self.assertCallsError(opt, invalid_value)
2060
class TestOptionWithBooleanConverter(TestOptionConverter):
2062
def get_option(self):
2063
return config.Option('foo', help='A boolean.',
2064
from_unicode=config.bool_from_store)
2066
def test_convert_invalid(self):
2067
opt = self.get_option()
2068
# A string that is not recognized as a boolean
2069
self.assertConvertInvalid(opt, u'invalid-boolean')
2070
# A list of strings is never recognized as a boolean
2071
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2073
def test_convert_valid(self):
2074
opt = self.get_option()
2075
self.assertConverted(True, opt, u'True')
2076
self.assertConverted(True, opt, u'1')
2077
self.assertConverted(False, opt, u'False')
2080
class TestOptionWithIntegerConverter(TestOptionConverter):
2082
def get_option(self):
2083
return config.Option('foo', help='An integer.',
2084
from_unicode=config.int_from_store)
2086
def test_convert_invalid(self):
2087
opt = self.get_option()
2088
# A string that is not recognized as an integer
2089
self.assertConvertInvalid(opt, u'forty-two')
2090
# A list of strings is never recognized as an integer
2091
self.assertConvertInvalid(opt, [u'a', u'list'])
2093
def test_convert_valid(self):
2094
opt = self.get_option()
2095
self.assertConverted(16, opt, u'16')
2098
class TestOptionWithSIUnitConverter(TestOptionConverter):
2100
def get_option(self):
2101
return config.Option('foo', help='An integer in SI units.',
2102
from_unicode=config.int_SI_from_store)
2104
def test_convert_invalid(self):
2105
opt = self.get_option()
2106
self.assertConvertInvalid(opt, u'not-a-unit')
2107
self.assertConvertInvalid(opt, u'Gb') # Forgot the value
2108
self.assertConvertInvalid(opt, u'1b') # Forgot the unit
2109
self.assertConvertInvalid(opt, u'1GG')
2110
self.assertConvertInvalid(opt, u'1Mbb')
2111
self.assertConvertInvalid(opt, u'1MM')
2113
def test_convert_valid(self):
2114
opt = self.get_option()
2115
self.assertConverted(int(5e3), opt, u'5kb')
2116
self.assertConverted(int(5e6), opt, u'5M')
2117
self.assertConverted(int(5e6), opt, u'5MB')
2118
self.assertConverted(int(5e9), opt, u'5g')
2119
self.assertConverted(int(5e9), opt, u'5gB')
2120
self.assertConverted(100, opt, u'100')
2123
class TestListOption(TestOptionConverter):
2125
def get_option(self):
2126
return config.ListOption('foo', help='A list.')
2128
def test_convert_invalid(self):
2129
opt = self.get_option()
2130
# We don't even try to convert a list into a list, we only expect
2132
self.assertConvertInvalid(opt, [1])
2133
# No string is invalid as all forms can be converted to a list
2135
def test_convert_valid(self):
2136
opt = self.get_option()
2137
# An empty string is an empty list
2138
self.assertConverted([], opt, '') # Using a bare str() just in case
2139
self.assertConverted([], opt, u'')
2141
self.assertConverted([u'True'], opt, u'True')
2143
self.assertConverted([u'42'], opt, u'42')
2145
self.assertConverted([u'bar'], opt, u'bar')
2148
class TestRegistryOption(TestOptionConverter):
2150
def get_option(self, registry):
2151
return config.RegistryOption('foo', registry,
2152
help='A registry option.')
2154
def test_convert_invalid(self):
2155
registry = _mod_registry.Registry()
2156
opt = self.get_option(registry)
2157
self.assertConvertInvalid(opt, [1])
2158
self.assertConvertInvalid(opt, u"notregistered")
2160
def test_convert_valid(self):
2161
registry = _mod_registry.Registry()
2162
registry.register("someval", 1234)
2163
opt = self.get_option(registry)
2164
# Using a bare str() just in case
2165
self.assertConverted(1234, opt, "someval")
2166
self.assertConverted(1234, opt, u'someval')
2167
self.assertConverted(None, opt, None)
2169
def test_help(self):
2170
registry = _mod_registry.Registry()
2171
registry.register("someval", 1234, help="some option")
2172
registry.register("dunno", 1234, help="some other option")
2173
opt = self.get_option(registry)
2175
'A registry option.\n'
2177
'The following values are supported:\n'
2178
' dunno - some other option\n'
2179
' someval - some option\n',
2182
def test_get_help_text(self):
2183
registry = _mod_registry.Registry()
2184
registry.register("someval", 1234, help="some option")
2185
registry.register("dunno", 1234, help="some other option")
2186
opt = self.get_option(registry)
2188
'A registry option.\n'
2190
'The following values are supported:\n'
2191
' dunno - some other option\n'
2192
' someval - some option\n',
2193
opt.get_help_text())
2196
class TestOptionRegistry(tests.TestCase):
2199
super(TestOptionRegistry, self).setUp()
2200
# Always start with an empty registry
2201
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2202
self.registry = config.option_registry
2204
def test_register(self):
2205
opt = config.Option('foo')
2206
self.registry.register(opt)
2207
self.assertIs(opt, self.registry.get('foo'))
2209
def test_registered_help(self):
2210
opt = config.Option('foo', help='A simple option')
2211
self.registry.register(opt)
2212
self.assertEqual('A simple option', self.registry.get_help('foo'))
2214
def test_dont_register_illegal_name(self):
2215
self.assertRaises(config.IllegalOptionName,
2216
self.registry.register, config.Option(' foo'))
2217
self.assertRaises(config.IllegalOptionName,
2218
self.registry.register, config.Option('bar,'))
2220
lazy_option = config.Option('lazy_foo', help='Lazy help')
2222
def test_register_lazy(self):
2223
self.registry.register_lazy('lazy_foo', self.__module__,
2224
'TestOptionRegistry.lazy_option')
2225
self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2227
def test_registered_lazy_help(self):
2228
self.registry.register_lazy('lazy_foo', self.__module__,
2229
'TestOptionRegistry.lazy_option')
2230
self.assertEqual('Lazy help', self.registry.get_help('lazy_foo'))
2232
def test_dont_lazy_register_illegal_name(self):
2233
# This is where the root cause of http://pad.lv/1235099 is better
2234
# understood: 'register_lazy' doc string mentions that key should match
2235
# the option name which indirectly requires that the option name is a
2236
# valid python identifier. We violate that rule here (using a key that
2237
# doesn't match the option name) to test the option name checking.
2238
self.assertRaises(config.IllegalOptionName,
2239
self.registry.register_lazy, ' foo', self.__module__,
2240
'TestOptionRegistry.lazy_option')
2241
self.assertRaises(config.IllegalOptionName,
2242
self.registry.register_lazy, '1,2', self.__module__,
2243
'TestOptionRegistry.lazy_option')
2246
class TestRegisteredOptions(tests.TestCase):
2247
"""All registered options should verify some constraints."""
2249
scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2250
in config.option_registry.iteritems()]
2253
super(TestRegisteredOptions, self).setUp()
2254
self.registry = config.option_registry
2256
def test_proper_name(self):
2257
# An option should be registered under its own name, this can't be
2258
# checked at registration time for the lazy ones.
2259
self.assertEqual(self.option_name, self.option.name)
2261
def test_help_is_set(self):
2262
option_help = self.registry.get_help(self.option_name)
2263
# Come on, think about the user, he really wants to know what the
2265
self.assertIsNot(None, option_help)
2266
self.assertNotEqual('', option_help)
2269
class TestSection(tests.TestCase):
2271
# FIXME: Parametrize so that all sections produced by Stores run these
2272
# tests -- vila 2011-04-01
2274
def test_get_a_value(self):
2275
a_dict = dict(foo='bar')
2276
section = config.Section('myID', a_dict)
2277
self.assertEqual('bar', section.get('foo'))
2279
def test_get_unknown_option(self):
2281
section = config.Section(None, a_dict)
2282
self.assertEqual('out of thin air',
2283
section.get('foo', 'out of thin air'))
2285
def test_options_is_shared(self):
2287
section = config.Section(None, a_dict)
2288
self.assertIs(a_dict, section.options)
2291
class TestMutableSection(tests.TestCase):
2293
scenarios = [('mutable',
2295
lambda opts: config.MutableSection('myID', opts)},),
2299
a_dict = dict(foo='bar')
2300
section = self.get_section(a_dict)
2301
section.set('foo', 'new_value')
2302
self.assertEqual('new_value', section.get('foo'))
2303
# The change appears in the shared section
2304
self.assertEqual('new_value', a_dict.get('foo'))
2305
# We keep track of the change
2306
self.assertTrue('foo' in section.orig)
2307
self.assertEqual('bar', section.orig.get('foo'))
2309
def test_set_preserve_original_once(self):
2310
a_dict = dict(foo='bar')
2311
section = self.get_section(a_dict)
2312
section.set('foo', 'first_value')
2313
section.set('foo', 'second_value')
2314
# We keep track of the original value
2315
self.assertTrue('foo' in section.orig)
2316
self.assertEqual('bar', section.orig.get('foo'))
2318
def test_remove(self):
2319
a_dict = dict(foo='bar')
2320
section = self.get_section(a_dict)
2321
section.remove('foo')
2322
# We get None for unknown options via the default value
2323
self.assertEqual(None, section.get('foo'))
2324
# Or we just get the default value
2325
self.assertEqual('unknown', section.get('foo', 'unknown'))
2326
self.assertFalse('foo' in section.options)
2327
# We keep track of the deletion
2328
self.assertTrue('foo' in section.orig)
2329
self.assertEqual('bar', section.orig.get('foo'))
2331
def test_remove_new_option(self):
2333
section = self.get_section(a_dict)
2334
section.set('foo', 'bar')
2335
section.remove('foo')
2336
self.assertFalse('foo' in section.options)
2337
# The option didn't exist initially so it we need to keep track of it
2338
# with a special value
2339
self.assertTrue('foo' in section.orig)
2340
self.assertEqual(config._NewlyCreatedOption, section.orig['foo'])
2343
class TestCommandLineStore(tests.TestCase):
2346
super(TestCommandLineStore, self).setUp()
2347
self.store = config.CommandLineStore()
2348
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2350
def get_section(self):
2351
"""Get the unique section for the command line overrides."""
2352
sections = list(self.store.get_sections())
2353
self.assertLength(1, sections)
2354
store, section = sections[0]
2355
self.assertEqual(self.store, store)
2358
def test_no_override(self):
2359
self.store._from_cmdline([])
2360
section = self.get_section()
2361
self.assertLength(0, list(section.iter_option_names()))
2363
def test_simple_override(self):
2364
self.store._from_cmdline(['a=b'])
2365
section = self.get_section()
2366
self.assertEqual('b', section.get('a'))
2368
def test_list_override(self):
2369
opt = config.ListOption('l')
2370
config.option_registry.register(opt)
2371
self.store._from_cmdline(['l=1,2,3'])
2372
val = self.get_section().get('l')
2373
self.assertEqual('1,2,3', val)
2374
# Reminder: lists should be registered as such explicitely, otherwise
2375
# the conversion needs to be done afterwards.
2376
self.assertEqual(['1', '2', '3'],
2377
opt.convert_from_unicode(self.store, val))
2379
def test_multiple_overrides(self):
2380
self.store._from_cmdline(['a=b', 'x=y'])
2381
section = self.get_section()
2382
self.assertEqual('b', section.get('a'))
2383
self.assertEqual('y', section.get('x'))
2385
def test_wrong_syntax(self):
2386
self.assertRaises(errors.BzrCommandError,
2387
self.store._from_cmdline, ['a=b', 'c'])
2389
class TestStoreMinimalAPI(tests.TestCaseWithTransport):
2391
scenarios = [(key, {'get_store': builder}) for key, builder
2392
in config.test_store_builder_registry.iteritems()] + [
2393
('cmdline', {'get_store': lambda test: config.CommandLineStore()})]
2396
store = self.get_store(self)
2397
if isinstance(store, config.TransportIniFileStore):
2398
raise tests.TestNotApplicable(
2399
"%s is not a concrete Store implementation"
2400
" so it doesn't need an id" % (store.__class__.__name__,))
2401
self.assertIsNot(None, store.id)
2404
class TestStore(tests.TestCaseWithTransport):
2406
def assertSectionContent(self, expected, store_and_section):
2407
"""Assert that some options have the proper values in a section."""
2408
_, section = store_and_section
2409
expected_name, expected_options = expected
2410
self.assertEqual(expected_name, section.id)
2413
dict([(k, section.get(k)) for k in expected_options.keys()]))
2416
class TestReadonlyStore(TestStore):
2418
scenarios = [(key, {'get_store': builder}) for key, builder
2419
in config.test_store_builder_registry.iteritems()]
2421
def test_building_delays_load(self):
2422
store = self.get_store(self)
2423
self.assertEqual(False, store.is_loaded())
2424
store._load_from_string('')
2425
self.assertEqual(True, store.is_loaded())
2427
def test_get_no_sections_for_empty(self):
2428
store = self.get_store(self)
2429
store._load_from_string('')
2430
self.assertEqual([], list(store.get_sections()))
2432
def test_get_default_section(self):
2433
store = self.get_store(self)
2434
store._load_from_string('foo=bar')
2435
sections = list(store.get_sections())
2436
self.assertLength(1, sections)
2437
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2439
def test_get_named_section(self):
2440
store = self.get_store(self)
2441
store._load_from_string('[baz]\nfoo=bar')
2442
sections = list(store.get_sections())
2443
self.assertLength(1, sections)
2444
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2446
def test_load_from_string_fails_for_non_empty_store(self):
2447
store = self.get_store(self)
2448
store._load_from_string('foo=bar')
2449
self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2452
class TestStoreQuoting(TestStore):
2454
scenarios = [(key, {'get_store': builder}) for key, builder
2455
in config.test_store_builder_registry.iteritems()]
2458
super(TestStoreQuoting, self).setUp()
2459
self.store = self.get_store(self)
2460
# We need a loaded store but any content will do
2461
self.store._load_from_string('')
2463
def assertIdempotent(self, s):
2464
"""Assert that quoting an unquoted string is a no-op and vice-versa.
2466
What matters here is that option values, as they appear in a store, can
2467
be safely round-tripped out of the store and back.
2469
:param s: A string, quoted if required.
2471
self.assertEqual(s, self.store.quote(self.store.unquote(s)))
2472
self.assertEqual(s, self.store.unquote(self.store.quote(s)))
2474
def test_empty_string(self):
2475
if isinstance(self.store, config.IniFileStore):
2476
# configobj._quote doesn't handle empty values
2477
self.assertRaises(AssertionError,
2478
self.assertIdempotent, '')
2480
self.assertIdempotent('')
2481
# But quoted empty strings are ok
2482
self.assertIdempotent('""')
2484
def test_embedded_spaces(self):
2485
self.assertIdempotent('" a b c "')
2487
def test_embedded_commas(self):
2488
self.assertIdempotent('" a , b c "')
2490
def test_simple_comma(self):
2491
if isinstance(self.store, config.IniFileStore):
2492
# configobj requires that lists are special-cased
2493
self.assertRaises(AssertionError,
2494
self.assertIdempotent, ',')
2496
self.assertIdempotent(',')
2497
# When a single comma is required, quoting is also required
2498
self.assertIdempotent('","')
2500
def test_list(self):
2501
if isinstance(self.store, config.IniFileStore):
2502
# configobj requires that lists are special-cased
2503
self.assertRaises(AssertionError,
2504
self.assertIdempotent, 'a,b')
2506
self.assertIdempotent('a,b')
2509
class TestDictFromStore(tests.TestCase):
2511
def test_unquote_not_string(self):
2512
conf = config.MemoryStack('x=2\n[a_section]\na=1\n')
2513
value = conf.get('a_section')
2514
# Urgh, despite 'conf' asking for the no-name section, we get the
2515
# content of another section as a dict o_O
2516
self.assertEqual({'a': '1'}, value)
2517
unquoted = conf.store.unquote(value)
2518
# Which cannot be unquoted but shouldn't crash either (the use cases
2519
# are getting the value or displaying it. In the later case, '%s' will
2521
self.assertEqual({'a': '1'}, unquoted)
2522
self.assertEqual("{u'a': u'1'}", '%s' % (unquoted,))
2525
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2526
"""Simulate loading a config store with content of various encodings.
2528
All files produced by bzr are in utf8 content.
2530
Users may modify them manually and end up with a file that can't be
2531
loaded. We need to issue proper error messages in this case.
2534
invalid_utf8_char = '\xff'
2536
def test_load_utf8(self):
2537
"""Ensure we can load an utf8-encoded file."""
2538
t = self.get_transport()
2539
# From http://pad.lv/799212
2540
unicode_user = u'b\N{Euro Sign}ar'
2541
unicode_content = u'user=%s' % (unicode_user,)
2542
utf8_content = unicode_content.encode('utf8')
2543
# Store the raw content in the config file
2544
t.put_bytes('foo.conf', utf8_content)
2545
store = config.TransportIniFileStore(t, 'foo.conf')
2547
stack = config.Stack([store.get_sections], store)
2548
self.assertEqual(unicode_user, stack.get('user'))
2550
def test_load_non_ascii(self):
2551
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2552
t = self.get_transport()
2553
t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2554
store = config.TransportIniFileStore(t, 'foo.conf')
2555
self.assertRaises(config.ConfigContentError, store.load)
2557
def test_load_erroneous_content(self):
2558
"""Ensure we display a proper error on content that can't be parsed."""
2559
t = self.get_transport()
2560
t.put_bytes('foo.conf', '[open_section\n')
2561
store = config.TransportIniFileStore(t, 'foo.conf')
2562
self.assertRaises(config.ParseConfigError, store.load)
2564
def test_load_permission_denied(self):
2565
"""Ensure we get warned when trying to load an inaccessible file."""
2568
warnings.append(args[0] % args[1:])
2569
self.overrideAttr(trace, 'warning', warning)
2571
t = self.get_transport()
2573
def get_bytes(relpath):
2574
raise errors.PermissionDenied(relpath, "")
2575
t.get_bytes = get_bytes
2576
store = config.TransportIniFileStore(t, 'foo.conf')
2577
self.assertRaises(errors.PermissionDenied, store.load)
2580
[u'Permission denied while trying to load configuration store %s.'
2581
% store.external_url()])
2584
class TestIniConfigContent(tests.TestCaseWithTransport):
2585
"""Simulate loading a IniBasedConfig with content of various encodings.
2587
All files produced by bzr are in utf8 content.
2589
Users may modify them manually and end up with a file that can't be
2590
loaded. We need to issue proper error messages in this case.
2593
invalid_utf8_char = '\xff'
2595
def test_load_utf8(self):
2596
"""Ensure we can load an utf8-encoded file."""
2597
# From http://pad.lv/799212
2598
unicode_user = u'b\N{Euro Sign}ar'
2599
unicode_content = u'user=%s' % (unicode_user,)
2600
utf8_content = unicode_content.encode('utf8')
2601
# Store the raw content in the config file
2602
with open('foo.conf', 'wb') as f:
2603
f.write(utf8_content)
2604
conf = config.IniBasedConfig(file_name='foo.conf')
2605
self.assertEqual(unicode_user, conf.get_user_option('user'))
2607
def test_load_badly_encoded_content(self):
2608
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2609
with open('foo.conf', 'wb') as f:
2610
f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2611
conf = config.IniBasedConfig(file_name='foo.conf')
2612
self.assertRaises(config.ConfigContentError, conf._get_parser)
2614
def test_load_erroneous_content(self):
2615
"""Ensure we display a proper error on content that can't be parsed."""
2616
with open('foo.conf', 'wb') as f:
2617
f.write('[open_section\n')
2618
conf = config.IniBasedConfig(file_name='foo.conf')
2619
self.assertRaises(config.ParseConfigError, conf._get_parser)
2622
class TestMutableStore(TestStore):
2624
scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2625
in config.test_store_builder_registry.iteritems()]
2628
super(TestMutableStore, self).setUp()
2629
self.transport = self.get_transport()
2631
def has_store(self, store):
2632
store_basename = urlutils.relative_url(self.transport.external_url(),
2633
store.external_url())
2634
return self.transport.has(store_basename)
2636
def test_save_empty_creates_no_file(self):
2637
# FIXME: There should be a better way than relying on the test
2638
# parametrization to identify branch.conf -- vila 2011-0526
2639
if self.store_id in ('branch', 'remote_branch'):
2640
raise tests.TestNotApplicable(
2641
'branch.conf is *always* created when a branch is initialized')
2642
store = self.get_store(self)
2644
self.assertEqual(False, self.has_store(store))
2646
def test_mutable_section_shared(self):
2647
store = self.get_store(self)
2648
store._load_from_string('foo=bar\n')
2649
# FIXME: There should be a better way than relying on the test
2650
# parametrization to identify branch.conf -- vila 2011-0526
2651
if self.store_id in ('branch', 'remote_branch'):
2652
# branch stores requires write locked branches
2653
self.addCleanup(store.branch.lock_write().unlock)
2654
section1 = store.get_mutable_section(None)
2655
section2 = store.get_mutable_section(None)
2656
# If we get different sections, different callers won't share the
2658
self.assertIs(section1, section2)
2660
def test_save_emptied_succeeds(self):
2661
store = self.get_store(self)
2662
store._load_from_string('foo=bar\n')
2663
# FIXME: There should be a better way than relying on the test
2664
# parametrization to identify branch.conf -- vila 2011-0526
2665
if self.store_id in ('branch', 'remote_branch'):
2666
# branch stores requires write locked branches
2667
self.addCleanup(store.branch.lock_write().unlock)
2668
section = store.get_mutable_section(None)
2669
section.remove('foo')
2671
self.assertEqual(True, self.has_store(store))
2672
modified_store = self.get_store(self)
2673
sections = list(modified_store.get_sections())
2674
self.assertLength(0, sections)
2676
def test_save_with_content_succeeds(self):
2677
# FIXME: There should be a better way than relying on the test
2678
# parametrization to identify branch.conf -- vila 2011-0526
2679
if self.store_id in ('branch', 'remote_branch'):
2680
raise tests.TestNotApplicable(
2681
'branch.conf is *always* created when a branch is initialized')
2682
store = self.get_store(self)
2683
store._load_from_string('foo=bar\n')
2684
self.assertEqual(False, self.has_store(store))
2686
self.assertEqual(True, self.has_store(store))
2687
modified_store = self.get_store(self)
2688
sections = list(modified_store.get_sections())
2689
self.assertLength(1, sections)
2690
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2692
def test_set_option_in_empty_store(self):
2693
store = self.get_store(self)
2694
# FIXME: There should be a better way than relying on the test
2695
# parametrization to identify branch.conf -- vila 2011-0526
2696
if self.store_id in ('branch', 'remote_branch'):
2697
# branch stores requires write locked branches
2698
self.addCleanup(store.branch.lock_write().unlock)
2699
section = store.get_mutable_section(None)
2700
section.set('foo', 'bar')
2702
modified_store = self.get_store(self)
2703
sections = list(modified_store.get_sections())
2704
self.assertLength(1, sections)
2705
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2707
def test_set_option_in_default_section(self):
2708
store = self.get_store(self)
2709
store._load_from_string('')
2710
# FIXME: There should be a better way than relying on the test
2711
# parametrization to identify branch.conf -- vila 2011-0526
2712
if self.store_id in ('branch', 'remote_branch'):
2713
# branch stores requires write locked branches
2714
self.addCleanup(store.branch.lock_write().unlock)
2715
section = store.get_mutable_section(None)
2716
section.set('foo', 'bar')
2718
modified_store = self.get_store(self)
2719
sections = list(modified_store.get_sections())
2720
self.assertLength(1, sections)
2721
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2723
def test_set_option_in_named_section(self):
2724
store = self.get_store(self)
2725
store._load_from_string('')
2726
# FIXME: There should be a better way than relying on the test
2727
# parametrization to identify branch.conf -- vila 2011-0526
2728
if self.store_id in ('branch', 'remote_branch'):
2729
# branch stores requires write locked branches
2730
self.addCleanup(store.branch.lock_write().unlock)
2731
section = store.get_mutable_section('baz')
2732
section.set('foo', 'bar')
2734
modified_store = self.get_store(self)
2735
sections = list(modified_store.get_sections())
2736
self.assertLength(1, sections)
2737
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2739
def test_load_hook(self):
2740
# First, we need to ensure that the store exists
2741
store = self.get_store(self)
2742
# FIXME: There should be a better way than relying on the test
2743
# parametrization to identify branch.conf -- vila 2011-0526
2744
if self.store_id in ('branch', 'remote_branch'):
2745
# branch stores requires write locked branches
2746
self.addCleanup(store.branch.lock_write().unlock)
2747
section = store.get_mutable_section('baz')
2748
section.set('foo', 'bar')
2750
# Now we can try to load it
2751
store = self.get_store(self)
2755
config.ConfigHooks.install_named_hook('load', hook, None)
2756
self.assertLength(0, calls)
2758
self.assertLength(1, calls)
2759
self.assertEqual((store,), calls[0])
2761
def test_save_hook(self):
2765
config.ConfigHooks.install_named_hook('save', hook, None)
2766
self.assertLength(0, calls)
2767
store = self.get_store(self)
2768
# FIXME: There should be a better way than relying on the test
2769
# parametrization to identify branch.conf -- vila 2011-0526
2770
if self.store_id in ('branch', 'remote_branch'):
2771
# branch stores requires write locked branches
2772
self.addCleanup(store.branch.lock_write().unlock)
2773
section = store.get_mutable_section('baz')
2774
section.set('foo', 'bar')
2776
self.assertLength(1, calls)
2777
self.assertEqual((store,), calls[0])
2779
def test_set_mark_dirty(self):
2780
stack = config.MemoryStack('')
2781
self.assertLength(0, stack.store.dirty_sections)
2782
stack.set('foo', 'baz')
2783
self.assertLength(1, stack.store.dirty_sections)
2784
self.assertTrue(stack.store._need_saving())
2786
def test_remove_mark_dirty(self):
2787
stack = config.MemoryStack('foo=bar')
2788
self.assertLength(0, stack.store.dirty_sections)
2790
self.assertLength(1, stack.store.dirty_sections)
2791
self.assertTrue(stack.store._need_saving())
2794
class TestStoreSaveChanges(tests.TestCaseWithTransport):
2795
"""Tests that config changes are kept in memory and saved on-demand."""
2798
super(TestStoreSaveChanges, self).setUp()
2799
self.transport = self.get_transport()
2800
# Most of the tests involve two stores pointing to the same persistent
2801
# storage to observe the effects of concurrent changes
2802
self.st1 = config.TransportIniFileStore(self.transport, 'foo.conf')
2803
self.st2 = config.TransportIniFileStore(self.transport, 'foo.conf')
2806
self.warnings.append(args[0] % args[1:])
2807
self.overrideAttr(trace, 'warning', warning)
2809
def has_store(self, store):
2810
store_basename = urlutils.relative_url(self.transport.external_url(),
2811
store.external_url())
2812
return self.transport.has(store_basename)
2814
def get_stack(self, store):
2815
# Any stack will do as long as it uses the right store, just a single
2816
# no-name section is enough
2817
return config.Stack([store.get_sections], store)
2819
def test_no_changes_no_save(self):
2820
s = self.get_stack(self.st1)
2821
s.store.save_changes()
2822
self.assertEqual(False, self.has_store(self.st1))
2824
def test_unrelated_concurrent_update(self):
2825
s1 = self.get_stack(self.st1)
2826
s2 = self.get_stack(self.st2)
2827
s1.set('foo', 'bar')
2828
s2.set('baz', 'quux')
2830
# Changes don't propagate magically
2831
self.assertEqual(None, s1.get('baz'))
2832
s2.store.save_changes()
2833
self.assertEqual('quux', s2.get('baz'))
2834
# Changes are acquired when saving
2835
self.assertEqual('bar', s2.get('foo'))
2836
# Since there is no overlap, no warnings are emitted
2837
self.assertLength(0, self.warnings)
2839
def test_concurrent_update_modified(self):
2840
s1 = self.get_stack(self.st1)
2841
s2 = self.get_stack(self.st2)
2842
s1.set('foo', 'bar')
2843
s2.set('foo', 'baz')
2846
s2.store.save_changes()
2847
self.assertEqual('baz', s2.get('foo'))
2848
# But the user get a warning
2849
self.assertLength(1, self.warnings)
2850
warning = self.warnings[0]
2851
self.assertStartsWith(warning, 'Option foo in section None')
2852
self.assertEndsWith(warning, 'was changed from <CREATED> to bar.'
2853
' The baz value will be saved.')
2855
def test_concurrent_deletion(self):
2856
self.st1._load_from_string('foo=bar')
2858
s1 = self.get_stack(self.st1)
2859
s2 = self.get_stack(self.st2)
2862
s1.store.save_changes()
2864
self.assertLength(0, self.warnings)
2865
s2.store.save_changes()
2867
self.assertLength(1, self.warnings)
2868
warning = self.warnings[0]
2869
self.assertStartsWith(warning, 'Option foo in section None')
2870
self.assertEndsWith(warning, 'was changed from bar to <CREATED>.'
2871
' The <DELETED> value will be saved.')
2874
class TestQuotingIniFileStore(tests.TestCaseWithTransport):
2876
def get_store(self):
2877
return config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2879
def test_get_quoted_string(self):
2880
store = self.get_store()
2881
store._load_from_string('foo= " abc "')
2882
stack = config.Stack([store.get_sections])
2883
self.assertEqual(' abc ', stack.get('foo'))
2885
def test_set_quoted_string(self):
2886
store = self.get_store()
2887
stack = config.Stack([store.get_sections], store)
2888
stack.set('foo', ' a b c ')
2890
self.assertFileEqual('foo = " a b c "' + os.linesep, 'foo.conf')
2893
class TestTransportIniFileStore(TestStore):
2895
def test_loading_unknown_file_fails(self):
2896
store = config.TransportIniFileStore(self.get_transport(),
2898
self.assertRaises(errors.NoSuchFile, store.load)
2900
def test_invalid_content(self):
2901
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2902
self.assertEqual(False, store.is_loaded())
2903
exc = self.assertRaises(
2904
config.ParseConfigError, store._load_from_string,
2905
'this is invalid !')
2906
self.assertEndsWith(exc.filename, 'foo.conf')
2907
# And the load failed
2908
self.assertEqual(False, store.is_loaded())
2910
def test_get_embedded_sections(self):
2911
# A more complicated example (which also shows that section names and
2912
# option names share the same name space...)
2913
# FIXME: This should be fixed by forbidding dicts as values ?
2914
# -- vila 2011-04-05
2915
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2916
store._load_from_string('''
2920
foo_in_DEFAULT=foo_DEFAULT
2928
sections = list(store.get_sections())
2929
self.assertLength(4, sections)
2930
# The default section has no name.
2931
# List values are provided as strings and need to be explicitly
2932
# converted by specifying from_unicode=list_from_store at option
2934
self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
2936
self.assertSectionContent(
2937
('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2938
self.assertSectionContent(
2939
('bar', {'foo_in_bar': 'barbar'}), sections[2])
2940
# sub sections are provided as embedded dicts.
2941
self.assertSectionContent(
2942
('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2946
class TestLockableIniFileStore(TestStore):
2948
def test_create_store_in_created_dir(self):
2949
self.assertPathDoesNotExist('dir')
2950
t = self.get_transport('dir/subdir')
2951
store = config.LockableIniFileStore(t, 'foo.conf')
2952
store.get_mutable_section(None).set('foo', 'bar')
2954
self.assertPathExists('dir/subdir')
2957
class TestConcurrentStoreUpdates(TestStore):
2958
"""Test that Stores properly handle conccurent updates.
2960
New Store implementation may fail some of these tests but until such
2961
implementations exist it's hard to properly filter them from the scenarios
2962
applied here. If you encounter such a case, contact the bzr devs.
2965
scenarios = [(key, {'get_stack': builder}) for key, builder
2966
in config.test_stack_builder_registry.iteritems()]
2969
super(TestConcurrentStoreUpdates, self).setUp()
2970
self.stack = self.get_stack(self)
2971
if not isinstance(self.stack, config._CompatibleStack):
2972
raise tests.TestNotApplicable(
2973
'%s is not meant to be compatible with the old config design'
2975
self.stack.set('one', '1')
2976
self.stack.set('two', '2')
2978
self.stack.store.save()
2980
def test_simple_read_access(self):
2981
self.assertEqual('1', self.stack.get('one'))
2983
def test_simple_write_access(self):
2984
self.stack.set('one', 'one')
2985
self.assertEqual('one', self.stack.get('one'))
2987
def test_listen_to_the_last_speaker(self):
2989
c2 = self.get_stack(self)
2990
c1.set('one', 'ONE')
2991
c2.set('two', 'TWO')
2992
self.assertEqual('ONE', c1.get('one'))
2993
self.assertEqual('TWO', c2.get('two'))
2994
# The second update respect the first one
2995
self.assertEqual('ONE', c2.get('one'))
2997
def test_last_speaker_wins(self):
2998
# If the same config is not shared, the same variable modified twice
2999
# can only see a single result.
3001
c2 = self.get_stack(self)
3004
self.assertEqual('c2', c2.get('one'))
3005
# The first modification is still available until another refresh
3007
self.assertEqual('c1', c1.get('one'))
3008
c1.set('two', 'done')
3009
self.assertEqual('c2', c1.get('one'))
3011
def test_writes_are_serialized(self):
3013
c2 = self.get_stack(self)
3015
# We spawn a thread that will pause *during* the config saving.
3016
before_writing = threading.Event()
3017
after_writing = threading.Event()
3018
writing_done = threading.Event()
3019
c1_save_without_locking_orig = c1.store.save_without_locking
3020
def c1_save_without_locking():
3021
before_writing.set()
3022
c1_save_without_locking_orig()
3023
# The lock is held. We wait for the main thread to decide when to
3025
after_writing.wait()
3026
c1.store.save_without_locking = c1_save_without_locking
3030
t1 = threading.Thread(target=c1_set)
3031
# Collect the thread after the test
3032
self.addCleanup(t1.join)
3033
# Be ready to unblock the thread if the test goes wrong
3034
self.addCleanup(after_writing.set)
3036
before_writing.wait()
3037
self.assertRaises(errors.LockContention,
3038
c2.set, 'one', 'c2')
3039
self.assertEqual('c1', c1.get('one'))
3040
# Let the lock be released
3044
self.assertEqual('c2', c2.get('one'))
3046
def test_read_while_writing(self):
3048
# We spawn a thread that will pause *during* the write
3049
ready_to_write = threading.Event()
3050
do_writing = threading.Event()
3051
writing_done = threading.Event()
3052
# We override the _save implementation so we know the store is locked
3053
c1_save_without_locking_orig = c1.store.save_without_locking
3054
def c1_save_without_locking():
3055
ready_to_write.set()
3056
# The lock is held. We wait for the main thread to decide when to
3059
c1_save_without_locking_orig()
3061
c1.store.save_without_locking = c1_save_without_locking
3064
t1 = threading.Thread(target=c1_set)
3065
# Collect the thread after the test
3066
self.addCleanup(t1.join)
3067
# Be ready to unblock the thread if the test goes wrong
3068
self.addCleanup(do_writing.set)
3070
# Ensure the thread is ready to write
3071
ready_to_write.wait()
3072
self.assertEqual('c1', c1.get('one'))
3073
# If we read during the write, we get the old value
3074
c2 = self.get_stack(self)
3075
self.assertEqual('1', c2.get('one'))
3076
# Let the writing occur and ensure it occurred
3079
# Now we get the updated value
3080
c3 = self.get_stack(self)
3081
self.assertEqual('c1', c3.get('one'))
3083
# FIXME: It may be worth looking into removing the lock dir when it's not
3084
# needed anymore and look at possible fallouts for concurrent lockers. This
3085
# will matter if/when we use config files outside of breezy directories
3086
# (.config/breezy or .bzr) -- vila 20110-04-111
3089
class TestSectionMatcher(TestStore):
3091
scenarios = [('location', {'matcher': config.LocationMatcher}),
3092
('id', {'matcher': config.NameMatcher}),]
3095
super(TestSectionMatcher, self).setUp()
3096
# Any simple store is good enough
3097
self.get_store = config.test_store_builder_registry.get('configobj')
3099
def test_no_matches_for_empty_stores(self):
3100
store = self.get_store(self)
3101
store._load_from_string('')
3102
matcher = self.matcher(store, '/bar')
3103
self.assertEqual([], list(matcher.get_sections()))
3105
def test_build_doesnt_load_store(self):
3106
store = self.get_store(self)
3107
self.matcher(store, '/bar')
3108
self.assertFalse(store.is_loaded())
3111
class TestLocationSection(tests.TestCase):
3113
def get_section(self, options, extra_path):
3114
section = config.Section('foo', options)
3115
return config.LocationSection(section, extra_path)
3117
def test_simple_option(self):
3118
section = self.get_section({'foo': 'bar'}, '')
3119
self.assertEqual('bar', section.get('foo'))
3121
def test_option_with_extra_path(self):
3122
section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
3124
self.assertEqual('bar/baz', section.get('foo'))
3126
def test_invalid_policy(self):
3127
section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
3129
# invalid policies are ignored
3130
self.assertEqual('bar', section.get('foo'))
3133
class TestLocationMatcher(TestStore):
3136
super(TestLocationMatcher, self).setUp()
3137
# Any simple store is good enough
3138
self.get_store = config.test_store_builder_registry.get('configobj')
3140
def test_unrelated_section_excluded(self):
3141
store = self.get_store(self)
3142
store._load_from_string('''
3150
section=/foo/bar/baz
3154
self.assertEqual(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3156
[section.id for _, section in store.get_sections()])
3157
matcher = config.LocationMatcher(store, '/foo/bar/quux')
3158
sections = [section for _, section in matcher.get_sections()]
3159
self.assertEqual(['/foo/bar', '/foo'],
3160
[section.id for section in sections])
3161
self.assertEqual(['quux', 'bar/quux'],
3162
[section.extra_path for section in sections])
3164
def test_more_specific_sections_first(self):
3165
store = self.get_store(self)
3166
store._load_from_string('''
3172
self.assertEqual(['/foo', '/foo/bar'],
3173
[section.id for _, section in store.get_sections()])
3174
matcher = config.LocationMatcher(store, '/foo/bar/baz')
3175
sections = [section for _, section in matcher.get_sections()]
3176
self.assertEqual(['/foo/bar', '/foo'],
3177
[section.id for section in sections])
3178
self.assertEqual(['baz', 'bar/baz'],
3179
[section.extra_path for section in sections])
3181
def test_appendpath_in_no_name_section(self):
3182
# It's a bit weird to allow appendpath in a no-name section, but
3183
# someone may found a use for it
3184
store = self.get_store(self)
3185
store._load_from_string('''
3187
foo:policy = appendpath
3189
matcher = config.LocationMatcher(store, 'dir/subdir')
3190
sections = list(matcher.get_sections())
3191
self.assertLength(1, sections)
3192
self.assertEqual('bar/dir/subdir', sections[0][1].get('foo'))
3194
def test_file_urls_are_normalized(self):
3195
store = self.get_store(self)
3196
if sys.platform == 'win32':
3197
expected_url = 'file:///C:/dir/subdir'
3198
expected_location = 'C:/dir/subdir'
3200
expected_url = 'file:///dir/subdir'
3201
expected_location = '/dir/subdir'
3202
matcher = config.LocationMatcher(store, expected_url)
3203
self.assertEqual(expected_location, matcher.location)
3205
def test_branch_name_colo(self):
3206
store = self.get_store(self)
3207
store._load_from_string(dedent("""\
3209
push_location=my{branchname}
3211
matcher = config.LocationMatcher(store, 'file:///,branch=example%3c')
3212
self.assertEqual('example<', matcher.branch_name)
3213
((_, section),) = matcher.get_sections()
3214
self.assertEqual('example<', section.locals['branchname'])
3216
def test_branch_name_basename(self):
3217
store = self.get_store(self)
3218
store._load_from_string(dedent("""\
3220
push_location=my{branchname}
3222
matcher = config.LocationMatcher(store, 'file:///parent/example%3c')
3223
self.assertEqual('example<', matcher.branch_name)
3224
((_, section),) = matcher.get_sections()
3225
self.assertEqual('example<', section.locals['branchname'])
3228
class TestStartingPathMatcher(TestStore):
3231
super(TestStartingPathMatcher, self).setUp()
3232
# Any simple store is good enough
3233
self.store = config.IniFileStore()
3235
def assertSectionIDs(self, expected, location, content):
3236
self.store._load_from_string(content)
3237
matcher = config.StartingPathMatcher(self.store, location)
3238
sections = list(matcher.get_sections())
3239
self.assertLength(len(expected), sections)
3240
self.assertEqual(expected, [section.id for _, section in sections])
3243
def test_empty(self):
3244
self.assertSectionIDs([], self.get_url(), '')
3246
def test_url_vs_local_paths(self):
3247
# The matcher location is an url and the section names are local paths
3248
self.assertSectionIDs(['/foo/bar', '/foo'],
3249
'file:///foo/bar/baz', '''\
3254
def test_local_path_vs_url(self):
3255
# The matcher location is a local path and the section names are urls
3256
self.assertSectionIDs(['file:///foo/bar', 'file:///foo'],
3257
'/foo/bar/baz', '''\
3263
def test_no_name_section_included_when_present(self):
3264
# Note that other tests will cover the case where the no-name section
3265
# is empty and as such, not included.
3266
sections = self.assertSectionIDs(['/foo/bar', '/foo', None],
3267
'/foo/bar/baz', '''\
3268
option = defined so the no-name section exists
3272
self.assertEqual(['baz', 'bar/baz', '/foo/bar/baz'],
3273
[s.locals['relpath'] for _, s in sections])
3275
def test_order_reversed(self):
3276
self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
3281
def test_unrelated_section_excluded(self):
3282
self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
3288
def test_glob_included(self):
3289
sections = self.assertSectionIDs(['/foo/*/baz', '/foo/b*', '/foo'],
3290
'/foo/bar/baz', '''\
3296
# Note that 'baz' as a relpath for /foo/b* is not fully correct, but
3297
# nothing really is... as far using {relpath} to append it to something
3298
# else, this seems good enough though.
3299
self.assertEqual(['', 'baz', 'bar/baz'],
3300
[s.locals['relpath'] for _, s in sections])
3302
def test_respect_order(self):
3303
self.assertSectionIDs(['/foo', '/foo/b*', '/foo/*/baz'],
3304
'/foo/bar/baz', '''\
3312
class TestNameMatcher(TestStore):
3315
super(TestNameMatcher, self).setUp()
3316
self.matcher = config.NameMatcher
3317
# Any simple store is good enough
3318
self.get_store = config.test_store_builder_registry.get('configobj')
3320
def get_matching_sections(self, name):
3321
store = self.get_store(self)
3322
store._load_from_string('''
3330
matcher = self.matcher(store, name)
3331
return list(matcher.get_sections())
3333
def test_matching(self):
3334
sections = self.get_matching_sections('foo')
3335
self.assertLength(1, sections)
3336
self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3338
def test_not_matching(self):
3339
sections = self.get_matching_sections('baz')
3340
self.assertLength(0, sections)
3343
class TestBaseStackGet(tests.TestCase):
3346
super(TestBaseStackGet, self).setUp()
3347
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3349
def test_get_first_definition(self):
3350
store1 = config.IniFileStore()
3351
store1._load_from_string('foo=bar')
3352
store2 = config.IniFileStore()
3353
store2._load_from_string('foo=baz')
3354
conf = config.Stack([store1.get_sections, store2.get_sections])
3355
self.assertEqual('bar', conf.get('foo'))
3357
def test_get_with_registered_default_value(self):
3358
config.option_registry.register(config.Option('foo', default='bar'))
3359
conf_stack = config.Stack([])
3360
self.assertEqual('bar', conf_stack.get('foo'))
3362
def test_get_without_registered_default_value(self):
3363
config.option_registry.register(config.Option('foo'))
3364
conf_stack = config.Stack([])
3365
self.assertEqual(None, conf_stack.get('foo'))
3367
def test_get_without_default_value_for_not_registered(self):
3368
conf_stack = config.Stack([])
3369
self.assertEqual(None, conf_stack.get('foo'))
3371
def test_get_for_empty_section_callable(self):
3372
conf_stack = config.Stack([lambda : []])
3373
self.assertEqual(None, conf_stack.get('foo'))
3375
def test_get_for_broken_callable(self):
3376
# Trying to use and invalid callable raises an exception on first use
3377
conf_stack = config.Stack([object])
3378
self.assertRaises(TypeError, conf_stack.get, 'foo')
3381
class TestStackWithSimpleStore(tests.TestCase):
3384
super(TestStackWithSimpleStore, self).setUp()
3385
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3386
self.registry = config.option_registry
3388
def get_conf(self, content=None):
3389
return config.MemoryStack(content)
3391
def test_override_value_from_env(self):
3392
self.overrideEnv('FOO', None)
3393
self.registry.register(
3394
config.Option('foo', default='bar', override_from_env=['FOO']))
3395
self.overrideEnv('FOO', 'quux')
3396
# Env variable provides a default taking over the option one
3397
conf = self.get_conf('foo=store')
3398
self.assertEqual('quux', conf.get('foo'))
3400
def test_first_override_value_from_env_wins(self):
3401
self.overrideEnv('NO_VALUE', None)
3402
self.overrideEnv('FOO', None)
3403
self.overrideEnv('BAZ', None)
3404
self.registry.register(
3405
config.Option('foo', default='bar',
3406
override_from_env=['NO_VALUE', 'FOO', 'BAZ']))
3407
self.overrideEnv('FOO', 'foo')
3408
self.overrideEnv('BAZ', 'baz')
3409
# The first env var set wins
3410
conf = self.get_conf('foo=store')
3411
self.assertEqual('foo', conf.get('foo'))
3414
class TestMemoryStack(tests.TestCase):
3417
conf = config.MemoryStack('foo=bar')
3418
self.assertEqual('bar', conf.get('foo'))
3421
conf = config.MemoryStack('foo=bar')
3422
conf.set('foo', 'baz')
3423
self.assertEqual('baz', conf.get('foo'))
3425
def test_no_content(self):
3426
conf = config.MemoryStack()
3427
# No content means no loading
3428
self.assertFalse(conf.store.is_loaded())
3429
self.assertRaises(NotImplementedError, conf.get, 'foo')
3430
# But a content can still be provided
3431
conf.store._load_from_string('foo=bar')
3432
self.assertEqual('bar', conf.get('foo'))
3435
class TestStackIterSections(tests.TestCase):
3437
def test_empty_stack(self):
3438
conf = config.Stack([])
3439
sections = list(conf.iter_sections())
3440
self.assertLength(0, sections)
3442
def test_empty_store(self):
3443
store = config.IniFileStore()
3444
store._load_from_string('')
3445
conf = config.Stack([store.get_sections])
3446
sections = list(conf.iter_sections())
3447
self.assertLength(0, sections)
3449
def test_simple_store(self):
3450
store = config.IniFileStore()
3451
store._load_from_string('foo=bar')
3452
conf = config.Stack([store.get_sections])
3453
tuples = list(conf.iter_sections())
3454
self.assertLength(1, tuples)
3455
(found_store, found_section) = tuples[0]
3456
self.assertIs(store, found_store)
3458
def test_two_stores(self):
3459
store1 = config.IniFileStore()
3460
store1._load_from_string('foo=bar')
3461
store2 = config.IniFileStore()
3462
store2._load_from_string('bar=qux')
3463
conf = config.Stack([store1.get_sections, store2.get_sections])
3464
tuples = list(conf.iter_sections())
3465
self.assertLength(2, tuples)
3466
self.assertIs(store1, tuples[0][0])
3467
self.assertIs(store2, tuples[1][0])
3470
class TestStackWithTransport(tests.TestCaseWithTransport):
3472
scenarios = [(key, {'get_stack': builder}) for key, builder
3473
in config.test_stack_builder_registry.iteritems()]
3476
class TestConcreteStacks(TestStackWithTransport):
3478
def test_build_stack(self):
3479
# Just a smoke test to help debug builders
3480
self.get_stack(self)
3483
class TestStackGet(TestStackWithTransport):
3486
super(TestStackGet, self).setUp()
3487
self.conf = self.get_stack(self)
3489
def test_get_for_empty_stack(self):
3490
self.assertEqual(None, self.conf.get('foo'))
3492
def test_get_hook(self):
3493
self.conf.set('foo', 'bar')
3497
config.ConfigHooks.install_named_hook('get', hook, None)
3498
self.assertLength(0, calls)
3499
value = self.conf.get('foo')
3500
self.assertEqual('bar', value)
3501
self.assertLength(1, calls)
3502
self.assertEqual((self.conf, 'foo', 'bar'), calls[0])
3505
class TestStackGetWithConverter(tests.TestCase):
3508
super(TestStackGetWithConverter, self).setUp()
3509
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3510
self.registry = config.option_registry
3512
def get_conf(self, content=None):
3513
return config.MemoryStack(content)
3515
def register_bool_option(self, name, default=None, default_from_env=None):
3516
b = config.Option(name, help='A boolean.',
3517
default=default, default_from_env=default_from_env,
3518
from_unicode=config.bool_from_store)
3519
self.registry.register(b)
3521
def test_get_default_bool_None(self):
3522
self.register_bool_option('foo')
3523
conf = self.get_conf('')
3524
self.assertEqual(None, conf.get('foo'))
3526
def test_get_default_bool_True(self):
3527
self.register_bool_option('foo', u'True')
3528
conf = self.get_conf('')
3529
self.assertEqual(True, conf.get('foo'))
3531
def test_get_default_bool_False(self):
3532
self.register_bool_option('foo', False)
3533
conf = self.get_conf('')
3534
self.assertEqual(False, conf.get('foo'))
3536
def test_get_default_bool_False_as_string(self):
3537
self.register_bool_option('foo', u'False')
3538
conf = self.get_conf('')
3539
self.assertEqual(False, conf.get('foo'))
3541
def test_get_default_bool_from_env_converted(self):
3542
self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3543
self.overrideEnv('FOO', 'False')
3544
conf = self.get_conf('')
3545
self.assertEqual(False, conf.get('foo'))
3547
def test_get_default_bool_when_conversion_fails(self):
3548
self.register_bool_option('foo', default='True')
3549
conf = self.get_conf('foo=invalid boolean')
3550
self.assertEqual(True, conf.get('foo'))
3552
def register_integer_option(self, name,
3553
default=None, default_from_env=None):
3554
i = config.Option(name, help='An integer.',
3555
default=default, default_from_env=default_from_env,
3556
from_unicode=config.int_from_store)
3557
self.registry.register(i)
3559
def test_get_default_integer_None(self):
3560
self.register_integer_option('foo')
3561
conf = self.get_conf('')
3562
self.assertEqual(None, conf.get('foo'))
3564
def test_get_default_integer(self):
3565
self.register_integer_option('foo', 42)
3566
conf = self.get_conf('')
3567
self.assertEqual(42, conf.get('foo'))
3569
def test_get_default_integer_as_string(self):
3570
self.register_integer_option('foo', u'42')
3571
conf = self.get_conf('')
3572
self.assertEqual(42, conf.get('foo'))
3574
def test_get_default_integer_from_env(self):
3575
self.register_integer_option('foo', default_from_env=['FOO'])
3576
self.overrideEnv('FOO', '18')
3577
conf = self.get_conf('')
3578
self.assertEqual(18, conf.get('foo'))
3580
def test_get_default_integer_when_conversion_fails(self):
3581
self.register_integer_option('foo', default='12')
3582
conf = self.get_conf('foo=invalid integer')
3583
self.assertEqual(12, conf.get('foo'))
3585
def register_list_option(self, name, default=None, default_from_env=None):
3586
l = config.ListOption(name, help='A list.', default=default,
3587
default_from_env=default_from_env)
3588
self.registry.register(l)
3590
def test_get_default_list_None(self):
3591
self.register_list_option('foo')
3592
conf = self.get_conf('')
3593
self.assertEqual(None, conf.get('foo'))
3595
def test_get_default_list_empty(self):
3596
self.register_list_option('foo', '')
3597
conf = self.get_conf('')
3598
self.assertEqual([], conf.get('foo'))
3600
def test_get_default_list_from_env(self):
3601
self.register_list_option('foo', default_from_env=['FOO'])
3602
self.overrideEnv('FOO', '')
3603
conf = self.get_conf('')
3604
self.assertEqual([], conf.get('foo'))
3606
def test_get_with_list_converter_no_item(self):
3607
self.register_list_option('foo', None)
3608
conf = self.get_conf('foo=,')
3609
self.assertEqual([], conf.get('foo'))
3611
def test_get_with_list_converter_many_items(self):
3612
self.register_list_option('foo', None)
3613
conf = self.get_conf('foo=m,o,r,e')
3614
self.assertEqual(['m', 'o', 'r', 'e'], conf.get('foo'))
3616
def test_get_with_list_converter_embedded_spaces_many_items(self):
3617
self.register_list_option('foo', None)
3618
conf = self.get_conf('foo=" bar", "baz "')
3619
self.assertEqual([' bar', 'baz '], conf.get('foo'))
3621
def test_get_with_list_converter_stripped_spaces_many_items(self):
3622
self.register_list_option('foo', None)
3623
conf = self.get_conf('foo= bar , baz ')
3624
self.assertEqual(['bar', 'baz'], conf.get('foo'))
3627
class TestIterOptionRefs(tests.TestCase):
3628
"""iter_option_refs is a bit unusual, document some cases."""
3630
def assertRefs(self, expected, string):
3631
self.assertEqual(expected, list(config.iter_option_refs(string)))
3633
def test_empty(self):
3634
self.assertRefs([(False, '')], '')
3636
def test_no_refs(self):
3637
self.assertRefs([(False, 'foo bar')], 'foo bar')
3639
def test_single_ref(self):
3640
self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
3642
def test_broken_ref(self):
3643
self.assertRefs([(False, '{foo')], '{foo')
3645
def test_embedded_ref(self):
3646
self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
3649
def test_two_refs(self):
3650
self.assertRefs([(False, ''), (True, '{foo}'),
3651
(False, ''), (True, '{bar}'),
3655
def test_newline_in_refs_are_not_matched(self):
3656
self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
3659
class TestStackExpandOptions(tests.TestCaseWithTransport):
3662
super(TestStackExpandOptions, self).setUp()
3663
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3664
self.registry = config.option_registry
3665
store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3666
self.conf = config.Stack([store.get_sections], store)
3668
def assertExpansion(self, expected, string, env=None):
3669
self.assertEqual(expected, self.conf.expand_options(string, env))
3671
def test_no_expansion(self):
3672
self.assertExpansion('foo', 'foo')
3674
def test_expand_default_value(self):
3675
self.conf.store._load_from_string('bar=baz')
3676
self.registry.register(config.Option('foo', default=u'{bar}'))
3677
self.assertEqual('baz', self.conf.get('foo', expand=True))
3679
def test_expand_default_from_env(self):
3680
self.conf.store._load_from_string('bar=baz')
3681
self.registry.register(config.Option('foo', default_from_env=['FOO']))
3682
self.overrideEnv('FOO', '{bar}')
3683
self.assertEqual('baz', self.conf.get('foo', expand=True))
3685
def test_expand_default_on_failed_conversion(self):
3686
self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
3687
self.registry.register(
3688
config.Option('foo', default=u'{bar}',
3689
from_unicode=config.int_from_store))
3690
self.assertEqual(42, self.conf.get('foo', expand=True))
3692
def test_env_adding_options(self):
3693
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3695
def test_env_overriding_options(self):
3696
self.conf.store._load_from_string('foo=baz')
3697
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3699
def test_simple_ref(self):
3700
self.conf.store._load_from_string('foo=xxx')
3701
self.assertExpansion('xxx', '{foo}')
3703
def test_unknown_ref(self):
3704
self.assertRaises(config.ExpandingUnknownOption,
3705
self.conf.expand_options, '{foo}')
3707
def test_illegal_def_is_ignored(self):
3708
self.assertExpansion('{1,2}', '{1,2}')
3709
self.assertExpansion('{ }', '{ }')
3710
self.assertExpansion('${Foo,f}', '${Foo,f}')
3712
def test_indirect_ref(self):
3713
self.conf.store._load_from_string('''
3717
self.assertExpansion('xxx', '{bar}')
3719
def test_embedded_ref(self):
3720
self.conf.store._load_from_string('''
3724
self.assertExpansion('xxx', '{{bar}}')
3726
def test_simple_loop(self):
3727
self.conf.store._load_from_string('foo={foo}')
3728
self.assertRaises(config.OptionExpansionLoop,
3729
self.conf.expand_options, '{foo}')
3731
def test_indirect_loop(self):
3732
self.conf.store._load_from_string('''
3736
e = self.assertRaises(config.OptionExpansionLoop,
3737
self.conf.expand_options, '{foo}')
3738
self.assertEqual('foo->bar->baz', e.refs)
3739
self.assertEqual('{foo}', e.string)
3741
def test_list(self):
3742
self.conf.store._load_from_string('''
3746
list={foo},{bar},{baz}
3748
self.registry.register(
3749
config.ListOption('list'))
3750
self.assertEqual(['start', 'middle', 'end'],
3751
self.conf.get('list', expand=True))
3753
def test_cascading_list(self):
3754
self.conf.store._load_from_string('''
3760
self.registry.register(config.ListOption('list'))
3761
# Register an intermediate option as a list to ensure no conversion
3762
# happen while expanding. Conversion should only occur for the original
3763
# option ('list' here).
3764
self.registry.register(config.ListOption('baz'))
3765
self.assertEqual(['start', 'middle', 'end'],
3766
self.conf.get('list', expand=True))
3768
def test_pathologically_hidden_list(self):
3769
self.conf.store._load_from_string('''
3775
hidden={start}{middle}{end}
3777
# What matters is what the registration says, the conversion happens
3778
# only after all expansions have been performed
3779
self.registry.register(config.ListOption('hidden'))
3780
self.assertEqual(['bin', 'go'],
3781
self.conf.get('hidden', expand=True))
3784
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3787
super(TestStackCrossSectionsExpand, self).setUp()
3789
def get_config(self, location, string):
3792
# Since we don't save the config we won't strictly require to inherit
3793
# from TestCaseInTempDir, but an error occurs so quickly...
3794
c = config.LocationStack(location)
3795
c.store._load_from_string(string)
3798
def test_dont_cross_unrelated_section(self):
3799
c = self.get_config('/another/branch/path','''
3804
[/another/branch/path]
3807
self.assertRaises(config.ExpandingUnknownOption,
3808
c.get, 'bar', expand=True)
3810
def test_cross_related_sections(self):
3811
c = self.get_config('/project/branch/path','''
3815
[/project/branch/path]
3818
self.assertEqual('quux', c.get('bar', expand=True))
3821
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
3823
def test_cross_global_locations(self):
3824
l_store = config.LocationStore()
3825
l_store._load_from_string('''
3831
g_store = config.GlobalStore()
3832
g_store._load_from_string('''
3838
stack = config.LocationStack('/branch')
3839
self.assertEqual('glob-bar', stack.get('lbar', expand=True))
3840
self.assertEqual('loc-foo', stack.get('gfoo', expand=True))
3843
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
3845
def test_expand_locals_empty(self):
3846
l_store = config.LocationStore()
3847
l_store._load_from_string('''
3848
[/home/user/project]
3853
stack = config.LocationStack('/home/user/project/')
3854
self.assertEqual('', stack.get('base', expand=True))
3855
self.assertEqual('', stack.get('rel', expand=True))
3857
def test_expand_basename_locally(self):
3858
l_store = config.LocationStore()
3859
l_store._load_from_string('''
3860
[/home/user/project]
3864
stack = config.LocationStack('/home/user/project/branch')
3865
self.assertEqual('branch', stack.get('bfoo', expand=True))
3867
def test_expand_basename_locally_longer_path(self):
3868
l_store = config.LocationStore()
3869
l_store._load_from_string('''
3874
stack = config.LocationStack('/home/user/project/dir/branch')
3875
self.assertEqual('branch', stack.get('bfoo', expand=True))
3877
def test_expand_relpath_locally(self):
3878
l_store = config.LocationStore()
3879
l_store._load_from_string('''
3880
[/home/user/project]
3881
lfoo = loc-foo/{relpath}
3884
stack = config.LocationStack('/home/user/project/branch')
3885
self.assertEqual('loc-foo/branch', stack.get('lfoo', expand=True))
3887
def test_expand_relpath_unknonw_in_global(self):
3888
g_store = config.GlobalStore()
3889
g_store._load_from_string('''
3894
stack = config.LocationStack('/home/user/project/branch')
3895
self.assertRaises(config.ExpandingUnknownOption,
3896
stack.get, 'gfoo', expand=True)
3898
def test_expand_local_option_locally(self):
3899
l_store = config.LocationStore()
3900
l_store._load_from_string('''
3901
[/home/user/project]
3902
lfoo = loc-foo/{relpath}
3906
g_store = config.GlobalStore()
3907
g_store._load_from_string('''
3913
stack = config.LocationStack('/home/user/project/branch')
3914
self.assertEqual('glob-bar', stack.get('lbar', expand=True))
3915
self.assertEqual('loc-foo/branch', stack.get('gfoo', expand=True))
3917
def test_locals_dont_leak(self):
3918
"""Make sure we chose the right local in presence of several sections.
3920
l_store = config.LocationStore()
3921
l_store._load_from_string('''
3923
lfoo = loc-foo/{relpath}
3924
[/home/user/project]
3925
lfoo = loc-foo/{relpath}
3928
stack = config.LocationStack('/home/user/project/branch')
3929
self.assertEqual('loc-foo/branch', stack.get('lfoo', expand=True))
3930
stack = config.LocationStack('/home/user/bar/baz')
3931
self.assertEqual('loc-foo/bar/baz', stack.get('lfoo', expand=True))
3935
class TestStackSet(TestStackWithTransport):
3937
def test_simple_set(self):
3938
conf = self.get_stack(self)
3939
self.assertEqual(None, conf.get('foo'))
3940
conf.set('foo', 'baz')
3941
# Did we get it back ?
3942
self.assertEqual('baz', conf.get('foo'))
3944
def test_set_creates_a_new_section(self):
3945
conf = self.get_stack(self)
3946
conf.set('foo', 'baz')
3947
self.assertEqual, 'baz', conf.get('foo')
3949
def test_set_hook(self):
3953
config.ConfigHooks.install_named_hook('set', hook, None)
3954
self.assertLength(0, calls)
3955
conf = self.get_stack(self)
3956
conf.set('foo', 'bar')
3957
self.assertLength(1, calls)
3958
self.assertEqual((conf, 'foo', 'bar'), calls[0])
3961
class TestStackRemove(TestStackWithTransport):
3963
def test_remove_existing(self):
3964
conf = self.get_stack(self)
3965
conf.set('foo', 'bar')
3966
self.assertEqual('bar', conf.get('foo'))
3968
# Did we get it back ?
3969
self.assertEqual(None, conf.get('foo'))
3971
def test_remove_unknown(self):
3972
conf = self.get_stack(self)
3973
self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3975
def test_remove_hook(self):
3979
config.ConfigHooks.install_named_hook('remove', hook, None)
3980
self.assertLength(0, calls)
3981
conf = self.get_stack(self)
3982
conf.set('foo', 'bar')
3984
self.assertLength(1, calls)
3985
self.assertEqual((conf, 'foo'), calls[0])
3988
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3991
super(TestConfigGetOptions, self).setUp()
3992
create_configs(self)
3994
def test_no_variable(self):
3995
# Using branch should query branch, locations and breezy
3996
self.assertOptions([], self.branch_config)
3998
def test_option_in_breezy(self):
3999
self.breezy_config.set_user_option('file', 'breezy')
4000
self.assertOptions([('file', 'breezy', 'DEFAULT', 'breezy')],
4003
def test_option_in_locations(self):
4004
self.locations_config.set_user_option('file', 'locations')
4006
[('file', 'locations', self.tree.basedir, 'locations')],
4007
self.locations_config)
4009
def test_option_in_branch(self):
4010
self.branch_config.set_user_option('file', 'branch')
4011
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
4014
def test_option_in_breezy_and_branch(self):
4015
self.breezy_config.set_user_option('file', 'breezy')
4016
self.branch_config.set_user_option('file', 'branch')
4017
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
4018
('file', 'breezy', 'DEFAULT', 'breezy'),],
4021
def test_option_in_branch_and_locations(self):
4022
# Hmm, locations override branch :-/
4023
self.locations_config.set_user_option('file', 'locations')
4024
self.branch_config.set_user_option('file', 'branch')
4026
[('file', 'locations', self.tree.basedir, 'locations'),
4027
('file', 'branch', 'DEFAULT', 'branch'),],
4030
def test_option_in_breezy_locations_and_branch(self):
4031
self.breezy_config.set_user_option('file', 'breezy')
4032
self.locations_config.set_user_option('file', 'locations')
4033
self.branch_config.set_user_option('file', 'branch')
4035
[('file', 'locations', self.tree.basedir, 'locations'),
4036
('file', 'branch', 'DEFAULT', 'branch'),
4037
('file', 'breezy', 'DEFAULT', 'breezy'),],
4041
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
4044
super(TestConfigRemoveOption, self).setUp()
4045
create_configs_with_file_option(self)
4047
def test_remove_in_locations(self):
4048
self.locations_config.remove_user_option('file', self.tree.basedir)
4050
[('file', 'branch', 'DEFAULT', 'branch'),
4051
('file', 'breezy', 'DEFAULT', 'breezy'),],
4054
def test_remove_in_branch(self):
4055
self.branch_config.remove_user_option('file')
4057
[('file', 'locations', self.tree.basedir, 'locations'),
4058
('file', 'breezy', 'DEFAULT', 'breezy'),],
4061
def test_remove_in_breezy(self):
4062
self.breezy_config.remove_user_option('file')
4064
[('file', 'locations', self.tree.basedir, 'locations'),
4065
('file', 'branch', 'DEFAULT', 'branch'),],
4069
class TestConfigGetSections(tests.TestCaseWithTransport):
4072
super(TestConfigGetSections, self).setUp()
4073
create_configs(self)
4075
def assertSectionNames(self, expected, conf, name=None):
4076
"""Check which sections are returned for a given config.
4078
If fallback configurations exist their sections can be included.
4080
:param expected: A list of section names.
4082
:param conf: The configuration that will be queried.
4084
:param name: An optional section name that will be passed to
4087
sections = list(conf._get_sections(name))
4088
self.assertLength(len(expected), sections)
4089
self.assertEqual(expected, [n for n, _, _ in sections])
4091
def test_breezy_default_section(self):
4092
self.assertSectionNames(['DEFAULT'], self.breezy_config)
4094
def test_locations_default_section(self):
4095
# No sections are defined in an empty file
4096
self.assertSectionNames([], self.locations_config)
4098
def test_locations_named_section(self):
4099
self.locations_config.set_user_option('file', 'locations')
4100
self.assertSectionNames([self.tree.basedir], self.locations_config)
4102
def test_locations_matching_sections(self):
4103
loc_config = self.locations_config
4104
loc_config.set_user_option('file', 'locations')
4105
# We need to cheat a bit here to create an option in sections above and
4106
# below the 'location' one.
4107
parser = loc_config._get_parser()
4108
# locations.cong deals with '/' ignoring native os.sep
4109
location_names = self.tree.basedir.split('/')
4110
parent = '/'.join(location_names[:-1])
4111
child = '/'.join(location_names + ['child'])
4113
parser[parent]['file'] = 'parent'
4115
parser[child]['file'] = 'child'
4116
self.assertSectionNames([self.tree.basedir, parent], loc_config)
4118
def test_branch_data_default_section(self):
4119
self.assertSectionNames([None],
4120
self.branch_config._get_branch_data_config())
4122
def test_branch_default_sections(self):
4123
# No sections are defined in an empty locations file
4124
self.assertSectionNames([None, 'DEFAULT'],
4126
# Unless we define an option
4127
self.branch_config._get_location_config().set_user_option(
4128
'file', 'locations')
4129
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
4132
def test_breezy_named_section(self):
4133
# We need to cheat as the API doesn't give direct access to sections
4134
# other than DEFAULT.
4135
self.breezy_config.set_alias('breezy', 'bzr')
4136
self.assertSectionNames(['ALIASES'], self.breezy_config, 'ALIASES')
4139
class TestSharedStores(tests.TestCaseInTempDir):
4141
def test_breezy_conf_shared(self):
4142
g1 = config.GlobalStack()
4143
g2 = config.GlobalStack()
4144
# The two stacks share the same store
4145
self.assertIs(g1.store, g2.store)
4148
class TestAuthenticationConfigFilePermissions(tests.TestCaseInTempDir):
4149
"""Test warning for permissions of authentication.conf."""
4152
super(TestAuthenticationConfigFilePermissions, self).setUp()
4153
self.path = osutils.pathjoin(self.test_dir, 'authentication.conf')
4154
with open(self.path, 'w') as f:
4155
f.write(b"""[broken]
4158
port=port # Error: Not an int
4160
self.overrideAttr(config, 'authentication_config_filename',
4162
osutils.chmod_if_possible(self.path, 0o755)
4164
def test_check_warning(self):
4165
conf = config.AuthenticationConfig()
4166
self.assertEqual(conf._filename, self.path)
4167
self.assertContainsRe(self.get_log(),
4168
'Saved passwords may be accessible by other users.')
4170
def test_check_suppressed_warning(self):
4171
global_config = config.GlobalConfig()
4172
global_config.set_user_option('suppress_warnings',
4173
'insecure_permissions')
4174
conf = config.AuthenticationConfig()
4175
self.assertEqual(conf._filename, self.path)
4176
self.assertNotContainsRe(self.get_log(),
4177
'Saved passwords may be accessible by other users.')
1315
4180
class TestAuthenticationConfigFile(tests.TestCase):
1316
4181
"""Test the authentication.conf file matching"""