367
585
'/home/bogus/.cache')
370
class TestIniConfig(tests.TestCase):
588
class TestXDGConfigDir(tests.TestCaseInTempDir):
589
# must be in temp dir because config tests for the existence of the bazaar
590
# subdirectory of $XDG_CONFIG_HOME
593
if sys.platform in ('darwin', 'win32'):
594
raise tests.TestNotApplicable(
595
'XDG config dir not used on this platform')
596
super(TestXDGConfigDir, self).setUp()
597
self.overrideEnv('HOME', self.test_home_dir)
598
# BZR_HOME overrides everything we want to test so unset it.
599
self.overrideEnv('BZR_HOME', None)
601
def test_xdg_config_dir_exists(self):
602
"""When ~/.config/bazaar exists, use it as the config dir."""
603
newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
605
self.assertEqual(config.config_dir(), newdir)
607
def test_xdg_config_home(self):
608
"""When XDG_CONFIG_HOME is set, use it."""
609
xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
610
self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
611
newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
613
self.assertEqual(config.config_dir(), newdir)
616
class TestIniConfig(tests.TestCaseInTempDir):
372
618
def make_config_parser(self, s):
373
conf = config.IniBasedConfig(None)
374
parser = conf._get_parser(file=StringIO(s.encode('utf-8')))
619
conf = config.IniBasedConfig.from_string(s)
620
return conf, conf._get_parser()
378
623
class TestIniConfigBuilding(TestIniConfig):
380
625
def test_contructs(self):
381
my_config = config.IniBasedConfig("nothing")
626
my_config = config.IniBasedConfig()
383
628
def test_from_fp(self):
384
config_file = StringIO(sample_config_text.encode('utf-8'))
385
my_config = config.IniBasedConfig(None)
387
isinstance(my_config._get_parser(file=config_file),
388
configobj.ConfigObj))
629
my_config = config.IniBasedConfig.from_string(sample_config_text)
630
self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
390
632
def test_cached(self):
633
my_config = config.IniBasedConfig.from_string(sample_config_text)
634
parser = my_config._get_parser()
635
self.assertTrue(my_config._get_parser() is parser)
637
def _dummy_chown(self, path, uid, gid):
638
self.path, self.uid, self.gid = path, uid, gid
640
def test_ini_config_ownership(self):
641
"""Ensure that chown is happening during _write_config_file"""
642
self.requireFeature(features.chown_feature)
643
self.overrideAttr(os, 'chown', self._dummy_chown)
644
self.path = self.uid = self.gid = None
645
conf = config.IniBasedConfig(file_name='./foo.conf')
646
conf._write_config_file()
647
self.assertEquals(self.path, './foo.conf')
648
self.assertTrue(isinstance(self.uid, int))
649
self.assertTrue(isinstance(self.gid, int))
651
def test_get_filename_parameter_is_deprecated_(self):
652
conf = self.callDeprecated([
653
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
654
' Use file_name instead.'],
655
config.IniBasedConfig, lambda: 'ini.conf')
656
self.assertEqual('ini.conf', conf.file_name)
658
def test_get_parser_file_parameter_is_deprecated_(self):
391
659
config_file = StringIO(sample_config_text.encode('utf-8'))
392
my_config = config.IniBasedConfig(None)
393
parser = my_config._get_parser(file=config_file)
394
self.failUnless(my_config._get_parser() is parser)
660
conf = config.IniBasedConfig.from_string(sample_config_text)
661
conf = self.callDeprecated([
662
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
663
' Use IniBasedConfig(_content=xxx) instead.'],
664
conf._get_parser, file=config_file)
667
class TestIniConfigSaving(tests.TestCaseInTempDir):
669
def test_cant_save_without_a_file_name(self):
670
conf = config.IniBasedConfig()
671
self.assertRaises(AssertionError, conf._write_config_file)
673
def test_saved_with_content(self):
674
content = 'foo = bar\n'
675
conf = config.IniBasedConfig.from_string(
676
content, file_name='./test.conf', save=True)
677
self.assertFileEqual(content, 'test.conf')
680
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
681
"""What is the default value of expand for config options.
683
This is an opt-in beta feature used to evaluate whether or not option
684
references can appear in dangerous place raising exceptions, disapearing
685
(and as such corrupting data) or if it's safe to activate the option by
688
Note that these tests relies on config._expand_default_value being already
689
overwritten in the parent class setUp.
693
super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
697
self.warnings.append(args[0] % args[1:])
698
self.overrideAttr(trace, 'warning', warning)
700
def get_config(self, expand):
701
c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
705
def assertExpandIs(self, expected):
706
actual = config._get_expand_default_value()
707
#self.config.get_user_option_as_bool('bzr.config.expand')
708
self.assertEquals(expected, actual)
710
def test_default_is_None(self):
711
self.assertEquals(None, config._expand_default_value)
713
def test_default_is_False_even_if_None(self):
714
self.config = self.get_config(None)
715
self.assertExpandIs(False)
717
def test_default_is_False_even_if_invalid(self):
718
self.config = self.get_config('<your choice>')
719
self.assertExpandIs(False)
721
# Huh ? My choice is False ? Thanks, always happy to hear that :D
722
# Wait, you've been warned !
723
self.assertLength(1, self.warnings)
725
'Value "<your choice>" is not a boolean for "bzr.config.expand"',
728
def test_default_is_True(self):
729
self.config = self.get_config(True)
730
self.assertExpandIs(True)
732
def test_default_is_False(self):
733
self.config = self.get_config(False)
734
self.assertExpandIs(False)
737
class TestIniConfigOptionExpansion(tests.TestCase):
738
"""Test option expansion from the IniConfig level.
740
What we really want here is to test the Config level, but the class being
741
abstract as far as storing values is concerned, this can't be done
744
# FIXME: This should be rewritten when all configs share a storage
745
# implementation -- vila 2011-02-18
747
def get_config(self, string=None):
750
c = config.IniBasedConfig.from_string(string)
753
def assertExpansion(self, expected, conf, string, env=None):
754
self.assertEquals(expected, conf.expand_options(string, env))
756
def test_no_expansion(self):
757
c = self.get_config('')
758
self.assertExpansion('foo', c, 'foo')
760
def test_env_adding_options(self):
761
c = self.get_config('')
762
self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
764
def test_env_overriding_options(self):
765
c = self.get_config('foo=baz')
766
self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
768
def test_simple_ref(self):
769
c = self.get_config('foo=xxx')
770
self.assertExpansion('xxx', c, '{foo}')
772
def test_unknown_ref(self):
773
c = self.get_config('')
774
self.assertRaises(errors.ExpandingUnknownOption,
775
c.expand_options, '{foo}')
777
def test_indirect_ref(self):
778
c = self.get_config('''
782
self.assertExpansion('xxx', c, '{bar}')
784
def test_embedded_ref(self):
785
c = self.get_config('''
789
self.assertExpansion('xxx', c, '{{bar}}')
791
def test_simple_loop(self):
792
c = self.get_config('foo={foo}')
793
self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
795
def test_indirect_loop(self):
796
c = self.get_config('''
800
e = self.assertRaises(errors.OptionExpansionLoop,
801
c.expand_options, '{foo}')
802
self.assertEquals('foo->bar->baz', e.refs)
803
self.assertEquals('{foo}', e.string)
806
conf = self.get_config('''
810
list={foo},{bar},{baz}
812
self.assertEquals(['start', 'middle', 'end'],
813
conf.get_user_option('list', expand=True))
815
def test_cascading_list(self):
816
conf = self.get_config('''
822
self.assertEquals(['start', 'middle', 'end'],
823
conf.get_user_option('list', expand=True))
825
def test_pathological_hidden_list(self):
826
conf = self.get_config('''
832
hidden={start}{middle}{end}
834
# Nope, it's either a string or a list, and the list wins as soon as a
835
# ',' appears, so the string concatenation never occur.
836
self.assertEquals(['{foo', '}', '{', 'bar}'],
837
conf.get_user_option('hidden', expand=True))
840
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
842
def get_config(self, location, string=None):
845
# Since we don't save the config we won't strictly require to inherit
846
# from TestCaseInTempDir, but an error occurs so quickly...
847
c = config.LocationConfig.from_string(string, location)
850
def test_dont_cross_unrelated_section(self):
851
c = self.get_config('/another/branch/path','''
856
[/another/branch/path]
859
self.assertRaises(errors.ExpandingUnknownOption,
860
c.get_user_option, 'bar', expand=True)
862
def test_cross_related_sections(self):
863
c = self.get_config('/project/branch/path','''
867
[/project/branch/path]
870
self.assertEquals('quux', c.get_user_option('bar', expand=True))
873
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
875
def test_cannot_reload_without_name(self):
876
conf = config.IniBasedConfig.from_string(sample_config_text)
877
self.assertRaises(AssertionError, conf.reload)
879
def test_reload_see_new_value(self):
880
c1 = config.IniBasedConfig.from_string('editor=vim\n',
881
file_name='./test/conf')
882
c1._write_config_file()
883
c2 = config.IniBasedConfig.from_string('editor=emacs\n',
884
file_name='./test/conf')
885
c2._write_config_file()
886
self.assertEqual('vim', c1.get_user_option('editor'))
887
self.assertEqual('emacs', c2.get_user_option('editor'))
888
# Make sure we get the Right value
890
self.assertEqual('emacs', c1.get_user_option('editor'))
893
class TestLockableConfig(tests.TestCaseInTempDir):
895
scenarios = lockable_config_scenarios()
900
config_section = None
903
super(TestLockableConfig, self).setUp()
904
self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
905
self.config = self.create_config(self._content)
907
def get_existing_config(self):
908
return self.config_class(*self.config_args)
910
def create_config(self, content):
911
kwargs = dict(save=True)
912
c = self.config_class.from_string(content, *self.config_args, **kwargs)
915
def test_simple_read_access(self):
916
self.assertEquals('1', self.config.get_user_option('one'))
918
def test_simple_write_access(self):
919
self.config.set_user_option('one', 'one')
920
self.assertEquals('one', self.config.get_user_option('one'))
922
def test_listen_to_the_last_speaker(self):
924
c2 = self.get_existing_config()
925
c1.set_user_option('one', 'ONE')
926
c2.set_user_option('two', 'TWO')
927
self.assertEquals('ONE', c1.get_user_option('one'))
928
self.assertEquals('TWO', c2.get_user_option('two'))
929
# The second update respect the first one
930
self.assertEquals('ONE', c2.get_user_option('one'))
932
def test_last_speaker_wins(self):
933
# If the same config is not shared, the same variable modified twice
934
# can only see a single result.
936
c2 = self.get_existing_config()
937
c1.set_user_option('one', 'c1')
938
c2.set_user_option('one', 'c2')
939
self.assertEquals('c2', c2._get_user_option('one'))
940
# The first modification is still available until another refresh
942
self.assertEquals('c1', c1._get_user_option('one'))
943
c1.set_user_option('two', 'done')
944
self.assertEquals('c2', c1._get_user_option('one'))
946
def test_writes_are_serialized(self):
948
c2 = self.get_existing_config()
950
# We spawn a thread that will pause *during* the write
951
before_writing = threading.Event()
952
after_writing = threading.Event()
953
writing_done = threading.Event()
954
c1_orig = c1._write_config_file
955
def c1_write_config_file():
958
# The lock is held. We wait for the main thread to decide when to
961
c1._write_config_file = c1_write_config_file
963
c1.set_user_option('one', 'c1')
965
t1 = threading.Thread(target=c1_set_option)
966
# Collect the thread after the test
967
self.addCleanup(t1.join)
968
# Be ready to unblock the thread if the test goes wrong
969
self.addCleanup(after_writing.set)
971
before_writing.wait()
972
self.assertTrue(c1._lock.is_held)
973
self.assertRaises(errors.LockContention,
974
c2.set_user_option, 'one', 'c2')
975
self.assertEquals('c1', c1.get_user_option('one'))
976
# Let the lock be released
979
c2.set_user_option('one', 'c2')
980
self.assertEquals('c2', c2.get_user_option('one'))
982
def test_read_while_writing(self):
984
# We spawn a thread that will pause *during* the write
985
ready_to_write = threading.Event()
986
do_writing = threading.Event()
987
writing_done = threading.Event()
988
c1_orig = c1._write_config_file
989
def c1_write_config_file():
991
# The lock is held. We wait for the main thread to decide when to
996
c1._write_config_file = c1_write_config_file
998
c1.set_user_option('one', 'c1')
999
t1 = threading.Thread(target=c1_set_option)
1000
# Collect the thread after the test
1001
self.addCleanup(t1.join)
1002
# Be ready to unblock the thread if the test goes wrong
1003
self.addCleanup(do_writing.set)
1005
# Ensure the thread is ready to write
1006
ready_to_write.wait()
1007
self.assertTrue(c1._lock.is_held)
1008
self.assertEquals('c1', c1.get_user_option('one'))
1009
# If we read during the write, we get the old value
1010
c2 = self.get_existing_config()
1011
self.assertEquals('1', c2.get_user_option('one'))
1012
# Let the writing occur and ensure it occurred
1015
# Now we get the updated value
1016
c3 = self.get_existing_config()
1017
self.assertEquals('c1', c3.get_user_option('one'))
397
1020
class TestGetUserOptionAs(TestIniConfig):
1312
2028
self.assertIs(None, bzrdir_config.get_default_stack_on())
2031
class TestOldConfigHooks(tests.TestCaseWithTransport):
2034
super(TestOldConfigHooks, self).setUp()
2035
create_configs_with_file_option(self)
2037
def assertGetHook(self, conf, name, value):
2041
config.OldConfigHooks.install_named_hook('get', hook, None)
2043
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2044
self.assertLength(0, calls)
2045
actual_value = conf.get_user_option(name)
2046
self.assertEquals(value, actual_value)
2047
self.assertLength(1, calls)
2048
self.assertEquals((conf, name, value), calls[0])
2050
def test_get_hook_bazaar(self):
2051
self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
2053
def test_get_hook_locations(self):
2054
self.assertGetHook(self.locations_config, 'file', 'locations')
2056
def test_get_hook_branch(self):
2057
# Since locations masks branch, we define a different option
2058
self.branch_config.set_user_option('file2', 'branch')
2059
self.assertGetHook(self.branch_config, 'file2', 'branch')
2061
def assertSetHook(self, conf, name, value):
2065
config.OldConfigHooks.install_named_hook('set', hook, None)
2067
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2068
self.assertLength(0, calls)
2069
conf.set_user_option(name, value)
2070
self.assertLength(1, calls)
2071
# We can't assert the conf object below as different configs use
2072
# different means to implement set_user_option and we care only about
2074
self.assertEquals((name, value), calls[0][1:])
2076
def test_set_hook_bazaar(self):
2077
self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
2079
def test_set_hook_locations(self):
2080
self.assertSetHook(self.locations_config, 'foo', 'locations')
2082
def test_set_hook_branch(self):
2083
self.assertSetHook(self.branch_config, 'foo', 'branch')
2085
def assertRemoveHook(self, conf, name, section_name=None):
2089
config.OldConfigHooks.install_named_hook('remove', hook, None)
2091
config.OldConfigHooks.uninstall_named_hook, 'remove', None)
2092
self.assertLength(0, calls)
2093
conf.remove_user_option(name, section_name)
2094
self.assertLength(1, calls)
2095
# We can't assert the conf object below as different configs use
2096
# different means to implement remove_user_option and we care only about
2098
self.assertEquals((name,), calls[0][1:])
2100
def test_remove_hook_bazaar(self):
2101
self.assertRemoveHook(self.bazaar_config, 'file')
2103
def test_remove_hook_locations(self):
2104
self.assertRemoveHook(self.locations_config, 'file',
2105
self.locations_config.location)
2107
def test_remove_hook_branch(self):
2108
self.assertRemoveHook(self.branch_config, 'file')
2110
def assertLoadHook(self, name, conf_class, *conf_args):
2114
config.OldConfigHooks.install_named_hook('load', hook, None)
2116
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2117
self.assertLength(0, calls)
2119
conf = conf_class(*conf_args)
2120
# Access an option to trigger a load
2121
conf.get_user_option(name)
2122
self.assertLength(1, calls)
2123
# Since we can't assert about conf, we just use the number of calls ;-/
2125
def test_load_hook_bazaar(self):
2126
self.assertLoadHook('file', config.GlobalConfig)
2128
def test_load_hook_locations(self):
2129
self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
2131
def test_load_hook_branch(self):
2132
self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
2134
def assertSaveHook(self, conf):
2138
config.OldConfigHooks.install_named_hook('save', hook, None)
2140
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2141
self.assertLength(0, calls)
2142
# Setting an option triggers a save
2143
conf.set_user_option('foo', 'bar')
2144
self.assertLength(1, calls)
2145
# Since we can't assert about conf, we just use the number of calls ;-/
2147
def test_save_hook_bazaar(self):
2148
self.assertSaveHook(self.bazaar_config)
2150
def test_save_hook_locations(self):
2151
self.assertSaveHook(self.locations_config)
2153
def test_save_hook_branch(self):
2154
self.assertSaveHook(self.branch_config)
2157
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
2158
"""Tests config hooks for remote configs.
2160
No tests for the remove hook as this is not implemented there.
2164
super(TestOldConfigHooksForRemote, self).setUp()
2165
self.transport_server = test_server.SmartTCPServer_for_testing
2166
create_configs_with_file_option(self)
2168
def assertGetHook(self, conf, name, value):
2172
config.OldConfigHooks.install_named_hook('get', hook, None)
2174
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2175
self.assertLength(0, calls)
2176
actual_value = conf.get_option(name)
2177
self.assertEquals(value, actual_value)
2178
self.assertLength(1, calls)
2179
self.assertEquals((conf, name, value), calls[0])
2181
def test_get_hook_remote_branch(self):
2182
remote_branch = branch.Branch.open(self.get_url('tree'))
2183
self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2185
def test_get_hook_remote_bzrdir(self):
2186
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2187
conf = remote_bzrdir._get_config()
2188
conf.set_option('remotedir', 'file')
2189
self.assertGetHook(conf, 'file', 'remotedir')
2191
def assertSetHook(self, conf, name, value):
2195
config.OldConfigHooks.install_named_hook('set', hook, None)
2197
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2198
self.assertLength(0, calls)
2199
conf.set_option(value, name)
2200
self.assertLength(1, calls)
2201
# We can't assert the conf object below as different configs use
2202
# different means to implement set_user_option and we care only about
2204
self.assertEquals((name, value), calls[0][1:])
2206
def test_set_hook_remote_branch(self):
2207
remote_branch = branch.Branch.open(self.get_url('tree'))
2208
self.addCleanup(remote_branch.lock_write().unlock)
2209
self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
2211
def test_set_hook_remote_bzrdir(self):
2212
remote_branch = branch.Branch.open(self.get_url('tree'))
2213
self.addCleanup(remote_branch.lock_write().unlock)
2214
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2215
self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2217
def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2221
config.OldConfigHooks.install_named_hook('load', hook, None)
2223
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2224
self.assertLength(0, calls)
2226
conf = conf_class(*conf_args)
2227
# Access an option to trigger a load
2228
conf.get_option(name)
2229
self.assertLength(expected_nb_calls, calls)
2230
# Since we can't assert about conf, we just use the number of calls ;-/
2232
def test_load_hook_remote_branch(self):
2233
remote_branch = branch.Branch.open(self.get_url('tree'))
2234
self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2236
def test_load_hook_remote_bzrdir(self):
2237
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2238
# The config file doesn't exist, set an option to force its creation
2239
conf = remote_bzrdir._get_config()
2240
conf.set_option('remotedir', 'file')
2241
# We get one call for the server and one call for the client, this is
2242
# caused by the differences in implementations betwen
2243
# SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
2244
# SmartServerBranchGetConfigFile (in smart/branch.py)
2245
self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
2247
def assertSaveHook(self, conf):
2251
config.OldConfigHooks.install_named_hook('save', hook, None)
2253
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2254
self.assertLength(0, calls)
2255
# Setting an option triggers a save
2256
conf.set_option('foo', 'bar')
2257
self.assertLength(1, calls)
2258
# Since we can't assert about conf, we just use the number of calls ;-/
2260
def test_save_hook_remote_branch(self):
2261
remote_branch = branch.Branch.open(self.get_url('tree'))
2262
self.addCleanup(remote_branch.lock_write().unlock)
2263
self.assertSaveHook(remote_branch._get_config())
2265
def test_save_hook_remote_bzrdir(self):
2266
remote_branch = branch.Branch.open(self.get_url('tree'))
2267
self.addCleanup(remote_branch.lock_write().unlock)
2268
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2269
self.assertSaveHook(remote_bzrdir._get_config())
2272
class TestOption(tests.TestCase):
2274
def test_default_value(self):
2275
opt = config.Option('foo', default='bar')
2276
self.assertEquals('bar', opt.get_default())
2278
def test_default_value_from_env(self):
2279
opt = config.Option('foo', default='bar', default_from_env=['FOO'])
2280
self.overrideEnv('FOO', 'quux')
2281
# Env variable provides a default taking over the option one
2282
self.assertEquals('quux', opt.get_default())
2284
def test_first_default_value_from_env_wins(self):
2285
opt = config.Option('foo', default='bar',
2286
default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
2287
self.overrideEnv('FOO', 'foo')
2288
self.overrideEnv('BAZ', 'baz')
2289
# The first env var set wins
2290
self.assertEquals('foo', opt.get_default())
2292
def test_not_supported_list_default_value(self):
2293
self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
2295
def test_not_supported_object_default_value(self):
2296
self.assertRaises(AssertionError, config.Option, 'foo',
2300
class TestOptionConverterMixin(object):
2302
def assertConverted(self, expected, opt, value):
2303
self.assertEquals(expected, opt.convert_from_unicode(value))
2305
def assertWarns(self, opt, value):
2308
warnings.append(args[0] % args[1:])
2309
self.overrideAttr(trace, 'warning', warning)
2310
self.assertEquals(None, opt.convert_from_unicode(value))
2311
self.assertLength(1, warnings)
2313
'Value "%s" is not valid for "%s"' % (value, opt.name),
2316
def assertErrors(self, opt, value):
2317
self.assertRaises(errors.ConfigOptionValueError,
2318
opt.convert_from_unicode, value)
2320
def assertConvertInvalid(self, opt, invalid_value):
2322
self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2323
opt.invalid = 'warning'
2324
self.assertWarns(opt, invalid_value)
2325
opt.invalid = 'error'
2326
self.assertErrors(opt, invalid_value)
2329
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2331
def get_option(self):
2332
return config.Option('foo', help='A boolean.',
2333
from_unicode=config.bool_from_store)
2335
def test_convert_invalid(self):
2336
opt = self.get_option()
2337
# A string that is not recognized as a boolean
2338
self.assertConvertInvalid(opt, u'invalid-boolean')
2339
# A list of strings is never recognized as a boolean
2340
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2342
def test_convert_valid(self):
2343
opt = self.get_option()
2344
self.assertConverted(True, opt, u'True')
2345
self.assertConverted(True, opt, u'1')
2346
self.assertConverted(False, opt, u'False')
2349
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2351
def get_option(self):
2352
return config.Option('foo', help='An integer.',
2353
from_unicode=config.int_from_store)
2355
def test_convert_invalid(self):
2356
opt = self.get_option()
2357
# A string that is not recognized as an integer
2358
self.assertConvertInvalid(opt, u'forty-two')
2359
# A list of strings is never recognized as an integer
2360
self.assertConvertInvalid(opt, [u'a', u'list'])
2362
def test_convert_valid(self):
2363
opt = self.get_option()
2364
self.assertConverted(16, opt, u'16')
2366
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2368
def get_option(self):
2369
return config.Option('foo', help='A list.',
2370
from_unicode=config.list_from_store)
2372
def test_convert_invalid(self):
2373
# No string is invalid as all forms can be converted to a list
2376
def test_convert_valid(self):
2377
opt = self.get_option()
2378
# An empty string is an empty list
2379
self.assertConverted([], opt, '') # Using a bare str() just in case
2380
self.assertConverted([], opt, u'')
2382
self.assertConverted([u'True'], opt, u'True')
2384
self.assertConverted([u'42'], opt, u'42')
2386
self.assertConverted([u'bar'], opt, u'bar')
2387
# A list remains a list (configObj will turn a string containing commas
2388
# into a list, but that's not what we're testing here)
2389
self.assertConverted([u'foo', u'1', u'True'],
2390
opt, [u'foo', u'1', u'True'])
2393
class TestOptionConverterMixin(object):
2395
def assertConverted(self, expected, opt, value):
2396
self.assertEquals(expected, opt.convert_from_unicode(value))
2398
def assertWarns(self, opt, value):
2401
warnings.append(args[0] % args[1:])
2402
self.overrideAttr(trace, 'warning', warning)
2403
self.assertEquals(None, opt.convert_from_unicode(value))
2404
self.assertLength(1, warnings)
2406
'Value "%s" is not valid for "%s"' % (value, opt.name),
2409
def assertErrors(self, opt, value):
2410
self.assertRaises(errors.ConfigOptionValueError,
2411
opt.convert_from_unicode, value)
2413
def assertConvertInvalid(self, opt, invalid_value):
2415
self.assertEquals(None, opt.convert_from_unicode(invalid_value))
2416
opt.invalid = 'warning'
2417
self.assertWarns(opt, invalid_value)
2418
opt.invalid = 'error'
2419
self.assertErrors(opt, invalid_value)
2422
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
2424
def get_option(self):
2425
return config.Option('foo', help='A boolean.',
2426
from_unicode=config.bool_from_store)
2428
def test_convert_invalid(self):
2429
opt = self.get_option()
2430
# A string that is not recognized as a boolean
2431
self.assertConvertInvalid(opt, u'invalid-boolean')
2432
# A list of strings is never recognized as a boolean
2433
self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2435
def test_convert_valid(self):
2436
opt = self.get_option()
2437
self.assertConverted(True, opt, u'True')
2438
self.assertConverted(True, opt, u'1')
2439
self.assertConverted(False, opt, u'False')
2442
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
2444
def get_option(self):
2445
return config.Option('foo', help='An integer.',
2446
from_unicode=config.int_from_store)
2448
def test_convert_invalid(self):
2449
opt = self.get_option()
2450
# A string that is not recognized as an integer
2451
self.assertConvertInvalid(opt, u'forty-two')
2452
# A list of strings is never recognized as an integer
2453
self.assertConvertInvalid(opt, [u'a', u'list'])
2455
def test_convert_valid(self):
2456
opt = self.get_option()
2457
self.assertConverted(16, opt, u'16')
2460
class TestOptionWithListConverter(tests.TestCase, TestOptionConverterMixin):
2462
def get_option(self):
2463
return config.Option('foo', help='A list.',
2464
from_unicode=config.list_from_store)
2466
def test_convert_invalid(self):
2467
opt = self.get_option()
2468
# We don't even try to convert a list into a list, we only expect
2470
self.assertConvertInvalid(opt, [1])
2471
# No string is invalid as all forms can be converted to a list
2473
def test_convert_valid(self):
2474
opt = self.get_option()
2475
# An empty string is an empty list
2476
self.assertConverted([], opt, '') # Using a bare str() just in case
2477
self.assertConverted([], opt, u'')
2479
self.assertConverted([u'True'], opt, u'True')
2481
self.assertConverted([u'42'], opt, u'42')
2483
self.assertConverted([u'bar'], opt, u'bar')
2486
class TestOptionRegistry(tests.TestCase):
2489
super(TestOptionRegistry, self).setUp()
2490
# Always start with an empty registry
2491
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2492
self.registry = config.option_registry
2494
def test_register(self):
2495
opt = config.Option('foo')
2496
self.registry.register(opt)
2497
self.assertIs(opt, self.registry.get('foo'))
2499
def test_registered_help(self):
2500
opt = config.Option('foo', help='A simple option')
2501
self.registry.register(opt)
2502
self.assertEquals('A simple option', self.registry.get_help('foo'))
2504
lazy_option = config.Option('lazy_foo', help='Lazy help')
2506
def test_register_lazy(self):
2507
self.registry.register_lazy('lazy_foo', self.__module__,
2508
'TestOptionRegistry.lazy_option')
2509
self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2511
def test_registered_lazy_help(self):
2512
self.registry.register_lazy('lazy_foo', self.__module__,
2513
'TestOptionRegistry.lazy_option')
2514
self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2517
class TestRegisteredOptions(tests.TestCase):
2518
"""All registered options should verify some constraints."""
2520
scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2521
in config.option_registry.iteritems()]
2524
super(TestRegisteredOptions, self).setUp()
2525
self.registry = config.option_registry
2527
def test_proper_name(self):
2528
# An option should be registered under its own name, this can't be
2529
# checked at registration time for the lazy ones.
2530
self.assertEquals(self.option_name, self.option.name)
2532
def test_help_is_set(self):
2533
option_help = self.registry.get_help(self.option_name)
2534
self.assertNotEquals(None, option_help)
2535
# Come on, think about the user, he really wants to know what the
2537
self.assertIsNot(None, option_help)
2538
self.assertNotEquals('', option_help)
2541
class TestSection(tests.TestCase):
2543
# FIXME: Parametrize so that all sections produced by Stores run these
2544
# tests -- vila 2011-04-01
2546
def test_get_a_value(self):
2547
a_dict = dict(foo='bar')
2548
section = config.Section('myID', a_dict)
2549
self.assertEquals('bar', section.get('foo'))
2551
def test_get_unknown_option(self):
2553
section = config.Section(None, a_dict)
2554
self.assertEquals('out of thin air',
2555
section.get('foo', 'out of thin air'))
2557
def test_options_is_shared(self):
2559
section = config.Section(None, a_dict)
2560
self.assertIs(a_dict, section.options)
2563
class TestMutableSection(tests.TestCase):
2565
scenarios = [('mutable',
2567
lambda opts: config.MutableSection('myID', opts)},),
2570
lambda opts: config.CommandLineSection(opts)},),
2574
a_dict = dict(foo='bar')
2575
section = self.get_section(a_dict)
2576
section.set('foo', 'new_value')
2577
self.assertEquals('new_value', section.get('foo'))
2578
# The change appears in the shared section
2579
self.assertEquals('new_value', a_dict.get('foo'))
2580
# We keep track of the change
2581
self.assertTrue('foo' in section.orig)
2582
self.assertEquals('bar', section.orig.get('foo'))
2584
def test_set_preserve_original_once(self):
2585
a_dict = dict(foo='bar')
2586
section = self.get_section(a_dict)
2587
section.set('foo', 'first_value')
2588
section.set('foo', 'second_value')
2589
# We keep track of the original value
2590
self.assertTrue('foo' in section.orig)
2591
self.assertEquals('bar', section.orig.get('foo'))
2593
def test_remove(self):
2594
a_dict = dict(foo='bar')
2595
section = self.get_section(a_dict)
2596
section.remove('foo')
2597
# We get None for unknown options via the default value
2598
self.assertEquals(None, section.get('foo'))
2599
# Or we just get the default value
2600
self.assertEquals('unknown', section.get('foo', 'unknown'))
2601
self.assertFalse('foo' in section.options)
2602
# We keep track of the deletion
2603
self.assertTrue('foo' in section.orig)
2604
self.assertEquals('bar', section.orig.get('foo'))
2606
def test_remove_new_option(self):
2608
section = self.get_section(a_dict)
2609
section.set('foo', 'bar')
2610
section.remove('foo')
2611
self.assertFalse('foo' in section.options)
2612
# The option didn't exist initially so it we need to keep track of it
2613
# with a special value
2614
self.assertTrue('foo' in section.orig)
2615
self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2618
class TestCommandLineSection(tests.TestCase):
2621
super(TestCommandLineSection, self).setUp()
2622
self.section = config.CommandLineSection()
2624
def test_no_override(self):
2625
self.section._from_cmdline([])
2626
# FIXME: we want some iterator over all options, failing that, we peek
2627
# under the cover -- vila 2011-09026
2628
self.assertLength(0, self.section.options)
2630
def test_simple_override(self):
2631
self.section._from_cmdline(['a=b'])
2632
self.assertEqual('b', self.section.get('a'))
2634
def test_list_override(self):
2635
self.section._from_cmdline(['l=1,2,3'])
2636
val = self.section.get('l')
2637
self.assertEqual('1,2,3', val)
2638
# Reminder: lists should registered as such explicitely, otherwise the
2639
# conversion needs to be done afterwards.
2640
self.assertEqual(['1', '2', '3'], config.list_from_store(val))
2642
def test_multiple_overrides(self):
2643
self.section._from_cmdline(['a=b', 'x=y'])
2644
self.assertEquals('b', self.section.get('a'))
2645
self.assertEquals('y', self.section.get('x'))
2647
def test_wrong_syntax(self):
2648
self.assertRaises(errors.BzrCommandError,
2649
self.section._from_cmdline, ['a=b', 'c'])
2652
class TestStore(tests.TestCaseWithTransport):
2654
def assertSectionContent(self, expected, section):
2655
"""Assert that some options have the proper values in a section."""
2656
expected_name, expected_options = expected
2657
self.assertEquals(expected_name, section.id)
2660
dict([(k, section.get(k)) for k in expected_options.keys()]))
2663
class TestReadonlyStore(TestStore):
2665
scenarios = [(key, {'get_store': builder}) for key, builder
2666
in config.test_store_builder_registry.iteritems()]
2668
def test_building_delays_load(self):
2669
store = self.get_store(self)
2670
self.assertEquals(False, store.is_loaded())
2671
store._load_from_string('')
2672
self.assertEquals(True, store.is_loaded())
2674
def test_get_no_sections_for_empty(self):
2675
store = self.get_store(self)
2676
store._load_from_string('')
2677
self.assertEquals([], list(store.get_sections()))
2679
def test_get_default_section(self):
2680
store = self.get_store(self)
2681
store._load_from_string('foo=bar')
2682
sections = list(store.get_sections())
2683
self.assertLength(1, sections)
2684
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2686
def test_get_named_section(self):
2687
store = self.get_store(self)
2688
store._load_from_string('[baz]\nfoo=bar')
2689
sections = list(store.get_sections())
2690
self.assertLength(1, sections)
2691
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2693
def test_load_from_string_fails_for_non_empty_store(self):
2694
store = self.get_store(self)
2695
store._load_from_string('foo=bar')
2696
self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2699
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2700
"""Simulate loading a config store with content of various encodings.
2702
All files produced by bzr are in utf8 content.
2704
Users may modify them manually and end up with a file that can't be
2705
loaded. We need to issue proper error messages in this case.
2708
invalid_utf8_char = '\xff'
2710
def test_load_utf8(self):
2711
"""Ensure we can load an utf8-encoded file."""
2712
t = self.get_transport()
2713
# From http://pad.lv/799212
2714
unicode_user = u'b\N{Euro Sign}ar'
2715
unicode_content = u'user=%s' % (unicode_user,)
2716
utf8_content = unicode_content.encode('utf8')
2717
# Store the raw content in the config file
2718
t.put_bytes('foo.conf', utf8_content)
2719
store = config.IniFileStore(t, 'foo.conf')
2721
stack = config.Stack([store.get_sections], store)
2722
self.assertEquals(unicode_user, stack.get('user'))
2724
def test_load_non_ascii(self):
2725
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2726
t = self.get_transport()
2727
t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2728
store = config.IniFileStore(t, 'foo.conf')
2729
self.assertRaises(errors.ConfigContentError, store.load)
2731
def test_load_erroneous_content(self):
2732
"""Ensure we display a proper error on content that can't be parsed."""
2733
t = self.get_transport()
2734
t.put_bytes('foo.conf', '[open_section\n')
2735
store = config.IniFileStore(t, 'foo.conf')
2736
self.assertRaises(errors.ParseConfigError, store.load)
2738
def test_load_permission_denied(self):
2739
"""Ensure we get warned when trying to load an inaccessible file."""
2742
warnings.append(args[0] % args[1:])
2743
self.overrideAttr(trace, 'warning', warning)
2745
t = self.get_transport()
2747
def get_bytes(relpath):
2748
raise errors.PermissionDenied(relpath, "")
2749
t.get_bytes = get_bytes
2750
store = config.IniFileStore(t, 'foo.conf')
2751
self.assertRaises(errors.PermissionDenied, store.load)
2754
[u'Permission denied while trying to load configuration store %s.'
2755
% store.external_url()])
2758
class TestIniConfigContent(tests.TestCaseWithTransport):
2759
"""Simulate loading a IniBasedConfig with content of various encodings.
2761
All files produced by bzr are in utf8 content.
2763
Users may modify them manually and end up with a file that can't be
2764
loaded. We need to issue proper error messages in this case.
2767
invalid_utf8_char = '\xff'
2769
def test_load_utf8(self):
2770
"""Ensure we can load an utf8-encoded file."""
2771
# From http://pad.lv/799212
2772
unicode_user = u'b\N{Euro Sign}ar'
2773
unicode_content = u'user=%s' % (unicode_user,)
2774
utf8_content = unicode_content.encode('utf8')
2775
# Store the raw content in the config file
2776
with open('foo.conf', 'wb') as f:
2777
f.write(utf8_content)
2778
conf = config.IniBasedConfig(file_name='foo.conf')
2779
self.assertEquals(unicode_user, conf.get_user_option('user'))
2781
def test_load_badly_encoded_content(self):
2782
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2783
with open('foo.conf', 'wb') as f:
2784
f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2785
conf = config.IniBasedConfig(file_name='foo.conf')
2786
self.assertRaises(errors.ConfigContentError, conf._get_parser)
2788
def test_load_erroneous_content(self):
2789
"""Ensure we display a proper error on content that can't be parsed."""
2790
with open('foo.conf', 'wb') as f:
2791
f.write('[open_section\n')
2792
conf = config.IniBasedConfig(file_name='foo.conf')
2793
self.assertRaises(errors.ParseConfigError, conf._get_parser)
2796
class TestMutableStore(TestStore):
2798
scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2799
in config.test_store_builder_registry.iteritems()]
2802
super(TestMutableStore, self).setUp()
2803
self.transport = self.get_transport()
2805
def has_store(self, store):
2806
store_basename = urlutils.relative_url(self.transport.external_url(),
2807
store.external_url())
2808
return self.transport.has(store_basename)
2810
def test_save_empty_creates_no_file(self):
2811
# FIXME: There should be a better way than relying on the test
2812
# parametrization to identify branch.conf -- vila 2011-0526
2813
if self.store_id in ('branch', 'remote_branch'):
2814
raise tests.TestNotApplicable(
2815
'branch.conf is *always* created when a branch is initialized')
2816
store = self.get_store(self)
2818
self.assertEquals(False, self.has_store(store))
2820
def test_save_emptied_succeeds(self):
2821
store = self.get_store(self)
2822
store._load_from_string('foo=bar\n')
2823
section = store.get_mutable_section(None)
2824
section.remove('foo')
2826
self.assertEquals(True, self.has_store(store))
2827
modified_store = self.get_store(self)
2828
sections = list(modified_store.get_sections())
2829
self.assertLength(0, sections)
2831
def test_save_with_content_succeeds(self):
2832
# FIXME: There should be a better way than relying on the test
2833
# parametrization to identify branch.conf -- vila 2011-0526
2834
if self.store_id in ('branch', 'remote_branch'):
2835
raise tests.TestNotApplicable(
2836
'branch.conf is *always* created when a branch is initialized')
2837
store = self.get_store(self)
2838
store._load_from_string('foo=bar\n')
2839
self.assertEquals(False, self.has_store(store))
2841
self.assertEquals(True, self.has_store(store))
2842
modified_store = self.get_store(self)
2843
sections = list(modified_store.get_sections())
2844
self.assertLength(1, sections)
2845
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2847
def test_set_option_in_empty_store(self):
2848
store = self.get_store(self)
2849
section = store.get_mutable_section(None)
2850
section.set('foo', 'bar')
2852
modified_store = self.get_store(self)
2853
sections = list(modified_store.get_sections())
2854
self.assertLength(1, sections)
2855
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2857
def test_set_option_in_default_section(self):
2858
store = self.get_store(self)
2859
store._load_from_string('')
2860
section = store.get_mutable_section(None)
2861
section.set('foo', 'bar')
2863
modified_store = self.get_store(self)
2864
sections = list(modified_store.get_sections())
2865
self.assertLength(1, sections)
2866
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2868
def test_set_option_in_named_section(self):
2869
store = self.get_store(self)
2870
store._load_from_string('')
2871
section = store.get_mutable_section('baz')
2872
section.set('foo', 'bar')
2874
modified_store = self.get_store(self)
2875
sections = list(modified_store.get_sections())
2876
self.assertLength(1, sections)
2877
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2879
def test_load_hook(self):
2880
# We first needs to ensure that the store exists
2881
store = self.get_store(self)
2882
section = store.get_mutable_section('baz')
2883
section.set('foo', 'bar')
2885
# Now we can try to load it
2886
store = self.get_store(self)
2890
config.ConfigHooks.install_named_hook('load', hook, None)
2891
self.assertLength(0, calls)
2893
self.assertLength(1, calls)
2894
self.assertEquals((store,), calls[0])
2896
def test_save_hook(self):
2900
config.ConfigHooks.install_named_hook('save', hook, None)
2901
self.assertLength(0, calls)
2902
store = self.get_store(self)
2903
section = store.get_mutable_section('baz')
2904
section.set('foo', 'bar')
2906
self.assertLength(1, calls)
2907
self.assertEquals((store,), calls[0])
2910
class TestIniFileStore(TestStore):
2912
def test_loading_unknown_file_fails(self):
2913
store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
2914
self.assertRaises(errors.NoSuchFile, store.load)
2916
def test_invalid_content(self):
2917
store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2918
self.assertEquals(False, store.is_loaded())
2919
exc = self.assertRaises(
2920
errors.ParseConfigError, store._load_from_string,
2921
'this is invalid !')
2922
self.assertEndsWith(exc.filename, 'foo.conf')
2923
# And the load failed
2924
self.assertEquals(False, store.is_loaded())
2926
def test_get_embedded_sections(self):
2927
# A more complicated example (which also shows that section names and
2928
# option names share the same name space...)
2929
# FIXME: This should be fixed by forbidding dicts as values ?
2930
# -- vila 2011-04-05
2931
store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2932
store._load_from_string('''
2936
foo_in_DEFAULT=foo_DEFAULT
2944
sections = list(store.get_sections())
2945
self.assertLength(4, sections)
2946
# The default section has no name.
2947
# List values are provided as strings and need to be explicitly
2948
# converted by specifying from_unicode=list_from_store at option
2950
self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
2952
self.assertSectionContent(
2953
('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2954
self.assertSectionContent(
2955
('bar', {'foo_in_bar': 'barbar'}), sections[2])
2956
# sub sections are provided as embedded dicts.
2957
self.assertSectionContent(
2958
('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2962
class TestLockableIniFileStore(TestStore):
2964
def test_create_store_in_created_dir(self):
2965
self.assertPathDoesNotExist('dir')
2966
t = self.get_transport('dir/subdir')
2967
store = config.LockableIniFileStore(t, 'foo.conf')
2968
store.get_mutable_section(None).set('foo', 'bar')
2970
self.assertPathExists('dir/subdir')
2973
class TestConcurrentStoreUpdates(TestStore):
2974
"""Test that Stores properly handle conccurent updates.
2976
New Store implementation may fail some of these tests but until such
2977
implementations exist it's hard to properly filter them from the scenarios
2978
applied here. If you encounter such a case, contact the bzr devs.
2981
scenarios = [(key, {'get_stack': builder}) for key, builder
2982
in config.test_stack_builder_registry.iteritems()]
2985
super(TestConcurrentStoreUpdates, self).setUp()
2986
self._content = 'one=1\ntwo=2\n'
2987
self.stack = self.get_stack(self)
2988
if not isinstance(self.stack, config._CompatibleStack):
2989
raise tests.TestNotApplicable(
2990
'%s is not meant to be compatible with the old config design'
2992
self.stack.store._load_from_string(self._content)
2994
self.stack.store.save()
2996
def test_simple_read_access(self):
2997
self.assertEquals('1', self.stack.get('one'))
2999
def test_simple_write_access(self):
3000
self.stack.set('one', 'one')
3001
self.assertEquals('one', self.stack.get('one'))
3003
def test_listen_to_the_last_speaker(self):
3005
c2 = self.get_stack(self)
3006
c1.set('one', 'ONE')
3007
c2.set('two', 'TWO')
3008
self.assertEquals('ONE', c1.get('one'))
3009
self.assertEquals('TWO', c2.get('two'))
3010
# The second update respect the first one
3011
self.assertEquals('ONE', c2.get('one'))
3013
def test_last_speaker_wins(self):
3014
# If the same config is not shared, the same variable modified twice
3015
# can only see a single result.
3017
c2 = self.get_stack(self)
3020
self.assertEquals('c2', c2.get('one'))
3021
# The first modification is still available until another refresh
3023
self.assertEquals('c1', c1.get('one'))
3024
c1.set('two', 'done')
3025
self.assertEquals('c2', c1.get('one'))
3027
def test_writes_are_serialized(self):
3029
c2 = self.get_stack(self)
3031
# We spawn a thread that will pause *during* the config saving.
3032
before_writing = threading.Event()
3033
after_writing = threading.Event()
3034
writing_done = threading.Event()
3035
c1_save_without_locking_orig = c1.store.save_without_locking
3036
def c1_save_without_locking():
3037
before_writing.set()
3038
c1_save_without_locking_orig()
3039
# The lock is held. We wait for the main thread to decide when to
3041
after_writing.wait()
3042
c1.store.save_without_locking = c1_save_without_locking
3046
t1 = threading.Thread(target=c1_set)
3047
# Collect the thread after the test
3048
self.addCleanup(t1.join)
3049
# Be ready to unblock the thread if the test goes wrong
3050
self.addCleanup(after_writing.set)
3052
before_writing.wait()
3053
self.assertRaises(errors.LockContention,
3054
c2.set, 'one', 'c2')
3055
self.assertEquals('c1', c1.get('one'))
3056
# Let the lock be released
3060
self.assertEquals('c2', c2.get('one'))
3062
def test_read_while_writing(self):
3064
# We spawn a thread that will pause *during* the write
3065
ready_to_write = threading.Event()
3066
do_writing = threading.Event()
3067
writing_done = threading.Event()
3068
# We override the _save implementation so we know the store is locked
3069
c1_save_without_locking_orig = c1.store.save_without_locking
3070
def c1_save_without_locking():
3071
ready_to_write.set()
3072
# The lock is held. We wait for the main thread to decide when to
3075
c1_save_without_locking_orig()
3077
c1.store.save_without_locking = c1_save_without_locking
3080
t1 = threading.Thread(target=c1_set)
3081
# Collect the thread after the test
3082
self.addCleanup(t1.join)
3083
# Be ready to unblock the thread if the test goes wrong
3084
self.addCleanup(do_writing.set)
3086
# Ensure the thread is ready to write
3087
ready_to_write.wait()
3088
self.assertEquals('c1', c1.get('one'))
3089
# If we read during the write, we get the old value
3090
c2 = self.get_stack(self)
3091
self.assertEquals('1', c2.get('one'))
3092
# Let the writing occur and ensure it occurred
3095
# Now we get the updated value
3096
c3 = self.get_stack(self)
3097
self.assertEquals('c1', c3.get('one'))
3099
# FIXME: It may be worth looking into removing the lock dir when it's not
3100
# needed anymore and look at possible fallouts for concurrent lockers. This
3101
# will matter if/when we use config files outside of bazaar directories
3102
# (.bazaar or .bzr) -- vila 20110-04-111
3105
class TestSectionMatcher(TestStore):
3107
scenarios = [('location', {'matcher': config.LocationMatcher}),
3108
('id', {'matcher': config.NameMatcher}),]
3110
def get_store(self, file_name):
3111
return config.IniFileStore(self.get_readonly_transport(), file_name)
3113
def test_no_matches_for_empty_stores(self):
3114
store = self.get_store('foo.conf')
3115
store._load_from_string('')
3116
matcher = self.matcher(store, '/bar')
3117
self.assertEquals([], list(matcher.get_sections()))
3119
def test_build_doesnt_load_store(self):
3120
store = self.get_store('foo.conf')
3121
matcher = self.matcher(store, '/bar')
3122
self.assertFalse(store.is_loaded())
3125
class TestLocationSection(tests.TestCase):
3127
def get_section(self, options, extra_path):
3128
section = config.Section('foo', options)
3129
# We don't care about the length so we use '0'
3130
return config.LocationSection(section, 0, extra_path)
3132
def test_simple_option(self):
3133
section = self.get_section({'foo': 'bar'}, '')
3134
self.assertEquals('bar', section.get('foo'))
3136
def test_option_with_extra_path(self):
3137
section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
3139
self.assertEquals('bar/baz', section.get('foo'))
3141
def test_invalid_policy(self):
3142
section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
3144
# invalid policies are ignored
3145
self.assertEquals('bar', section.get('foo'))
3148
class TestLocationMatcher(TestStore):
3150
def get_store(self, file_name):
3151
return config.IniFileStore(self.get_readonly_transport(), file_name)
3153
def test_unrelated_section_excluded(self):
3154
store = self.get_store('foo.conf')
3155
store._load_from_string('''
3163
section=/foo/bar/baz
3167
self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3169
[section.id for section in store.get_sections()])
3170
matcher = config.LocationMatcher(store, '/foo/bar/quux')
3171
sections = list(matcher.get_sections())
3172
self.assertEquals([3, 2],
3173
[section.length for section in sections])
3174
self.assertEquals(['/foo/bar', '/foo'],
3175
[section.id for section in sections])
3176
self.assertEquals(['quux', 'bar/quux'],
3177
[section.extra_path for section in sections])
3179
def test_more_specific_sections_first(self):
3180
store = self.get_store('foo.conf')
3181
store._load_from_string('''
3187
self.assertEquals(['/foo', '/foo/bar'],
3188
[section.id for section in store.get_sections()])
3189
matcher = config.LocationMatcher(store, '/foo/bar/baz')
3190
sections = list(matcher.get_sections())
3191
self.assertEquals([3, 2],
3192
[section.length for section in sections])
3193
self.assertEquals(['/foo/bar', '/foo'],
3194
[section.id for section in sections])
3195
self.assertEquals(['baz', 'bar/baz'],
3196
[section.extra_path for section in sections])
3198
def test_appendpath_in_no_name_section(self):
3199
# It's a bit weird to allow appendpath in a no-name section, but
3200
# someone may found a use for it
3201
store = self.get_store('foo.conf')
3202
store._load_from_string('''
3204
foo:policy = appendpath
3206
matcher = config.LocationMatcher(store, 'dir/subdir')
3207
sections = list(matcher.get_sections())
3208
self.assertLength(1, sections)
3209
self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
3211
def test_file_urls_are_normalized(self):
3212
store = self.get_store('foo.conf')
3213
if sys.platform == 'win32':
3214
expected_url = 'file:///C:/dir/subdir'
3215
expected_location = 'C:/dir/subdir'
3217
expected_url = 'file:///dir/subdir'
3218
expected_location = '/dir/subdir'
3219
matcher = config.LocationMatcher(store, expected_url)
3220
self.assertEquals(expected_location, matcher.location)
3223
class TestNameMatcher(TestStore):
3226
super(TestNameMatcher, self).setUp()
3227
self.store = config.IniFileStore(self.get_readonly_transport(),
3229
self.store._load_from_string('''
3238
def get_matching_sections(self, name):
3239
matcher = config.NameMatcher(self.store, name)
3240
return list(matcher.get_sections())
3242
def test_matching(self):
3243
sections = self.get_matching_sections('foo')
3244
self.assertLength(1, sections)
3245
self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3247
def test_not_matching(self):
3248
sections = self.get_matching_sections('baz')
3249
self.assertLength(0, sections)
3252
class TestStackGet(tests.TestCase):
3254
# FIXME: This should be parametrized for all known Stack or dedicated
3255
# paramerized tests created to avoid bloating -- vila 2011-03-31
3257
def overrideOptionRegistry(self):
3258
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3260
def test_single_config_get(self):
3261
conf = dict(foo='bar')
3262
conf_stack = config.Stack([conf])
3263
self.assertEquals('bar', conf_stack.get('foo'))
3265
def test_get_with_registered_default_value(self):
3266
conf_stack = config.Stack([dict()])
3267
opt = config.Option('foo', default='bar')
3268
self.overrideOptionRegistry()
3269
config.option_registry.register('foo', opt)
3270
self.assertEquals('bar', conf_stack.get('foo'))
3272
def test_get_without_registered_default_value(self):
3273
conf_stack = config.Stack([dict()])
3274
opt = config.Option('foo')
3275
self.overrideOptionRegistry()
3276
config.option_registry.register('foo', opt)
3277
self.assertEquals(None, conf_stack.get('foo'))
3279
def test_get_without_default_value_for_not_registered(self):
3280
conf_stack = config.Stack([dict()])
3281
opt = config.Option('foo')
3282
self.overrideOptionRegistry()
3283
self.assertEquals(None, conf_stack.get('foo'))
3285
def test_get_first_definition(self):
3286
conf1 = dict(foo='bar')
3287
conf2 = dict(foo='baz')
3288
conf_stack = config.Stack([conf1, conf2])
3289
self.assertEquals('bar', conf_stack.get('foo'))
3291
def test_get_embedded_definition(self):
3292
conf1 = dict(yy='12')
3293
conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
3294
conf_stack = config.Stack([conf1, conf2])
3295
self.assertEquals('baz', conf_stack.get('foo'))
3297
def test_get_for_empty_section_callable(self):
3298
conf_stack = config.Stack([lambda : []])
3299
self.assertEquals(None, conf_stack.get('foo'))
3301
def test_get_for_broken_callable(self):
3302
# Trying to use and invalid callable raises an exception on first use
3303
conf_stack = config.Stack([lambda : object()])
3304
self.assertRaises(TypeError, conf_stack.get, 'foo')
3307
class TestStackWithTransport(tests.TestCaseWithTransport):
3309
scenarios = [(key, {'get_stack': builder}) for key, builder
3310
in config.test_stack_builder_registry.iteritems()]
3313
class TestConcreteStacks(TestStackWithTransport):
3315
def test_build_stack(self):
3316
# Just a smoke test to help debug builders
3317
stack = self.get_stack(self)
3320
class TestStackGet(TestStackWithTransport):
3323
super(TestStackGet, self).setUp()
3324
self.conf = self.get_stack(self)
3326
def test_get_for_empty_stack(self):
3327
self.assertEquals(None, self.conf.get('foo'))
3329
def test_get_hook(self):
3330
self.conf.store._load_from_string('foo=bar')
3334
config.ConfigHooks.install_named_hook('get', hook, None)
3335
self.assertLength(0, calls)
3336
value = self.conf.get('foo')
3337
self.assertEquals('bar', value)
3338
self.assertLength(1, calls)
3339
self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
3342
class TestStackGetWithConverter(TestStackGet):
3345
super(TestStackGetWithConverter, self).setUp()
3346
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3347
self.registry = config.option_registry
3349
def register_bool_option(self, name, default=None, default_from_env=None):
3350
b = config.Option(name, help='A boolean.',
3351
default=default, default_from_env=default_from_env,
3352
from_unicode=config.bool_from_store)
3353
self.registry.register(b)
3355
def test_get_default_bool_None(self):
3356
self.register_bool_option('foo')
3357
self.assertEquals(None, self.conf.get('foo'))
3359
def test_get_default_bool_True(self):
3360
self.register_bool_option('foo', u'True')
3361
self.assertEquals(True, self.conf.get('foo'))
3363
def test_get_default_bool_False(self):
3364
self.register_bool_option('foo', False)
3365
self.assertEquals(False, self.conf.get('foo'))
3367
def test_get_default_bool_False_as_string(self):
3368
self.register_bool_option('foo', u'False')
3369
self.assertEquals(False, self.conf.get('foo'))
3371
def test_get_default_bool_from_env_converted(self):
3372
self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3373
self.overrideEnv('FOO', 'False')
3374
self.assertEquals(False, self.conf.get('foo'))
3376
def test_get_default_bool_when_conversion_fails(self):
3377
self.register_bool_option('foo', default='True')
3378
self.conf.store._load_from_string('foo=invalid boolean')
3379
self.assertEquals(True, self.conf.get('foo'))
3381
def register_integer_option(self, name,
3382
default=None, default_from_env=None):
3383
i = config.Option(name, help='An integer.',
3384
default=default, default_from_env=default_from_env,
3385
from_unicode=config.int_from_store)
3386
self.registry.register(i)
3388
def test_get_default_integer_None(self):
3389
self.register_integer_option('foo')
3390
self.assertEquals(None, self.conf.get('foo'))
3392
def test_get_default_integer(self):
3393
self.register_integer_option('foo', 42)
3394
self.assertEquals(42, self.conf.get('foo'))
3396
def test_get_default_integer_as_string(self):
3397
self.register_integer_option('foo', u'42')
3398
self.assertEquals(42, self.conf.get('foo'))
3400
def test_get_default_integer_from_env(self):
3401
self.register_integer_option('foo', default_from_env=['FOO'])
3402
self.overrideEnv('FOO', '18')
3403
self.assertEquals(18, self.conf.get('foo'))
3405
def test_get_default_integer_when_conversion_fails(self):
3406
self.register_integer_option('foo', default='12')
3407
self.conf.store._load_from_string('foo=invalid integer')
3408
self.assertEquals(12, self.conf.get('foo'))
3410
def register_list_option(self, name, default=None, default_from_env=None):
3411
l = config.Option(name, help='A list.',
3412
default=default, default_from_env=default_from_env,
3413
from_unicode=config.list_from_store)
3414
self.registry.register(l)
3416
def test_get_default_list_None(self):
3417
self.register_list_option('foo')
3418
self.assertEquals(None, self.conf.get('foo'))
3420
def test_get_default_list_empty(self):
3421
self.register_list_option('foo', '')
3422
self.assertEquals([], self.conf.get('foo'))
3424
def test_get_default_list_from_env(self):
3425
self.register_list_option('foo', default_from_env=['FOO'])
3426
self.overrideEnv('FOO', '')
3427
self.assertEquals([], self.conf.get('foo'))
3429
def test_get_with_list_converter_no_item(self):
3430
self.register_list_option('foo', None)
3431
self.conf.store._load_from_string('foo=,')
3432
self.assertEquals([], self.conf.get('foo'))
3434
def test_get_with_list_converter_many_items(self):
3435
self.register_list_option('foo', None)
3436
self.conf.store._load_from_string('foo=m,o,r,e')
3437
self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
3439
def test_get_with_list_converter_embedded_spaces_many_items(self):
3440
self.register_list_option('foo', None)
3441
self.conf.store._load_from_string('foo=" bar", "baz "')
3442
self.assertEquals([' bar', 'baz '], self.conf.get('foo'))
3444
def test_get_with_list_converter_stripped_spaces_many_items(self):
3445
self.register_list_option('foo', None)
3446
self.conf.store._load_from_string('foo= bar , baz ')
3447
self.assertEquals(['bar', 'baz'], self.conf.get('foo'))
3450
class TestStackExpandOptions(tests.TestCaseWithTransport):
3453
super(TestStackExpandOptions, self).setUp()
3454
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3455
self.registry = config.option_registry
3456
self.conf = build_branch_stack(self)
3458
def assertExpansion(self, expected, string, env=None):
3459
self.assertEquals(expected, self.conf.expand_options(string, env))
3461
def test_no_expansion(self):
3462
self.assertExpansion('foo', 'foo')
3464
def test_expand_default_value(self):
3465
self.conf.store._load_from_string('bar=baz')
3466
self.registry.register(config.Option('foo', default=u'{bar}'))
3467
self.assertEquals('baz', self.conf.get('foo', expand=True))
3469
def test_expand_default_from_env(self):
3470
self.conf.store._load_from_string('bar=baz')
3471
self.registry.register(config.Option('foo', default_from_env=['FOO']))
3472
self.overrideEnv('FOO', '{bar}')
3473
self.assertEquals('baz', self.conf.get('foo', expand=True))
3475
def test_expand_default_on_failed_conversion(self):
3476
self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
3477
self.registry.register(
3478
config.Option('foo', default=u'{bar}',
3479
from_unicode=config.int_from_store))
3480
self.assertEquals(42, self.conf.get('foo', expand=True))
3482
def test_env_adding_options(self):
3483
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3485
def test_env_overriding_options(self):
3486
self.conf.store._load_from_string('foo=baz')
3487
self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3489
def test_simple_ref(self):
3490
self.conf.store._load_from_string('foo=xxx')
3491
self.assertExpansion('xxx', '{foo}')
3493
def test_unknown_ref(self):
3494
self.assertRaises(errors.ExpandingUnknownOption,
3495
self.conf.expand_options, '{foo}')
3497
def test_indirect_ref(self):
3498
self.conf.store._load_from_string('''
3502
self.assertExpansion('xxx', '{bar}')
3504
def test_embedded_ref(self):
3505
self.conf.store._load_from_string('''
3509
self.assertExpansion('xxx', '{{bar}}')
3511
def test_simple_loop(self):
3512
self.conf.store._load_from_string('foo={foo}')
3513
self.assertRaises(errors.OptionExpansionLoop,
3514
self.conf.expand_options, '{foo}')
3516
def test_indirect_loop(self):
3517
self.conf.store._load_from_string('''
3521
e = self.assertRaises(errors.OptionExpansionLoop,
3522
self.conf.expand_options, '{foo}')
3523
self.assertEquals('foo->bar->baz', e.refs)
3524
self.assertEquals('{foo}', e.string)
3526
def test_list(self):
3527
self.conf.store._load_from_string('''
3531
list={foo},{bar},{baz}
3533
self.registry.register(
3534
config.Option('list', from_unicode=config.list_from_store))
3535
self.assertEquals(['start', 'middle', 'end'],
3536
self.conf.get('list', expand=True))
3538
def test_cascading_list(self):
3539
self.conf.store._load_from_string('''
3545
self.registry.register(
3546
config.Option('list', from_unicode=config.list_from_store))
3547
self.assertEquals(['start', 'middle', 'end'],
3548
self.conf.get('list', expand=True))
3550
def test_pathologically_hidden_list(self):
3551
self.conf.store._load_from_string('''
3557
hidden={start}{middle}{end}
3559
# What matters is what the registration says, the conversion happens
3560
# only after all expansions have been performed
3561
self.registry.register(
3562
config.Option('hidden', from_unicode=config.list_from_store))
3563
self.assertEquals(['bin', 'go'],
3564
self.conf.get('hidden', expand=True))
3567
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3570
super(TestStackCrossSectionsExpand, self).setUp()
3572
def get_config(self, location, string):
3575
# Since we don't save the config we won't strictly require to inherit
3576
# from TestCaseInTempDir, but an error occurs so quickly...
3577
c = config.LocationStack(location)
3578
c.store._load_from_string(string)
3581
def test_dont_cross_unrelated_section(self):
3582
c = self.get_config('/another/branch/path','''
3587
[/another/branch/path]
3590
self.assertRaises(errors.ExpandingUnknownOption,
3591
c.get, 'bar', expand=True)
3593
def test_cross_related_sections(self):
3594
c = self.get_config('/project/branch/path','''
3598
[/project/branch/path]
3601
self.assertEquals('quux', c.get('bar', expand=True))
3604
class TestStackSet(TestStackWithTransport):
3606
def test_simple_set(self):
3607
conf = self.get_stack(self)
3608
conf.store._load_from_string('foo=bar')
3609
self.assertEquals('bar', conf.get('foo'))
3610
conf.set('foo', 'baz')
3611
# Did we get it back ?
3612
self.assertEquals('baz', conf.get('foo'))
3614
def test_set_creates_a_new_section(self):
3615
conf = self.get_stack(self)
3616
conf.set('foo', 'baz')
3617
self.assertEquals, 'baz', conf.get('foo')
3619
def test_set_hook(self):
3623
config.ConfigHooks.install_named_hook('set', hook, None)
3624
self.assertLength(0, calls)
3625
conf = self.get_stack(self)
3626
conf.set('foo', 'bar')
3627
self.assertLength(1, calls)
3628
self.assertEquals((conf, 'foo', 'bar'), calls[0])
3631
class TestStackRemove(TestStackWithTransport):
3633
def test_remove_existing(self):
3634
conf = self.get_stack(self)
3635
conf.store._load_from_string('foo=bar')
3636
self.assertEquals('bar', conf.get('foo'))
3638
# Did we get it back ?
3639
self.assertEquals(None, conf.get('foo'))
3641
def test_remove_unknown(self):
3642
conf = self.get_stack(self)
3643
self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3645
def test_remove_hook(self):
3649
config.ConfigHooks.install_named_hook('remove', hook, None)
3650
self.assertLength(0, calls)
3651
conf = self.get_stack(self)
3652
conf.store._load_from_string('foo=bar')
3654
self.assertLength(1, calls)
3655
self.assertEquals((conf, 'foo'), calls[0])
3658
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3661
super(TestConfigGetOptions, self).setUp()
3662
create_configs(self)
3664
def test_no_variable(self):
3665
# Using branch should query branch, locations and bazaar
3666
self.assertOptions([], self.branch_config)
3668
def test_option_in_bazaar(self):
3669
self.bazaar_config.set_user_option('file', 'bazaar')
3670
self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
3673
def test_option_in_locations(self):
3674
self.locations_config.set_user_option('file', 'locations')
3676
[('file', 'locations', self.tree.basedir, 'locations')],
3677
self.locations_config)
3679
def test_option_in_branch(self):
3680
self.branch_config.set_user_option('file', 'branch')
3681
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
3684
def test_option_in_bazaar_and_branch(self):
3685
self.bazaar_config.set_user_option('file', 'bazaar')
3686
self.branch_config.set_user_option('file', 'branch')
3687
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
3688
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3691
def test_option_in_branch_and_locations(self):
3692
# Hmm, locations override branch :-/
3693
self.locations_config.set_user_option('file', 'locations')
3694
self.branch_config.set_user_option('file', 'branch')
3696
[('file', 'locations', self.tree.basedir, 'locations'),
3697
('file', 'branch', 'DEFAULT', 'branch'),],
3700
def test_option_in_bazaar_locations_and_branch(self):
3701
self.bazaar_config.set_user_option('file', 'bazaar')
3702
self.locations_config.set_user_option('file', 'locations')
3703
self.branch_config.set_user_option('file', 'branch')
3705
[('file', 'locations', self.tree.basedir, 'locations'),
3706
('file', 'branch', 'DEFAULT', 'branch'),
3707
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3711
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
3714
super(TestConfigRemoveOption, self).setUp()
3715
create_configs_with_file_option(self)
3717
def test_remove_in_locations(self):
3718
self.locations_config.remove_user_option('file', self.tree.basedir)
3720
[('file', 'branch', 'DEFAULT', 'branch'),
3721
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3724
def test_remove_in_branch(self):
3725
self.branch_config.remove_user_option('file')
3727
[('file', 'locations', self.tree.basedir, 'locations'),
3728
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3731
def test_remove_in_bazaar(self):
3732
self.bazaar_config.remove_user_option('file')
3734
[('file', 'locations', self.tree.basedir, 'locations'),
3735
('file', 'branch', 'DEFAULT', 'branch'),],
3739
class TestConfigGetSections(tests.TestCaseWithTransport):
3742
super(TestConfigGetSections, self).setUp()
3743
create_configs(self)
3745
def assertSectionNames(self, expected, conf, name=None):
3746
"""Check which sections are returned for a given config.
3748
If fallback configurations exist their sections can be included.
3750
:param expected: A list of section names.
3752
:param conf: The configuration that will be queried.
3754
:param name: An optional section name that will be passed to
3757
sections = list(conf._get_sections(name))
3758
self.assertLength(len(expected), sections)
3759
self.assertEqual(expected, [name for name, _, _ in sections])
3761
def test_bazaar_default_section(self):
3762
self.assertSectionNames(['DEFAULT'], self.bazaar_config)
3764
def test_locations_default_section(self):
3765
# No sections are defined in an empty file
3766
self.assertSectionNames([], self.locations_config)
3768
def test_locations_named_section(self):
3769
self.locations_config.set_user_option('file', 'locations')
3770
self.assertSectionNames([self.tree.basedir], self.locations_config)
3772
def test_locations_matching_sections(self):
3773
loc_config = self.locations_config
3774
loc_config.set_user_option('file', 'locations')
3775
# We need to cheat a bit here to create an option in sections above and
3776
# below the 'location' one.
3777
parser = loc_config._get_parser()
3778
# locations.cong deals with '/' ignoring native os.sep
3779
location_names = self.tree.basedir.split('/')
3780
parent = '/'.join(location_names[:-1])
3781
child = '/'.join(location_names + ['child'])
3783
parser[parent]['file'] = 'parent'
3785
parser[child]['file'] = 'child'
3786
self.assertSectionNames([self.tree.basedir, parent], loc_config)
3788
def test_branch_data_default_section(self):
3789
self.assertSectionNames([None],
3790
self.branch_config._get_branch_data_config())
3792
def test_branch_default_sections(self):
3793
# No sections are defined in an empty locations file
3794
self.assertSectionNames([None, 'DEFAULT'],
3796
# Unless we define an option
3797
self.branch_config._get_location_config().set_user_option(
3798
'file', 'locations')
3799
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
3802
def test_bazaar_named_section(self):
3803
# We need to cheat as the API doesn't give direct access to sections
3804
# other than DEFAULT.
3805
self.bazaar_config.set_alias('bazaar', 'bzr')
3806
self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
1315
3809
class TestAuthenticationConfigFile(tests.TestCase):
1316
3810
"""Test the authentication.conf file matching"""