367
568
'/home/bogus/.cache')
370
class TestIniConfig(tests.TestCase):
571
class TestXDGConfigDir(tests.TestCaseInTempDir):
572
# must be in temp dir because config tests for the existence of the bazaar
573
# subdirectory of $XDG_CONFIG_HOME
576
if sys.platform in ('darwin', 'win32'):
577
raise tests.TestNotApplicable(
578
'XDG config dir not used on this platform')
579
super(TestXDGConfigDir, self).setUp()
580
self.overrideEnv('HOME', self.test_home_dir)
581
# BZR_HOME overrides everything we want to test so unset it.
582
self.overrideEnv('BZR_HOME', None)
584
def test_xdg_config_dir_exists(self):
585
"""When ~/.config/bazaar exists, use it as the config dir."""
586
newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
588
self.assertEqual(config.config_dir(), newdir)
590
def test_xdg_config_home(self):
591
"""When XDG_CONFIG_HOME is set, use it."""
592
xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
593
self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
594
newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
596
self.assertEqual(config.config_dir(), newdir)
599
class TestIniConfig(tests.TestCaseInTempDir):
372
601
def make_config_parser(self, s):
373
conf = config.IniBasedConfig(None)
374
parser = conf._get_parser(file=StringIO(s.encode('utf-8')))
602
conf = config.IniBasedConfig.from_string(s)
603
return conf, conf._get_parser()
378
606
class TestIniConfigBuilding(TestIniConfig):
380
608
def test_contructs(self):
381
my_config = config.IniBasedConfig("nothing")
609
my_config = config.IniBasedConfig()
383
611
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))
612
my_config = config.IniBasedConfig.from_string(sample_config_text)
613
self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
390
615
def test_cached(self):
616
my_config = config.IniBasedConfig.from_string(sample_config_text)
617
parser = my_config._get_parser()
618
self.assertTrue(my_config._get_parser() is parser)
620
def _dummy_chown(self, path, uid, gid):
621
self.path, self.uid, self.gid = path, uid, gid
623
def test_ini_config_ownership(self):
624
"""Ensure that chown is happening during _write_config_file"""
625
self.requireFeature(features.chown_feature)
626
self.overrideAttr(os, 'chown', self._dummy_chown)
627
self.path = self.uid = self.gid = None
628
conf = config.IniBasedConfig(file_name='./foo.conf')
629
conf._write_config_file()
630
self.assertEquals(self.path, './foo.conf')
631
self.assertTrue(isinstance(self.uid, int))
632
self.assertTrue(isinstance(self.gid, int))
634
def test_get_filename_parameter_is_deprecated_(self):
635
conf = self.callDeprecated([
636
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
637
' Use file_name instead.'],
638
config.IniBasedConfig, lambda: 'ini.conf')
639
self.assertEqual('ini.conf', conf.file_name)
641
def test_get_parser_file_parameter_is_deprecated_(self):
391
642
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)
643
conf = config.IniBasedConfig.from_string(sample_config_text)
644
conf = self.callDeprecated([
645
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
646
' Use IniBasedConfig(_content=xxx) instead.'],
647
conf._get_parser, file=config_file)
650
class TestIniConfigSaving(tests.TestCaseInTempDir):
652
def test_cant_save_without_a_file_name(self):
653
conf = config.IniBasedConfig()
654
self.assertRaises(AssertionError, conf._write_config_file)
656
def test_saved_with_content(self):
657
content = 'foo = bar\n'
658
conf = config.IniBasedConfig.from_string(
659
content, file_name='./test.conf', save=True)
660
self.assertFileEqual(content, 'test.conf')
663
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
664
"""What is the default value of expand for config options.
666
This is an opt-in beta feature used to evaluate whether or not option
667
references can appear in dangerous place raising exceptions, disapearing
668
(and as such corrupting data) or if it's safe to activate the option by
671
Note that these tests relies on config._expand_default_value being already
672
overwritten in the parent class setUp.
676
super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
680
self.warnings.append(args[0] % args[1:])
681
self.overrideAttr(trace, 'warning', warning)
683
def get_config(self, expand):
684
c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
688
def assertExpandIs(self, expected):
689
actual = config._get_expand_default_value()
690
#self.config.get_user_option_as_bool('bzr.config.expand')
691
self.assertEquals(expected, actual)
693
def test_default_is_None(self):
694
self.assertEquals(None, config._expand_default_value)
696
def test_default_is_False_even_if_None(self):
697
self.config = self.get_config(None)
698
self.assertExpandIs(False)
700
def test_default_is_False_even_if_invalid(self):
701
self.config = self.get_config('<your choice>')
702
self.assertExpandIs(False)
704
# Huh ? My choice is False ? Thanks, always happy to hear that :D
705
# Wait, you've been warned !
706
self.assertLength(1, self.warnings)
708
'Value "<your choice>" is not a boolean for "bzr.config.expand"',
711
def test_default_is_True(self):
712
self.config = self.get_config(True)
713
self.assertExpandIs(True)
715
def test_default_is_False(self):
716
self.config = self.get_config(False)
717
self.assertExpandIs(False)
720
class TestIniConfigOptionExpansion(tests.TestCase):
721
"""Test option expansion from the IniConfig level.
723
What we really want here is to test the Config level, but the class being
724
abstract as far as storing values is concerned, this can't be done
727
# FIXME: This should be rewritten when all configs share a storage
728
# implementation -- vila 2011-02-18
730
def get_config(self, string=None):
733
c = config.IniBasedConfig.from_string(string)
736
def assertExpansion(self, expected, conf, string, env=None):
737
self.assertEquals(expected, conf.expand_options(string, env))
739
def test_no_expansion(self):
740
c = self.get_config('')
741
self.assertExpansion('foo', c, 'foo')
743
def test_env_adding_options(self):
744
c = self.get_config('')
745
self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
747
def test_env_overriding_options(self):
748
c = self.get_config('foo=baz')
749
self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
751
def test_simple_ref(self):
752
c = self.get_config('foo=xxx')
753
self.assertExpansion('xxx', c, '{foo}')
755
def test_unknown_ref(self):
756
c = self.get_config('')
757
self.assertRaises(errors.ExpandingUnknownOption,
758
c.expand_options, '{foo}')
760
def test_indirect_ref(self):
761
c = self.get_config('''
765
self.assertExpansion('xxx', c, '{bar}')
767
def test_embedded_ref(self):
768
c = self.get_config('''
772
self.assertExpansion('xxx', c, '{{bar}}')
774
def test_simple_loop(self):
775
c = self.get_config('foo={foo}')
776
self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
778
def test_indirect_loop(self):
779
c = self.get_config('''
783
e = self.assertRaises(errors.OptionExpansionLoop,
784
c.expand_options, '{foo}')
785
self.assertEquals('foo->bar->baz', e.refs)
786
self.assertEquals('{foo}', e.string)
789
conf = self.get_config('''
793
list={foo},{bar},{baz}
795
self.assertEquals(['start', 'middle', 'end'],
796
conf.get_user_option('list', expand=True))
798
def test_cascading_list(self):
799
conf = self.get_config('''
805
self.assertEquals(['start', 'middle', 'end'],
806
conf.get_user_option('list', expand=True))
808
def test_pathological_hidden_list(self):
809
conf = self.get_config('''
815
hidden={start}{middle}{end}
817
# Nope, it's either a string or a list, and the list wins as soon as a
818
# ',' appears, so the string concatenation never occur.
819
self.assertEquals(['{foo', '}', '{', 'bar}'],
820
conf.get_user_option('hidden', expand=True))
822
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
824
def get_config(self, location, string=None):
827
# Since we don't save the config we won't strictly require to inherit
828
# from TestCaseInTempDir, but an error occurs so quickly...
829
c = config.LocationConfig.from_string(string, location)
832
def test_dont_cross_unrelated_section(self):
833
c = self.get_config('/another/branch/path','''
838
[/another/branch/path]
841
self.assertRaises(errors.ExpandingUnknownOption,
842
c.get_user_option, 'bar', expand=True)
844
def test_cross_related_sections(self):
845
c = self.get_config('/project/branch/path','''
849
[/project/branch/path]
852
self.assertEquals('quux', c.get_user_option('bar', expand=True))
855
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
857
def test_cannot_reload_without_name(self):
858
conf = config.IniBasedConfig.from_string(sample_config_text)
859
self.assertRaises(AssertionError, conf.reload)
861
def test_reload_see_new_value(self):
862
c1 = config.IniBasedConfig.from_string('editor=vim\n',
863
file_name='./test/conf')
864
c1._write_config_file()
865
c2 = config.IniBasedConfig.from_string('editor=emacs\n',
866
file_name='./test/conf')
867
c2._write_config_file()
868
self.assertEqual('vim', c1.get_user_option('editor'))
869
self.assertEqual('emacs', c2.get_user_option('editor'))
870
# Make sure we get the Right value
872
self.assertEqual('emacs', c1.get_user_option('editor'))
875
class TestLockableConfig(tests.TestCaseInTempDir):
877
scenarios = lockable_config_scenarios()
882
config_section = None
885
super(TestLockableConfig, self).setUp()
886
self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
887
self.config = self.create_config(self._content)
889
def get_existing_config(self):
890
return self.config_class(*self.config_args)
892
def create_config(self, content):
893
kwargs = dict(save=True)
894
c = self.config_class.from_string(content, *self.config_args, **kwargs)
897
def test_simple_read_access(self):
898
self.assertEquals('1', self.config.get_user_option('one'))
900
def test_simple_write_access(self):
901
self.config.set_user_option('one', 'one')
902
self.assertEquals('one', self.config.get_user_option('one'))
904
def test_listen_to_the_last_speaker(self):
906
c2 = self.get_existing_config()
907
c1.set_user_option('one', 'ONE')
908
c2.set_user_option('two', 'TWO')
909
self.assertEquals('ONE', c1.get_user_option('one'))
910
self.assertEquals('TWO', c2.get_user_option('two'))
911
# The second update respect the first one
912
self.assertEquals('ONE', c2.get_user_option('one'))
914
def test_last_speaker_wins(self):
915
# If the same config is not shared, the same variable modified twice
916
# can only see a single result.
918
c2 = self.get_existing_config()
919
c1.set_user_option('one', 'c1')
920
c2.set_user_option('one', 'c2')
921
self.assertEquals('c2', c2._get_user_option('one'))
922
# The first modification is still available until another refresh
924
self.assertEquals('c1', c1._get_user_option('one'))
925
c1.set_user_option('two', 'done')
926
self.assertEquals('c2', c1._get_user_option('one'))
928
def test_writes_are_serialized(self):
930
c2 = self.get_existing_config()
932
# We spawn a thread that will pause *during* the write
933
before_writing = threading.Event()
934
after_writing = threading.Event()
935
writing_done = threading.Event()
936
c1_orig = c1._write_config_file
937
def c1_write_config_file():
940
# The lock is held. We wait for the main thread to decide when to
943
c1._write_config_file = c1_write_config_file
945
c1.set_user_option('one', 'c1')
947
t1 = threading.Thread(target=c1_set_option)
948
# Collect the thread after the test
949
self.addCleanup(t1.join)
950
# Be ready to unblock the thread if the test goes wrong
951
self.addCleanup(after_writing.set)
953
before_writing.wait()
954
self.assertTrue(c1._lock.is_held)
955
self.assertRaises(errors.LockContention,
956
c2.set_user_option, 'one', 'c2')
957
self.assertEquals('c1', c1.get_user_option('one'))
958
# Let the lock be released
961
c2.set_user_option('one', 'c2')
962
self.assertEquals('c2', c2.get_user_option('one'))
964
def test_read_while_writing(self):
966
# We spawn a thread that will pause *during* the write
967
ready_to_write = threading.Event()
968
do_writing = threading.Event()
969
writing_done = threading.Event()
970
c1_orig = c1._write_config_file
971
def c1_write_config_file():
973
# The lock is held. We wait for the main thread to decide when to
978
c1._write_config_file = c1_write_config_file
980
c1.set_user_option('one', 'c1')
981
t1 = threading.Thread(target=c1_set_option)
982
# Collect the thread after the test
983
self.addCleanup(t1.join)
984
# Be ready to unblock the thread if the test goes wrong
985
self.addCleanup(do_writing.set)
987
# Ensure the thread is ready to write
988
ready_to_write.wait()
989
self.assertTrue(c1._lock.is_held)
990
self.assertEquals('c1', c1.get_user_option('one'))
991
# If we read during the write, we get the old value
992
c2 = self.get_existing_config()
993
self.assertEquals('1', c2.get_user_option('one'))
994
# Let the writing occur and ensure it occurred
997
# Now we get the updated value
998
c3 = self.get_existing_config()
999
self.assertEquals('c1', c3.get_user_option('one'))
397
1002
class TestGetUserOptionAs(TestIniConfig):
1312
1966
self.assertIs(None, bzrdir_config.get_default_stack_on())
1969
class TestOldConfigHooks(tests.TestCaseWithTransport):
1972
super(TestOldConfigHooks, self).setUp()
1973
create_configs_with_file_option(self)
1975
def assertGetHook(self, conf, name, value):
1979
config.OldConfigHooks.install_named_hook('get', hook, None)
1981
config.OldConfigHooks.uninstall_named_hook, 'get', None)
1982
self.assertLength(0, calls)
1983
actual_value = conf.get_user_option(name)
1984
self.assertEquals(value, actual_value)
1985
self.assertLength(1, calls)
1986
self.assertEquals((conf, name, value), calls[0])
1988
def test_get_hook_bazaar(self):
1989
self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
1991
def test_get_hook_locations(self):
1992
self.assertGetHook(self.locations_config, 'file', 'locations')
1994
def test_get_hook_branch(self):
1995
# Since locations masks branch, we define a different option
1996
self.branch_config.set_user_option('file2', 'branch')
1997
self.assertGetHook(self.branch_config, 'file2', 'branch')
1999
def assertSetHook(self, conf, name, value):
2003
config.OldConfigHooks.install_named_hook('set', hook, None)
2005
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2006
self.assertLength(0, calls)
2007
conf.set_user_option(name, value)
2008
self.assertLength(1, calls)
2009
# We can't assert the conf object below as different configs use
2010
# different means to implement set_user_option and we care only about
2012
self.assertEquals((name, value), calls[0][1:])
2014
def test_set_hook_bazaar(self):
2015
self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
2017
def test_set_hook_locations(self):
2018
self.assertSetHook(self.locations_config, 'foo', 'locations')
2020
def test_set_hook_branch(self):
2021
self.assertSetHook(self.branch_config, 'foo', 'branch')
2023
def assertRemoveHook(self, conf, name, section_name=None):
2027
config.OldConfigHooks.install_named_hook('remove', hook, None)
2029
config.OldConfigHooks.uninstall_named_hook, 'remove', None)
2030
self.assertLength(0, calls)
2031
conf.remove_user_option(name, section_name)
2032
self.assertLength(1, calls)
2033
# We can't assert the conf object below as different configs use
2034
# different means to implement remove_user_option and we care only about
2036
self.assertEquals((name,), calls[0][1:])
2038
def test_remove_hook_bazaar(self):
2039
self.assertRemoveHook(self.bazaar_config, 'file')
2041
def test_remove_hook_locations(self):
2042
self.assertRemoveHook(self.locations_config, 'file',
2043
self.locations_config.location)
2045
def test_remove_hook_branch(self):
2046
self.assertRemoveHook(self.branch_config, 'file')
2048
def assertLoadHook(self, name, conf_class, *conf_args):
2052
config.OldConfigHooks.install_named_hook('load', hook, None)
2054
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2055
self.assertLength(0, calls)
2057
conf = conf_class(*conf_args)
2058
# Access an option to trigger a load
2059
conf.get_user_option(name)
2060
self.assertLength(1, calls)
2061
# Since we can't assert about conf, we just use the number of calls ;-/
2063
def test_load_hook_bazaar(self):
2064
self.assertLoadHook('file', config.GlobalConfig)
2066
def test_load_hook_locations(self):
2067
self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
2069
def test_load_hook_branch(self):
2070
self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
2072
def assertSaveHook(self, conf):
2076
config.OldConfigHooks.install_named_hook('save', hook, None)
2078
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2079
self.assertLength(0, calls)
2080
# Setting an option triggers a save
2081
conf.set_user_option('foo', 'bar')
2082
self.assertLength(1, calls)
2083
# Since we can't assert about conf, we just use the number of calls ;-/
2085
def test_save_hook_bazaar(self):
2086
self.assertSaveHook(self.bazaar_config)
2088
def test_save_hook_locations(self):
2089
self.assertSaveHook(self.locations_config)
2091
def test_save_hook_branch(self):
2092
self.assertSaveHook(self.branch_config)
2095
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
2096
"""Tests config hooks for remote configs.
2098
No tests for the remove hook as this is not implemented there.
2102
super(TestOldConfigHooksForRemote, self).setUp()
2103
self.transport_server = test_server.SmartTCPServer_for_testing
2104
create_configs_with_file_option(self)
2106
def assertGetHook(self, conf, name, value):
2110
config.OldConfigHooks.install_named_hook('get', hook, None)
2112
config.OldConfigHooks.uninstall_named_hook, 'get', None)
2113
self.assertLength(0, calls)
2114
actual_value = conf.get_option(name)
2115
self.assertEquals(value, actual_value)
2116
self.assertLength(1, calls)
2117
self.assertEquals((conf, name, value), calls[0])
2119
def test_get_hook_remote_branch(self):
2120
remote_branch = branch.Branch.open(self.get_url('tree'))
2121
self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2123
def test_get_hook_remote_bzrdir(self):
2124
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2125
conf = remote_bzrdir._get_config()
2126
conf.set_option('remotedir', 'file')
2127
self.assertGetHook(conf, 'file', 'remotedir')
2129
def assertSetHook(self, conf, name, value):
2133
config.OldConfigHooks.install_named_hook('set', hook, None)
2135
config.OldConfigHooks.uninstall_named_hook, 'set', None)
2136
self.assertLength(0, calls)
2137
conf.set_option(value, name)
2138
self.assertLength(1, calls)
2139
# We can't assert the conf object below as different configs use
2140
# different means to implement set_user_option and we care only about
2142
self.assertEquals((name, value), calls[0][1:])
2144
def test_set_hook_remote_branch(self):
2145
remote_branch = branch.Branch.open(self.get_url('tree'))
2146
self.addCleanup(remote_branch.lock_write().unlock)
2147
self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
2149
def test_set_hook_remote_bzrdir(self):
2150
remote_branch = branch.Branch.open(self.get_url('tree'))
2151
self.addCleanup(remote_branch.lock_write().unlock)
2152
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2153
self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2155
def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2159
config.OldConfigHooks.install_named_hook('load', hook, None)
2161
config.OldConfigHooks.uninstall_named_hook, 'load', None)
2162
self.assertLength(0, calls)
2164
conf = conf_class(*conf_args)
2165
# Access an option to trigger a load
2166
conf.get_option(name)
2167
self.assertLength(expected_nb_calls, calls)
2168
# Since we can't assert about conf, we just use the number of calls ;-/
2170
def test_load_hook_remote_branch(self):
2171
remote_branch = branch.Branch.open(self.get_url('tree'))
2172
self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2174
def test_load_hook_remote_bzrdir(self):
2175
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2176
# The config file doesn't exist, set an option to force its creation
2177
conf = remote_bzrdir._get_config()
2178
conf.set_option('remotedir', 'file')
2179
# We get one call for the server and one call for the client, this is
2180
# caused by the differences in implementations betwen
2181
# SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
2182
# SmartServerBranchGetConfigFile (in smart/branch.py)
2183
self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
2185
def assertSaveHook(self, conf):
2189
config.OldConfigHooks.install_named_hook('save', hook, None)
2191
config.OldConfigHooks.uninstall_named_hook, 'save', None)
2192
self.assertLength(0, calls)
2193
# Setting an option triggers a save
2194
conf.set_option('foo', 'bar')
2195
self.assertLength(1, calls)
2196
# Since we can't assert about conf, we just use the number of calls ;-/
2198
def test_save_hook_remote_branch(self):
2199
remote_branch = branch.Branch.open(self.get_url('tree'))
2200
self.addCleanup(remote_branch.lock_write().unlock)
2201
self.assertSaveHook(remote_branch._get_config())
2203
def test_save_hook_remote_bzrdir(self):
2204
remote_branch = branch.Branch.open(self.get_url('tree'))
2205
self.addCleanup(remote_branch.lock_write().unlock)
2206
remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2207
self.assertSaveHook(remote_bzrdir._get_config())
2210
class TestOption(tests.TestCase):
2212
def test_default_value(self):
2213
opt = config.Option('foo', default='bar')
2214
self.assertEquals('bar', opt.get_default())
2217
class TestOptionRegistry(tests.TestCase):
2220
super(TestOptionRegistry, self).setUp()
2221
# Always start with an empty registry
2222
self.overrideAttr(config, 'option_registry', registry.Registry())
2223
self.registry = config.option_registry
2225
def test_register(self):
2226
opt = config.Option('foo')
2227
self.registry.register('foo', opt)
2228
self.assertIs(opt, self.registry.get('foo'))
2230
lazy_option = config.Option('lazy_foo')
2232
def test_register_lazy(self):
2233
self.registry.register_lazy('foo', self.__module__,
2234
'TestOptionRegistry.lazy_option')
2235
self.assertIs(self.lazy_option, self.registry.get('foo'))
2237
def test_registered_help(self):
2238
opt = config.Option('foo')
2239
self.registry.register('foo', opt, help='A simple option')
2240
self.assertEquals('A simple option', self.registry.get_help('foo'))
2243
class TestRegisteredOptions(tests.TestCase):
2244
"""All registered options should verify some constraints."""
2246
scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2247
in config.option_registry.iteritems()]
2250
super(TestRegisteredOptions, self).setUp()
2251
self.registry = config.option_registry
2253
def test_proper_name(self):
2254
# An option should be registered under its own name, this can't be
2255
# checked at registration time for the lazy ones.
2256
self.assertEquals(self.option_name, self.option.name)
2258
def test_help_is_set(self):
2259
option_help = self.registry.get_help(self.option_name)
2260
self.assertNotEquals(None, option_help)
2261
# Come on, think about the user, he really wants to know whst the
2263
self.assertNotEquals('', option_help)
2266
class TestSection(tests.TestCase):
2268
# FIXME: Parametrize so that all sections produced by Stores run these
2269
# tests -- vila 2011-04-01
2271
def test_get_a_value(self):
2272
a_dict = dict(foo='bar')
2273
section = config.Section('myID', a_dict)
2274
self.assertEquals('bar', section.get('foo'))
2276
def test_get_unknown_option(self):
2278
section = config.Section(None, a_dict)
2279
self.assertEquals('out of thin air',
2280
section.get('foo', 'out of thin air'))
2282
def test_options_is_shared(self):
2284
section = config.Section(None, a_dict)
2285
self.assertIs(a_dict, section.options)
2288
class TestMutableSection(tests.TestCase):
2290
# FIXME: Parametrize so that all sections (including os.environ and the
2291
# ones produced by Stores) run these tests -- vila 2011-04-01
2294
a_dict = dict(foo='bar')
2295
section = config.MutableSection('myID', a_dict)
2296
section.set('foo', 'new_value')
2297
self.assertEquals('new_value', section.get('foo'))
2298
# The change appears in the shared section
2299
self.assertEquals('new_value', a_dict.get('foo'))
2300
# We keep track of the change
2301
self.assertTrue('foo' in section.orig)
2302
self.assertEquals('bar', section.orig.get('foo'))
2304
def test_set_preserve_original_once(self):
2305
a_dict = dict(foo='bar')
2306
section = config.MutableSection('myID', a_dict)
2307
section.set('foo', 'first_value')
2308
section.set('foo', 'second_value')
2309
# We keep track of the original value
2310
self.assertTrue('foo' in section.orig)
2311
self.assertEquals('bar', section.orig.get('foo'))
2313
def test_remove(self):
2314
a_dict = dict(foo='bar')
2315
section = config.MutableSection('myID', a_dict)
2316
section.remove('foo')
2317
# We get None for unknown options via the default value
2318
self.assertEquals(None, section.get('foo'))
2319
# Or we just get the default value
2320
self.assertEquals('unknown', section.get('foo', 'unknown'))
2321
self.assertFalse('foo' in section.options)
2322
# We keep track of the deletion
2323
self.assertTrue('foo' in section.orig)
2324
self.assertEquals('bar', section.orig.get('foo'))
2326
def test_remove_new_option(self):
2328
section = config.MutableSection('myID', a_dict)
2329
section.set('foo', 'bar')
2330
section.remove('foo')
2331
self.assertFalse('foo' in section.options)
2332
# The option didn't exist initially so it we need to keep track of it
2333
# with a special value
2334
self.assertTrue('foo' in section.orig)
2335
self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2338
class TestStore(tests.TestCaseWithTransport):
2340
def assertSectionContent(self, expected, section):
2341
"""Assert that some options have the proper values in a section."""
2342
expected_name, expected_options = expected
2343
self.assertEquals(expected_name, section.id)
2346
dict([(k, section.get(k)) for k in expected_options.keys()]))
2349
class TestReadonlyStore(TestStore):
2351
scenarios = [(key, {'get_store': builder}) for key, builder
2352
in config.test_store_builder_registry.iteritems()]
2355
super(TestReadonlyStore, self).setUp()
2357
def test_building_delays_load(self):
2358
store = self.get_store(self)
2359
self.assertEquals(False, store.is_loaded())
2360
store._load_from_string('')
2361
self.assertEquals(True, store.is_loaded())
2363
def test_get_no_sections_for_empty(self):
2364
store = self.get_store(self)
2365
store._load_from_string('')
2366
self.assertEquals([], list(store.get_sections()))
2368
def test_get_default_section(self):
2369
store = self.get_store(self)
2370
store._load_from_string('foo=bar')
2371
sections = list(store.get_sections())
2372
self.assertLength(1, sections)
2373
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2375
def test_get_named_section(self):
2376
store = self.get_store(self)
2377
store._load_from_string('[baz]\nfoo=bar')
2378
sections = list(store.get_sections())
2379
self.assertLength(1, sections)
2380
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2382
def test_load_from_string_fails_for_non_empty_store(self):
2383
store = self.get_store(self)
2384
store._load_from_string('foo=bar')
2385
self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2388
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2389
"""Simulate loading a config store without content of various encodings.
2391
All files produced by bzr are in utf8 content.
2393
Users may modify them manually and end up with a file that can't be
2394
loaded. We need to issue proper error messages in this case.
2397
invalid_utf8_char = '\xff'
2399
def test_load_utf8(self):
2400
"""Ensure we can load an utf8-encoded file."""
2401
t = self.get_transport()
2402
# From http://pad.lv/799212
2403
unicode_user = u'b\N{Euro Sign}ar'
2404
unicode_content = u'user=%s' % (unicode_user,)
2405
utf8_content = unicode_content.encode('utf8')
2406
# Store the raw content in the config file
2407
t.put_bytes('foo.conf', utf8_content)
2408
store = config.IniFileStore(t, 'foo.conf')
2410
stack = config.Stack([store.get_sections], store)
2411
self.assertEquals(unicode_user, stack.get('user'))
2413
def test_load_non_ascii(self):
2414
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2415
t = self.get_transport()
2416
t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2417
store = config.IniFileStore(t, 'foo.conf')
2418
self.assertRaises(errors.ConfigContentError, store.load)
2420
def test_load_erroneous_content(self):
2421
"""Ensure we display a proper error on content that can't be parsed."""
2422
t = self.get_transport()
2423
t.put_bytes('foo.conf', '[open_section\n')
2424
store = config.IniFileStore(t, 'foo.conf')
2425
self.assertRaises(errors.ParseConfigError, store.load)
2428
class TestIniConfigContent(tests.TestCaseWithTransport):
2429
"""Simulate loading a IniBasedConfig without content of various encodings.
2431
All files produced by bzr are in utf8 content.
2433
Users may modify them manually and end up with a file that can't be
2434
loaded. We need to issue proper error messages in this case.
2437
invalid_utf8_char = '\xff'
2439
def test_load_utf8(self):
2440
"""Ensure we can load an utf8-encoded file."""
2441
# From http://pad.lv/799212
2442
unicode_user = u'b\N{Euro Sign}ar'
2443
unicode_content = u'user=%s' % (unicode_user,)
2444
utf8_content = unicode_content.encode('utf8')
2445
# Store the raw content in the config file
2446
with open('foo.conf', 'wb') as f:
2447
f.write(utf8_content)
2448
conf = config.IniBasedConfig(file_name='foo.conf')
2449
self.assertEquals(unicode_user, conf.get_user_option('user'))
2451
def test_load_badly_encoded_content(self):
2452
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2453
with open('foo.conf', 'wb') as f:
2454
f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2455
conf = config.IniBasedConfig(file_name='foo.conf')
2456
self.assertRaises(errors.ConfigContentError, conf._get_parser)
2458
def test_load_erroneous_content(self):
2459
"""Ensure we display a proper error on content that can't be parsed."""
2460
with open('foo.conf', 'wb') as f:
2461
f.write('[open_section\n')
2462
conf = config.IniBasedConfig(file_name='foo.conf')
2463
self.assertRaises(errors.ParseConfigError, conf._get_parser)
2466
class TestMutableStore(TestStore):
2468
scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2469
in config.test_store_builder_registry.iteritems()]
2472
super(TestMutableStore, self).setUp()
2473
self.transport = self.get_transport()
2475
def has_store(self, store):
2476
store_basename = urlutils.relative_url(self.transport.external_url(),
2477
store.external_url())
2478
return self.transport.has(store_basename)
2480
def test_save_empty_creates_no_file(self):
2481
# FIXME: There should be a better way than relying on the test
2482
# parametrization to identify branch.conf -- vila 2011-0526
2483
if self.store_id in ('branch', 'remote_branch'):
2484
raise tests.TestNotApplicable(
2485
'branch.conf is *always* created when a branch is initialized')
2486
store = self.get_store(self)
2488
self.assertEquals(False, self.has_store(store))
2490
def test_save_emptied_succeeds(self):
2491
store = self.get_store(self)
2492
store._load_from_string('foo=bar\n')
2493
section = store.get_mutable_section(None)
2494
section.remove('foo')
2496
self.assertEquals(True, self.has_store(store))
2497
modified_store = self.get_store(self)
2498
sections = list(modified_store.get_sections())
2499
self.assertLength(0, sections)
2501
def test_save_with_content_succeeds(self):
2502
# FIXME: There should be a better way than relying on the test
2503
# parametrization to identify branch.conf -- vila 2011-0526
2504
if self.store_id in ('branch', 'remote_branch'):
2505
raise tests.TestNotApplicable(
2506
'branch.conf is *always* created when a branch is initialized')
2507
store = self.get_store(self)
2508
store._load_from_string('foo=bar\n')
2509
self.assertEquals(False, self.has_store(store))
2511
self.assertEquals(True, self.has_store(store))
2512
modified_store = self.get_store(self)
2513
sections = list(modified_store.get_sections())
2514
self.assertLength(1, sections)
2515
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2517
def test_set_option_in_empty_store(self):
2518
store = self.get_store(self)
2519
section = store.get_mutable_section(None)
2520
section.set('foo', 'bar')
2522
modified_store = self.get_store(self)
2523
sections = list(modified_store.get_sections())
2524
self.assertLength(1, sections)
2525
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2527
def test_set_option_in_default_section(self):
2528
store = self.get_store(self)
2529
store._load_from_string('')
2530
section = store.get_mutable_section(None)
2531
section.set('foo', 'bar')
2533
modified_store = self.get_store(self)
2534
sections = list(modified_store.get_sections())
2535
self.assertLength(1, sections)
2536
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2538
def test_set_option_in_named_section(self):
2539
store = self.get_store(self)
2540
store._load_from_string('')
2541
section = store.get_mutable_section('baz')
2542
section.set('foo', 'bar')
2544
modified_store = self.get_store(self)
2545
sections = list(modified_store.get_sections())
2546
self.assertLength(1, sections)
2547
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2549
def test_load_hook(self):
2550
# We first needs to ensure that the store exists
2551
store = self.get_store(self)
2552
section = store.get_mutable_section('baz')
2553
section.set('foo', 'bar')
2555
# Now we can try to load it
2556
store = self.get_store(self)
2560
config.ConfigHooks.install_named_hook('load', hook, None)
2561
self.assertLength(0, calls)
2563
self.assertLength(1, calls)
2564
self.assertEquals((store,), calls[0])
2566
def test_save_hook(self):
2570
config.ConfigHooks.install_named_hook('save', hook, None)
2571
self.assertLength(0, calls)
2572
store = self.get_store(self)
2573
section = store.get_mutable_section('baz')
2574
section.set('foo', 'bar')
2576
self.assertLength(1, calls)
2577
self.assertEquals((store,), calls[0])
2580
class TestIniFileStore(TestStore):
2582
def test_loading_unknown_file_fails(self):
2583
store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
2584
self.assertRaises(errors.NoSuchFile, store.load)
2586
def test_invalid_content(self):
2587
store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2588
self.assertEquals(False, store.is_loaded())
2589
exc = self.assertRaises(
2590
errors.ParseConfigError, store._load_from_string,
2591
'this is invalid !')
2592
self.assertEndsWith(exc.filename, 'foo.conf')
2593
# And the load failed
2594
self.assertEquals(False, store.is_loaded())
2596
def test_get_embedded_sections(self):
2597
# A more complicated example (which also shows that section names and
2598
# option names share the same name space...)
2599
# FIXME: This should be fixed by forbidding dicts as values ?
2600
# -- vila 2011-04-05
2601
store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2602
store._load_from_string('''
2606
foo_in_DEFAULT=foo_DEFAULT
2614
sections = list(store.get_sections())
2615
self.assertLength(4, sections)
2616
# The default section has no name.
2617
# List values are provided as lists
2618
self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
2620
self.assertSectionContent(
2621
('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2622
self.assertSectionContent(
2623
('bar', {'foo_in_bar': 'barbar'}), sections[2])
2624
# sub sections are provided as embedded dicts.
2625
self.assertSectionContent(
2626
('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2630
class TestLockableIniFileStore(TestStore):
2632
def test_create_store_in_created_dir(self):
2633
self.assertPathDoesNotExist('dir')
2634
t = self.get_transport('dir/subdir')
2635
store = config.LockableIniFileStore(t, 'foo.conf')
2636
store.get_mutable_section(None).set('foo', 'bar')
2638
self.assertPathExists('dir/subdir')
2641
class TestConcurrentStoreUpdates(TestStore):
2642
"""Test that Stores properly handle conccurent updates.
2644
New Store implementation may fail some of these tests but until such
2645
implementations exist it's hard to properly filter them from the scenarios
2646
applied here. If you encounter such a case, contact the bzr devs.
2649
scenarios = [(key, {'get_stack': builder}) for key, builder
2650
in config.test_stack_builder_registry.iteritems()]
2653
super(TestConcurrentStoreUpdates, self).setUp()
2654
self._content = 'one=1\ntwo=2\n'
2655
self.stack = self.get_stack(self)
2656
if not isinstance(self.stack, config._CompatibleStack):
2657
raise tests.TestNotApplicable(
2658
'%s is not meant to be compatible with the old config design'
2660
self.stack.store._load_from_string(self._content)
2662
self.stack.store.save()
2664
def test_simple_read_access(self):
2665
self.assertEquals('1', self.stack.get('one'))
2667
def test_simple_write_access(self):
2668
self.stack.set('one', 'one')
2669
self.assertEquals('one', self.stack.get('one'))
2671
def test_listen_to_the_last_speaker(self):
2673
c2 = self.get_stack(self)
2674
c1.set('one', 'ONE')
2675
c2.set('two', 'TWO')
2676
self.assertEquals('ONE', c1.get('one'))
2677
self.assertEquals('TWO', c2.get('two'))
2678
# The second update respect the first one
2679
self.assertEquals('ONE', c2.get('one'))
2681
def test_last_speaker_wins(self):
2682
# If the same config is not shared, the same variable modified twice
2683
# can only see a single result.
2685
c2 = self.get_stack(self)
2688
self.assertEquals('c2', c2.get('one'))
2689
# The first modification is still available until another refresh
2691
self.assertEquals('c1', c1.get('one'))
2692
c1.set('two', 'done')
2693
self.assertEquals('c2', c1.get('one'))
2695
def test_writes_are_serialized(self):
2697
c2 = self.get_stack(self)
2699
# We spawn a thread that will pause *during* the config saving.
2700
before_writing = threading.Event()
2701
after_writing = threading.Event()
2702
writing_done = threading.Event()
2703
c1_save_without_locking_orig = c1.store.save_without_locking
2704
def c1_save_without_locking():
2705
before_writing.set()
2706
c1_save_without_locking_orig()
2707
# The lock is held. We wait for the main thread to decide when to
2709
after_writing.wait()
2710
c1.store.save_without_locking = c1_save_without_locking
2714
t1 = threading.Thread(target=c1_set)
2715
# Collect the thread after the test
2716
self.addCleanup(t1.join)
2717
# Be ready to unblock the thread if the test goes wrong
2718
self.addCleanup(after_writing.set)
2720
before_writing.wait()
2721
self.assertRaises(errors.LockContention,
2722
c2.set, 'one', 'c2')
2723
self.assertEquals('c1', c1.get('one'))
2724
# Let the lock be released
2728
self.assertEquals('c2', c2.get('one'))
2730
def test_read_while_writing(self):
2732
# We spawn a thread that will pause *during* the write
2733
ready_to_write = threading.Event()
2734
do_writing = threading.Event()
2735
writing_done = threading.Event()
2736
# We override the _save implementation so we know the store is locked
2737
c1_save_without_locking_orig = c1.store.save_without_locking
2738
def c1_save_without_locking():
2739
ready_to_write.set()
2740
# The lock is held. We wait for the main thread to decide when to
2743
c1_save_without_locking_orig()
2745
c1.store.save_without_locking = c1_save_without_locking
2748
t1 = threading.Thread(target=c1_set)
2749
# Collect the thread after the test
2750
self.addCleanup(t1.join)
2751
# Be ready to unblock the thread if the test goes wrong
2752
self.addCleanup(do_writing.set)
2754
# Ensure the thread is ready to write
2755
ready_to_write.wait()
2756
self.assertEquals('c1', c1.get('one'))
2757
# If we read during the write, we get the old value
2758
c2 = self.get_stack(self)
2759
self.assertEquals('1', c2.get('one'))
2760
# Let the writing occur and ensure it occurred
2763
# Now we get the updated value
2764
c3 = self.get_stack(self)
2765
self.assertEquals('c1', c3.get('one'))
2767
# FIXME: It may be worth looking into removing the lock dir when it's not
2768
# needed anymore and look at possible fallouts for concurrent lockers. This
2769
# will matter if/when we use config files outside of bazaar directories
2770
# (.bazaar or .bzr) -- vila 20110-04-11
2773
class TestSectionMatcher(TestStore):
2775
scenarios = [('location', {'matcher': config.LocationMatcher})]
2777
def get_store(self, file_name):
2778
return config.IniFileStore(self.get_readonly_transport(), file_name)
2780
def test_no_matches_for_empty_stores(self):
2781
store = self.get_store('foo.conf')
2782
store._load_from_string('')
2783
matcher = self.matcher(store, '/bar')
2784
self.assertEquals([], list(matcher.get_sections()))
2786
def test_build_doesnt_load_store(self):
2787
store = self.get_store('foo.conf')
2788
matcher = self.matcher(store, '/bar')
2789
self.assertFalse(store.is_loaded())
2792
class TestLocationSection(tests.TestCase):
2794
def get_section(self, options, extra_path):
2795
section = config.Section('foo', options)
2796
# We don't care about the length so we use '0'
2797
return config.LocationSection(section, 0, extra_path)
2799
def test_simple_option(self):
2800
section = self.get_section({'foo': 'bar'}, '')
2801
self.assertEquals('bar', section.get('foo'))
2803
def test_option_with_extra_path(self):
2804
section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
2806
self.assertEquals('bar/baz', section.get('foo'))
2808
def test_invalid_policy(self):
2809
section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
2811
# invalid policies are ignored
2812
self.assertEquals('bar', section.get('foo'))
2815
class TestLocationMatcher(TestStore):
2817
def get_store(self, file_name):
2818
return config.IniFileStore(self.get_readonly_transport(), file_name)
2820
def test_more_specific_sections_first(self):
2821
store = self.get_store('foo.conf')
2822
store._load_from_string('''
2828
self.assertEquals(['/foo', '/foo/bar'],
2829
[section.id for section in store.get_sections()])
2830
matcher = config.LocationMatcher(store, '/foo/bar/baz')
2831
sections = list(matcher.get_sections())
2832
self.assertEquals([3, 2],
2833
[section.length for section in sections])
2834
self.assertEquals(['/foo/bar', '/foo'],
2835
[section.id for section in sections])
2836
self.assertEquals(['baz', 'bar/baz'],
2837
[section.extra_path for section in sections])
2839
def test_appendpath_in_no_name_section(self):
2840
# It's a bit weird to allow appendpath in a no-name section, but
2841
# someone may found a use for it
2842
store = self.get_store('foo.conf')
2843
store._load_from_string('''
2845
foo:policy = appendpath
2847
matcher = config.LocationMatcher(store, 'dir/subdir')
2848
sections = list(matcher.get_sections())
2849
self.assertLength(1, sections)
2850
self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
2852
def test_file_urls_are_normalized(self):
2853
store = self.get_store('foo.conf')
2854
if sys.platform == 'win32':
2855
expected_url = 'file:///C:/dir/subdir'
2856
expected_location = 'C:/dir/subdir'
2858
expected_url = 'file:///dir/subdir'
2859
expected_location = '/dir/subdir'
2860
matcher = config.LocationMatcher(store, expected_url)
2861
self.assertEquals(expected_location, matcher.location)
2864
class TestStackGet(tests.TestCase):
2866
# FIXME: This should be parametrized for all known Stack or dedicated
2867
# paramerized tests created to avoid bloating -- vila 2011-03-31
2869
def test_single_config_get(self):
2870
conf = dict(foo='bar')
2871
conf_stack = config.Stack([conf])
2872
self.assertEquals('bar', conf_stack.get('foo'))
2874
def test_get_with_registered_default_value(self):
2875
conf_stack = config.Stack([dict()])
2876
opt = config.Option('foo', default='bar')
2877
self.overrideAttr(config, 'option_registry', registry.Registry())
2878
config.option_registry.register('foo', opt)
2879
self.assertEquals('bar', conf_stack.get('foo'))
2881
def test_get_without_registered_default_value(self):
2882
conf_stack = config.Stack([dict()])
2883
opt = config.Option('foo')
2884
self.overrideAttr(config, 'option_registry', registry.Registry())
2885
config.option_registry.register('foo', opt)
2886
self.assertEquals(None, conf_stack.get('foo'))
2888
def test_get_without_default_value_for_not_registered(self):
2889
conf_stack = config.Stack([dict()])
2890
opt = config.Option('foo')
2891
self.overrideAttr(config, 'option_registry', registry.Registry())
2892
self.assertEquals(None, conf_stack.get('foo'))
2894
def test_get_first_definition(self):
2895
conf1 = dict(foo='bar')
2896
conf2 = dict(foo='baz')
2897
conf_stack = config.Stack([conf1, conf2])
2898
self.assertEquals('bar', conf_stack.get('foo'))
2900
def test_get_embedded_definition(self):
2901
conf1 = dict(yy='12')
2902
conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
2903
conf_stack = config.Stack([conf1, conf2])
2904
self.assertEquals('baz', conf_stack.get('foo'))
2906
def test_get_for_empty_section_callable(self):
2907
conf_stack = config.Stack([lambda : []])
2908
self.assertEquals(None, conf_stack.get('foo'))
2910
def test_get_for_broken_callable(self):
2911
# Trying to use and invalid callable raises an exception on first use
2912
conf_stack = config.Stack([lambda : object()])
2913
self.assertRaises(TypeError, conf_stack.get, 'foo')
2916
class TestStackWithTransport(tests.TestCaseWithTransport):
2918
scenarios = [(key, {'get_stack': builder}) for key, builder
2919
in config.test_stack_builder_registry.iteritems()]
2922
class TestConcreteStacks(TestStackWithTransport):
2924
def test_build_stack(self):
2925
# Just a smoke test to help debug builders
2926
stack = self.get_stack(self)
2929
class TestStackGet(TestStackWithTransport):
2931
def test_get_for_empty_stack(self):
2932
conf = self.get_stack(self)
2933
self.assertEquals(None, conf.get('foo'))
2935
def test_get_hook(self):
2936
conf = self.get_stack(self)
2937
conf.store._load_from_string('foo=bar')
2941
config.ConfigHooks.install_named_hook('get', hook, None)
2942
self.assertLength(0, calls)
2943
value = conf.get('foo')
2944
self.assertEquals('bar', value)
2945
self.assertLength(1, calls)
2946
self.assertEquals((conf, 'foo', 'bar'), calls[0])
2949
class TestStackSet(TestStackWithTransport):
2951
def test_simple_set(self):
2952
conf = self.get_stack(self)
2953
conf.store._load_from_string('foo=bar')
2954
self.assertEquals('bar', conf.get('foo'))
2955
conf.set('foo', 'baz')
2956
# Did we get it back ?
2957
self.assertEquals('baz', conf.get('foo'))
2959
def test_set_creates_a_new_section(self):
2960
conf = self.get_stack(self)
2961
conf.set('foo', 'baz')
2962
self.assertEquals, 'baz', conf.get('foo')
2964
def test_set_hook(self):
2968
config.ConfigHooks.install_named_hook('set', hook, None)
2969
self.assertLength(0, calls)
2970
conf = self.get_stack(self)
2971
conf.set('foo', 'bar')
2972
self.assertLength(1, calls)
2973
self.assertEquals((conf, 'foo', 'bar'), calls[0])
2976
class TestStackRemove(TestStackWithTransport):
2978
def test_remove_existing(self):
2979
conf = self.get_stack(self)
2980
conf.store._load_from_string('foo=bar')
2981
self.assertEquals('bar', conf.get('foo'))
2983
# Did we get it back ?
2984
self.assertEquals(None, conf.get('foo'))
2986
def test_remove_unknown(self):
2987
conf = self.get_stack(self)
2988
self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
2990
def test_remove_hook(self):
2994
config.ConfigHooks.install_named_hook('remove', hook, None)
2995
self.assertLength(0, calls)
2996
conf = self.get_stack(self)
2997
conf.store._load_from_string('foo=bar')
2999
self.assertLength(1, calls)
3000
self.assertEquals((conf, 'foo'), calls[0])
3003
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3006
super(TestConfigGetOptions, self).setUp()
3007
create_configs(self)
3009
def test_no_variable(self):
3010
# Using branch should query branch, locations and bazaar
3011
self.assertOptions([], self.branch_config)
3013
def test_option_in_bazaar(self):
3014
self.bazaar_config.set_user_option('file', 'bazaar')
3015
self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
3018
def test_option_in_locations(self):
3019
self.locations_config.set_user_option('file', 'locations')
3021
[('file', 'locations', self.tree.basedir, 'locations')],
3022
self.locations_config)
3024
def test_option_in_branch(self):
3025
self.branch_config.set_user_option('file', 'branch')
3026
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
3029
def test_option_in_bazaar_and_branch(self):
3030
self.bazaar_config.set_user_option('file', 'bazaar')
3031
self.branch_config.set_user_option('file', 'branch')
3032
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
3033
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3036
def test_option_in_branch_and_locations(self):
3037
# Hmm, locations override branch :-/
3038
self.locations_config.set_user_option('file', 'locations')
3039
self.branch_config.set_user_option('file', 'branch')
3041
[('file', 'locations', self.tree.basedir, 'locations'),
3042
('file', 'branch', 'DEFAULT', 'branch'),],
3045
def test_option_in_bazaar_locations_and_branch(self):
3046
self.bazaar_config.set_user_option('file', 'bazaar')
3047
self.locations_config.set_user_option('file', 'locations')
3048
self.branch_config.set_user_option('file', 'branch')
3050
[('file', 'locations', self.tree.basedir, 'locations'),
3051
('file', 'branch', 'DEFAULT', 'branch'),
3052
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3056
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
3059
super(TestConfigRemoveOption, self).setUp()
3060
create_configs_with_file_option(self)
3062
def test_remove_in_locations(self):
3063
self.locations_config.remove_user_option('file', self.tree.basedir)
3065
[('file', 'branch', 'DEFAULT', 'branch'),
3066
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3069
def test_remove_in_branch(self):
3070
self.branch_config.remove_user_option('file')
3072
[('file', 'locations', self.tree.basedir, 'locations'),
3073
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3076
def test_remove_in_bazaar(self):
3077
self.bazaar_config.remove_user_option('file')
3079
[('file', 'locations', self.tree.basedir, 'locations'),
3080
('file', 'branch', 'DEFAULT', 'branch'),],
3084
class TestConfigGetSections(tests.TestCaseWithTransport):
3087
super(TestConfigGetSections, self).setUp()
3088
create_configs(self)
3090
def assertSectionNames(self, expected, conf, name=None):
3091
"""Check which sections are returned for a given config.
3093
If fallback configurations exist their sections can be included.
3095
:param expected: A list of section names.
3097
:param conf: The configuration that will be queried.
3099
:param name: An optional section name that will be passed to
3102
sections = list(conf._get_sections(name))
3103
self.assertLength(len(expected), sections)
3104
self.assertEqual(expected, [name for name, _, _ in sections])
3106
def test_bazaar_default_section(self):
3107
self.assertSectionNames(['DEFAULT'], self.bazaar_config)
3109
def test_locations_default_section(self):
3110
# No sections are defined in an empty file
3111
self.assertSectionNames([], self.locations_config)
3113
def test_locations_named_section(self):
3114
self.locations_config.set_user_option('file', 'locations')
3115
self.assertSectionNames([self.tree.basedir], self.locations_config)
3117
def test_locations_matching_sections(self):
3118
loc_config = self.locations_config
3119
loc_config.set_user_option('file', 'locations')
3120
# We need to cheat a bit here to create an option in sections above and
3121
# below the 'location' one.
3122
parser = loc_config._get_parser()
3123
# locations.cong deals with '/' ignoring native os.sep
3124
location_names = self.tree.basedir.split('/')
3125
parent = '/'.join(location_names[:-1])
3126
child = '/'.join(location_names + ['child'])
3128
parser[parent]['file'] = 'parent'
3130
parser[child]['file'] = 'child'
3131
self.assertSectionNames([self.tree.basedir, parent], loc_config)
3133
def test_branch_data_default_section(self):
3134
self.assertSectionNames([None],
3135
self.branch_config._get_branch_data_config())
3137
def test_branch_default_sections(self):
3138
# No sections are defined in an empty locations file
3139
self.assertSectionNames([None, 'DEFAULT'],
3141
# Unless we define an option
3142
self.branch_config._get_location_config().set_user_option(
3143
'file', 'locations')
3144
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
3147
def test_bazaar_named_section(self):
3148
# We need to cheat as the API doesn't give direct access to sections
3149
# other than DEFAULT.
3150
self.bazaar_config.set_alias('bazaar', 'bzr')
3151
self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
1315
3154
class TestAuthenticationConfigFile(tests.TestCase):
1316
3155
"""Test the authentication.conf file matching"""