563
345
self.assertEqual(config.authentication_config_filename(),
564
346
self.bzr_home + '/authentication.conf')
566
def test_xdg_cache_dir(self):
567
self.assertEqual(config.xdg_cache_dir(),
568
'/home/bogus/.cache')
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):
601
def make_config_parser(self, s):
602
conf = config.IniBasedConfig.from_string(s)
603
return conf, conf._get_parser()
606
class TestIniConfigBuilding(TestIniConfig):
349
class TestIniConfig(tests.TestCase):
608
351
def test_contructs(self):
609
my_config = config.IniBasedConfig()
352
my_config = config.IniBasedConfig("nothing")
611
354
def test_from_fp(self):
612
my_config = config.IniBasedConfig.from_string(sample_config_text)
613
self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
355
config_file = StringIO(sample_config_text.encode('utf-8'))
356
my_config = config.IniBasedConfig(None)
358
isinstance(my_config._get_parser(file=config_file),
359
configobj.ConfigObj))
615
361
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):
642
362
config_file = StringIO(sample_config_text.encode('utf-8'))
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'))
1002
class TestGetUserOptionAs(TestIniConfig):
1004
def test_get_user_option_as_bool(self):
1005
conf, parser = self.make_config_parser("""
1008
an_invalid_bool = maybe
1009
a_list = hmm, who knows ? # This is interpreted as a list !
1011
get_bool = conf.get_user_option_as_bool
1012
self.assertEqual(True, get_bool('a_true_bool'))
1013
self.assertEqual(False, get_bool('a_false_bool'))
1016
warnings.append(args[0] % args[1:])
1017
self.overrideAttr(trace, 'warning', warning)
1018
msg = 'Value "%s" is not a boolean for "%s"'
1019
self.assertIs(None, get_bool('an_invalid_bool'))
1020
self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
1022
self.assertIs(None, get_bool('not_defined_in_this_config'))
1023
self.assertEquals([], warnings)
1025
def test_get_user_option_as_list(self):
1026
conf, parser = self.make_config_parser("""
1031
get_list = conf.get_user_option_as_list
1032
self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
1033
self.assertEqual(['1'], get_list('length_1'))
1034
self.assertEqual('x', conf.get_user_option('one_item'))
1035
# automatically cast to list
1036
self.assertEqual(['x'], get_list('one_item'))
1039
class TestSupressWarning(TestIniConfig):
1041
def make_warnings_config(self, s):
1042
conf, parser = self.make_config_parser(s)
1043
return conf.suppress_warning
1045
def test_suppress_warning_unknown(self):
1046
suppress_warning = self.make_warnings_config('')
1047
self.assertEqual(False, suppress_warning('unknown_warning'))
1049
def test_suppress_warning_known(self):
1050
suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
1051
self.assertEqual(False, suppress_warning('c'))
1052
self.assertEqual(True, suppress_warning('a'))
1053
self.assertEqual(True, suppress_warning('b'))
363
my_config = config.IniBasedConfig(None)
364
parser = my_config._get_parser(file=config_file)
365
self.failUnless(my_config._get_parser() is parser)
1056
368
class TestGetConfig(tests.TestCase):
1966
1217
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', config.OptionRegistry())
2223
self.registry = config.option_registry
2225
def test_register(self):
2226
opt = config.Option('foo')
2227
self.registry.register(opt)
2228
self.assertIs(opt, self.registry.get('foo'))
2230
def test_registered_help(self):
2231
opt = config.Option('foo', help='A simple option')
2232
self.registry.register(opt)
2233
self.assertEquals('A simple option', self.registry.get_help('foo'))
2235
lazy_option = config.Option('lazy_foo', help='Lazy help')
2237
def test_register_lazy(self):
2238
self.registry.register_lazy('lazy_foo', self.__module__,
2239
'TestOptionRegistry.lazy_option')
2240
self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2242
def test_registered_lazy_help(self):
2243
self.registry.register_lazy('lazy_foo', self.__module__,
2244
'TestOptionRegistry.lazy_option')
2245
self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2248
class TestRegisteredOptions(tests.TestCase):
2249
"""All registered options should verify some constraints."""
2251
scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2252
in config.option_registry.iteritems()]
2255
super(TestRegisteredOptions, self).setUp()
2256
self.registry = config.option_registry
2258
def test_proper_name(self):
2259
# An option should be registered under its own name, this can't be
2260
# checked at registration time for the lazy ones.
2261
self.assertEquals(self.option_name, self.option.name)
2263
def test_help_is_set(self):
2264
option_help = self.registry.get_help(self.option_name)
2265
self.assertNotEquals(None, option_help)
2266
# Come on, think about the user, he really wants to know what the
2268
self.assertIsNot(None, option_help)
2269
self.assertNotEquals('', option_help)
2272
class TestSection(tests.TestCase):
2274
# FIXME: Parametrize so that all sections produced by Stores run these
2275
# tests -- vila 2011-04-01
2277
def test_get_a_value(self):
2278
a_dict = dict(foo='bar')
2279
section = config.Section('myID', a_dict)
2280
self.assertEquals('bar', section.get('foo'))
2282
def test_get_unknown_option(self):
2284
section = config.Section(None, a_dict)
2285
self.assertEquals('out of thin air',
2286
section.get('foo', 'out of thin air'))
2288
def test_options_is_shared(self):
2290
section = config.Section(None, a_dict)
2291
self.assertIs(a_dict, section.options)
2294
class TestMutableSection(tests.TestCase):
2296
# FIXME: Parametrize so that all sections (including os.environ and the
2297
# ones produced by Stores) run these tests -- vila 2011-04-01
2300
a_dict = dict(foo='bar')
2301
section = config.MutableSection('myID', a_dict)
2302
section.set('foo', 'new_value')
2303
self.assertEquals('new_value', section.get('foo'))
2304
# The change appears in the shared section
2305
self.assertEquals('new_value', a_dict.get('foo'))
2306
# We keep track of the change
2307
self.assertTrue('foo' in section.orig)
2308
self.assertEquals('bar', section.orig.get('foo'))
2310
def test_set_preserve_original_once(self):
2311
a_dict = dict(foo='bar')
2312
section = config.MutableSection('myID', a_dict)
2313
section.set('foo', 'first_value')
2314
section.set('foo', 'second_value')
2315
# We keep track of the original value
2316
self.assertTrue('foo' in section.orig)
2317
self.assertEquals('bar', section.orig.get('foo'))
2319
def test_remove(self):
2320
a_dict = dict(foo='bar')
2321
section = config.MutableSection('myID', a_dict)
2322
section.remove('foo')
2323
# We get None for unknown options via the default value
2324
self.assertEquals(None, section.get('foo'))
2325
# Or we just get the default value
2326
self.assertEquals('unknown', section.get('foo', 'unknown'))
2327
self.assertFalse('foo' in section.options)
2328
# We keep track of the deletion
2329
self.assertTrue('foo' in section.orig)
2330
self.assertEquals('bar', section.orig.get('foo'))
2332
def test_remove_new_option(self):
2334
section = config.MutableSection('myID', a_dict)
2335
section.set('foo', 'bar')
2336
section.remove('foo')
2337
self.assertFalse('foo' in section.options)
2338
# The option didn't exist initially so it we need to keep track of it
2339
# with a special value
2340
self.assertTrue('foo' in section.orig)
2341
self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2344
class TestStore(tests.TestCaseWithTransport):
2346
def assertSectionContent(self, expected, section):
2347
"""Assert that some options have the proper values in a section."""
2348
expected_name, expected_options = expected
2349
self.assertEquals(expected_name, section.id)
2352
dict([(k, section.get(k)) for k in expected_options.keys()]))
2355
class TestReadonlyStore(TestStore):
2357
scenarios = [(key, {'get_store': builder}) for key, builder
2358
in config.test_store_builder_registry.iteritems()]
2361
super(TestReadonlyStore, self).setUp()
2363
def test_building_delays_load(self):
2364
store = self.get_store(self)
2365
self.assertEquals(False, store.is_loaded())
2366
store._load_from_string('')
2367
self.assertEquals(True, store.is_loaded())
2369
def test_get_no_sections_for_empty(self):
2370
store = self.get_store(self)
2371
store._load_from_string('')
2372
self.assertEquals([], list(store.get_sections()))
2374
def test_get_default_section(self):
2375
store = self.get_store(self)
2376
store._load_from_string('foo=bar')
2377
sections = list(store.get_sections())
2378
self.assertLength(1, sections)
2379
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2381
def test_get_named_section(self):
2382
store = self.get_store(self)
2383
store._load_from_string('[baz]\nfoo=bar')
2384
sections = list(store.get_sections())
2385
self.assertLength(1, sections)
2386
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2388
def test_load_from_string_fails_for_non_empty_store(self):
2389
store = self.get_store(self)
2390
store._load_from_string('foo=bar')
2391
self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2394
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2395
"""Simulate loading a config store without content of various encodings.
2397
All files produced by bzr are in utf8 content.
2399
Users may modify them manually and end up with a file that can't be
2400
loaded. We need to issue proper error messages in this case.
2403
invalid_utf8_char = '\xff'
2405
def test_load_utf8(self):
2406
"""Ensure we can load an utf8-encoded file."""
2407
t = self.get_transport()
2408
# From http://pad.lv/799212
2409
unicode_user = u'b\N{Euro Sign}ar'
2410
unicode_content = u'user=%s' % (unicode_user,)
2411
utf8_content = unicode_content.encode('utf8')
2412
# Store the raw content in the config file
2413
t.put_bytes('foo.conf', utf8_content)
2414
store = config.IniFileStore(t, 'foo.conf')
2416
stack = config.Stack([store.get_sections], store)
2417
self.assertEquals(unicode_user, stack.get('user'))
2419
def test_load_non_ascii(self):
2420
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2421
t = self.get_transport()
2422
t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2423
store = config.IniFileStore(t, 'foo.conf')
2424
self.assertRaises(errors.ConfigContentError, store.load)
2426
def test_load_erroneous_content(self):
2427
"""Ensure we display a proper error on content that can't be parsed."""
2428
t = self.get_transport()
2429
t.put_bytes('foo.conf', '[open_section\n')
2430
store = config.IniFileStore(t, 'foo.conf')
2431
self.assertRaises(errors.ParseConfigError, store.load)
2434
class TestIniConfigContent(tests.TestCaseWithTransport):
2435
"""Simulate loading a IniBasedConfig without content of various encodings.
2437
All files produced by bzr are in utf8 content.
2439
Users may modify them manually and end up with a file that can't be
2440
loaded. We need to issue proper error messages in this case.
2443
invalid_utf8_char = '\xff'
2445
def test_load_utf8(self):
2446
"""Ensure we can load an utf8-encoded file."""
2447
# From http://pad.lv/799212
2448
unicode_user = u'b\N{Euro Sign}ar'
2449
unicode_content = u'user=%s' % (unicode_user,)
2450
utf8_content = unicode_content.encode('utf8')
2451
# Store the raw content in the config file
2452
with open('foo.conf', 'wb') as f:
2453
f.write(utf8_content)
2454
conf = config.IniBasedConfig(file_name='foo.conf')
2455
self.assertEquals(unicode_user, conf.get_user_option('user'))
2457
def test_load_badly_encoded_content(self):
2458
"""Ensure we display a proper error on non-ascii, non utf-8 content."""
2459
with open('foo.conf', 'wb') as f:
2460
f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2461
conf = config.IniBasedConfig(file_name='foo.conf')
2462
self.assertRaises(errors.ConfigContentError, conf._get_parser)
2464
def test_load_erroneous_content(self):
2465
"""Ensure we display a proper error on content that can't be parsed."""
2466
with open('foo.conf', 'wb') as f:
2467
f.write('[open_section\n')
2468
conf = config.IniBasedConfig(file_name='foo.conf')
2469
self.assertRaises(errors.ParseConfigError, conf._get_parser)
2472
class TestMutableStore(TestStore):
2474
scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2475
in config.test_store_builder_registry.iteritems()]
2478
super(TestMutableStore, self).setUp()
2479
self.transport = self.get_transport()
2481
def has_store(self, store):
2482
store_basename = urlutils.relative_url(self.transport.external_url(),
2483
store.external_url())
2484
return self.transport.has(store_basename)
2486
def test_save_empty_creates_no_file(self):
2487
# FIXME: There should be a better way than relying on the test
2488
# parametrization to identify branch.conf -- vila 2011-0526
2489
if self.store_id in ('branch', 'remote_branch'):
2490
raise tests.TestNotApplicable(
2491
'branch.conf is *always* created when a branch is initialized')
2492
store = self.get_store(self)
2494
self.assertEquals(False, self.has_store(store))
2496
def test_save_emptied_succeeds(self):
2497
store = self.get_store(self)
2498
store._load_from_string('foo=bar\n')
2499
section = store.get_mutable_section(None)
2500
section.remove('foo')
2502
self.assertEquals(True, self.has_store(store))
2503
modified_store = self.get_store(self)
2504
sections = list(modified_store.get_sections())
2505
self.assertLength(0, sections)
2507
def test_save_with_content_succeeds(self):
2508
# FIXME: There should be a better way than relying on the test
2509
# parametrization to identify branch.conf -- vila 2011-0526
2510
if self.store_id in ('branch', 'remote_branch'):
2511
raise tests.TestNotApplicable(
2512
'branch.conf is *always* created when a branch is initialized')
2513
store = self.get_store(self)
2514
store._load_from_string('foo=bar\n')
2515
self.assertEquals(False, self.has_store(store))
2517
self.assertEquals(True, self.has_store(store))
2518
modified_store = self.get_store(self)
2519
sections = list(modified_store.get_sections())
2520
self.assertLength(1, sections)
2521
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2523
def test_set_option_in_empty_store(self):
2524
store = self.get_store(self)
2525
section = store.get_mutable_section(None)
2526
section.set('foo', 'bar')
2528
modified_store = self.get_store(self)
2529
sections = list(modified_store.get_sections())
2530
self.assertLength(1, sections)
2531
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2533
def test_set_option_in_default_section(self):
2534
store = self.get_store(self)
2535
store._load_from_string('')
2536
section = store.get_mutable_section(None)
2537
section.set('foo', 'bar')
2539
modified_store = self.get_store(self)
2540
sections = list(modified_store.get_sections())
2541
self.assertLength(1, sections)
2542
self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2544
def test_set_option_in_named_section(self):
2545
store = self.get_store(self)
2546
store._load_from_string('')
2547
section = store.get_mutable_section('baz')
2548
section.set('foo', 'bar')
2550
modified_store = self.get_store(self)
2551
sections = list(modified_store.get_sections())
2552
self.assertLength(1, sections)
2553
self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2555
def test_load_hook(self):
2556
# We first needs to ensure that the store exists
2557
store = self.get_store(self)
2558
section = store.get_mutable_section('baz')
2559
section.set('foo', 'bar')
2561
# Now we can try to load it
2562
store = self.get_store(self)
2566
config.ConfigHooks.install_named_hook('load', hook, None)
2567
self.assertLength(0, calls)
2569
self.assertLength(1, calls)
2570
self.assertEquals((store,), calls[0])
2572
def test_save_hook(self):
2576
config.ConfigHooks.install_named_hook('save', hook, None)
2577
self.assertLength(0, calls)
2578
store = self.get_store(self)
2579
section = store.get_mutable_section('baz')
2580
section.set('foo', 'bar')
2582
self.assertLength(1, calls)
2583
self.assertEquals((store,), calls[0])
2586
class TestIniFileStore(TestStore):
2588
def test_loading_unknown_file_fails(self):
2589
store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
2590
self.assertRaises(errors.NoSuchFile, store.load)
2592
def test_invalid_content(self):
2593
store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2594
self.assertEquals(False, store.is_loaded())
2595
exc = self.assertRaises(
2596
errors.ParseConfigError, store._load_from_string,
2597
'this is invalid !')
2598
self.assertEndsWith(exc.filename, 'foo.conf')
2599
# And the load failed
2600
self.assertEquals(False, store.is_loaded())
2602
def test_get_embedded_sections(self):
2603
# A more complicated example (which also shows that section names and
2604
# option names share the same name space...)
2605
# FIXME: This should be fixed by forbidding dicts as values ?
2606
# -- vila 2011-04-05
2607
store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2608
store._load_from_string('''
2612
foo_in_DEFAULT=foo_DEFAULT
2620
sections = list(store.get_sections())
2621
self.assertLength(4, sections)
2622
# The default section has no name.
2623
# List values are provided as lists
2624
self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
2626
self.assertSectionContent(
2627
('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2628
self.assertSectionContent(
2629
('bar', {'foo_in_bar': 'barbar'}), sections[2])
2630
# sub sections are provided as embedded dicts.
2631
self.assertSectionContent(
2632
('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2636
class TestLockableIniFileStore(TestStore):
2638
def test_create_store_in_created_dir(self):
2639
self.assertPathDoesNotExist('dir')
2640
t = self.get_transport('dir/subdir')
2641
store = config.LockableIniFileStore(t, 'foo.conf')
2642
store.get_mutable_section(None).set('foo', 'bar')
2644
self.assertPathExists('dir/subdir')
2647
class TestConcurrentStoreUpdates(TestStore):
2648
"""Test that Stores properly handle conccurent updates.
2650
New Store implementation may fail some of these tests but until such
2651
implementations exist it's hard to properly filter them from the scenarios
2652
applied here. If you encounter such a case, contact the bzr devs.
2655
scenarios = [(key, {'get_stack': builder}) for key, builder
2656
in config.test_stack_builder_registry.iteritems()]
2659
super(TestConcurrentStoreUpdates, self).setUp()
2660
self._content = 'one=1\ntwo=2\n'
2661
self.stack = self.get_stack(self)
2662
if not isinstance(self.stack, config._CompatibleStack):
2663
raise tests.TestNotApplicable(
2664
'%s is not meant to be compatible with the old config design'
2666
self.stack.store._load_from_string(self._content)
2668
self.stack.store.save()
2670
def test_simple_read_access(self):
2671
self.assertEquals('1', self.stack.get('one'))
2673
def test_simple_write_access(self):
2674
self.stack.set('one', 'one')
2675
self.assertEquals('one', self.stack.get('one'))
2677
def test_listen_to_the_last_speaker(self):
2679
c2 = self.get_stack(self)
2680
c1.set('one', 'ONE')
2681
c2.set('two', 'TWO')
2682
self.assertEquals('ONE', c1.get('one'))
2683
self.assertEquals('TWO', c2.get('two'))
2684
# The second update respect the first one
2685
self.assertEquals('ONE', c2.get('one'))
2687
def test_last_speaker_wins(self):
2688
# If the same config is not shared, the same variable modified twice
2689
# can only see a single result.
2691
c2 = self.get_stack(self)
2694
self.assertEquals('c2', c2.get('one'))
2695
# The first modification is still available until another refresh
2697
self.assertEquals('c1', c1.get('one'))
2698
c1.set('two', 'done')
2699
self.assertEquals('c2', c1.get('one'))
2701
def test_writes_are_serialized(self):
2703
c2 = self.get_stack(self)
2705
# We spawn a thread that will pause *during* the config saving.
2706
before_writing = threading.Event()
2707
after_writing = threading.Event()
2708
writing_done = threading.Event()
2709
c1_save_without_locking_orig = c1.store.save_without_locking
2710
def c1_save_without_locking():
2711
before_writing.set()
2712
c1_save_without_locking_orig()
2713
# The lock is held. We wait for the main thread to decide when to
2715
after_writing.wait()
2716
c1.store.save_without_locking = c1_save_without_locking
2720
t1 = threading.Thread(target=c1_set)
2721
# Collect the thread after the test
2722
self.addCleanup(t1.join)
2723
# Be ready to unblock the thread if the test goes wrong
2724
self.addCleanup(after_writing.set)
2726
before_writing.wait()
2727
self.assertRaises(errors.LockContention,
2728
c2.set, 'one', 'c2')
2729
self.assertEquals('c1', c1.get('one'))
2730
# Let the lock be released
2734
self.assertEquals('c2', c2.get('one'))
2736
def test_read_while_writing(self):
2738
# We spawn a thread that will pause *during* the write
2739
ready_to_write = threading.Event()
2740
do_writing = threading.Event()
2741
writing_done = threading.Event()
2742
# We override the _save implementation so we know the store is locked
2743
c1_save_without_locking_orig = c1.store.save_without_locking
2744
def c1_save_without_locking():
2745
ready_to_write.set()
2746
# The lock is held. We wait for the main thread to decide when to
2749
c1_save_without_locking_orig()
2751
c1.store.save_without_locking = c1_save_without_locking
2754
t1 = threading.Thread(target=c1_set)
2755
# Collect the thread after the test
2756
self.addCleanup(t1.join)
2757
# Be ready to unblock the thread if the test goes wrong
2758
self.addCleanup(do_writing.set)
2760
# Ensure the thread is ready to write
2761
ready_to_write.wait()
2762
self.assertEquals('c1', c1.get('one'))
2763
# If we read during the write, we get the old value
2764
c2 = self.get_stack(self)
2765
self.assertEquals('1', c2.get('one'))
2766
# Let the writing occur and ensure it occurred
2769
# Now we get the updated value
2770
c3 = self.get_stack(self)
2771
self.assertEquals('c1', c3.get('one'))
2773
# FIXME: It may be worth looking into removing the lock dir when it's not
2774
# needed anymore and look at possible fallouts for concurrent lockers. This
2775
# will matter if/when we use config files outside of bazaar directories
2776
# (.bazaar or .bzr) -- vila 20110-04-11
2779
class TestSectionMatcher(TestStore):
2781
scenarios = [('location', {'matcher': config.LocationMatcher})]
2783
def get_store(self, file_name):
2784
return config.IniFileStore(self.get_readonly_transport(), file_name)
2786
def test_no_matches_for_empty_stores(self):
2787
store = self.get_store('foo.conf')
2788
store._load_from_string('')
2789
matcher = self.matcher(store, '/bar')
2790
self.assertEquals([], list(matcher.get_sections()))
2792
def test_build_doesnt_load_store(self):
2793
store = self.get_store('foo.conf')
2794
matcher = self.matcher(store, '/bar')
2795
self.assertFalse(store.is_loaded())
2798
class TestLocationSection(tests.TestCase):
2800
def get_section(self, options, extra_path):
2801
section = config.Section('foo', options)
2802
# We don't care about the length so we use '0'
2803
return config.LocationSection(section, 0, extra_path)
2805
def test_simple_option(self):
2806
section = self.get_section({'foo': 'bar'}, '')
2807
self.assertEquals('bar', section.get('foo'))
2809
def test_option_with_extra_path(self):
2810
section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
2812
self.assertEquals('bar/baz', section.get('foo'))
2814
def test_invalid_policy(self):
2815
section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
2817
# invalid policies are ignored
2818
self.assertEquals('bar', section.get('foo'))
2821
class TestLocationMatcher(TestStore):
2823
def get_store(self, file_name):
2824
return config.IniFileStore(self.get_readonly_transport(), file_name)
2826
def test_more_specific_sections_first(self):
2827
store = self.get_store('foo.conf')
2828
store._load_from_string('''
2834
self.assertEquals(['/foo', '/foo/bar'],
2835
[section.id for section in store.get_sections()])
2836
matcher = config.LocationMatcher(store, '/foo/bar/baz')
2837
sections = list(matcher.get_sections())
2838
self.assertEquals([3, 2],
2839
[section.length for section in sections])
2840
self.assertEquals(['/foo/bar', '/foo'],
2841
[section.id for section in sections])
2842
self.assertEquals(['baz', 'bar/baz'],
2843
[section.extra_path for section in sections])
2845
def test_appendpath_in_no_name_section(self):
2846
# It's a bit weird to allow appendpath in a no-name section, but
2847
# someone may found a use for it
2848
store = self.get_store('foo.conf')
2849
store._load_from_string('''
2851
foo:policy = appendpath
2853
matcher = config.LocationMatcher(store, 'dir/subdir')
2854
sections = list(matcher.get_sections())
2855
self.assertLength(1, sections)
2856
self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
2858
def test_file_urls_are_normalized(self):
2859
store = self.get_store('foo.conf')
2860
if sys.platform == 'win32':
2861
expected_url = 'file:///C:/dir/subdir'
2862
expected_location = 'C:/dir/subdir'
2864
expected_url = 'file:///dir/subdir'
2865
expected_location = '/dir/subdir'
2866
matcher = config.LocationMatcher(store, expected_url)
2867
self.assertEquals(expected_location, matcher.location)
2870
class TestStackGet(tests.TestCase):
2872
# FIXME: This should be parametrized for all known Stack or dedicated
2873
# paramerized tests created to avoid bloating -- vila 2011-03-31
2875
def overrideOptionRegistry(self):
2876
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2878
def test_single_config_get(self):
2879
conf = dict(foo='bar')
2880
conf_stack = config.Stack([conf])
2881
self.assertEquals('bar', conf_stack.get('foo'))
2883
def test_get_with_registered_default_value(self):
2884
conf_stack = config.Stack([dict()])
2885
opt = config.Option('foo', default='bar')
2886
self.overrideOptionRegistry()
2887
config.option_registry.register('foo', opt)
2888
self.assertEquals('bar', conf_stack.get('foo'))
2890
def test_get_without_registered_default_value(self):
2891
conf_stack = config.Stack([dict()])
2892
opt = config.Option('foo')
2893
self.overrideOptionRegistry()
2894
config.option_registry.register('foo', opt)
2895
self.assertEquals(None, conf_stack.get('foo'))
2897
def test_get_without_default_value_for_not_registered(self):
2898
conf_stack = config.Stack([dict()])
2899
opt = config.Option('foo')
2900
self.overrideOptionRegistry()
2901
self.assertEquals(None, conf_stack.get('foo'))
2903
def test_get_first_definition(self):
2904
conf1 = dict(foo='bar')
2905
conf2 = dict(foo='baz')
2906
conf_stack = config.Stack([conf1, conf2])
2907
self.assertEquals('bar', conf_stack.get('foo'))
2909
def test_get_embedded_definition(self):
2910
conf1 = dict(yy='12')
2911
conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
2912
conf_stack = config.Stack([conf1, conf2])
2913
self.assertEquals('baz', conf_stack.get('foo'))
2915
def test_get_for_empty_section_callable(self):
2916
conf_stack = config.Stack([lambda : []])
2917
self.assertEquals(None, conf_stack.get('foo'))
2919
def test_get_for_broken_callable(self):
2920
# Trying to use and invalid callable raises an exception on first use
2921
conf_stack = config.Stack([lambda : object()])
2922
self.assertRaises(TypeError, conf_stack.get, 'foo')
2925
class TestStackWithTransport(tests.TestCaseWithTransport):
2927
scenarios = [(key, {'get_stack': builder}) for key, builder
2928
in config.test_stack_builder_registry.iteritems()]
2931
class TestConcreteStacks(TestStackWithTransport):
2933
def test_build_stack(self):
2934
# Just a smoke test to help debug builders
2935
stack = self.get_stack(self)
2938
class TestStackGet(TestStackWithTransport):
2941
super(TestStackGet, self).setUp()
2942
self.conf = self.get_stack(self)
2944
def test_get_for_empty_stack(self):
2945
self.assertEquals(None, self.conf.get('foo'))
2947
def test_get_hook(self):
2948
self.conf.store._load_from_string('foo=bar')
2952
config.ConfigHooks.install_named_hook('get', hook, None)
2953
self.assertLength(0, calls)
2954
value = self.conf.get('foo')
2955
self.assertEquals('bar', value)
2956
self.assertLength(1, calls)
2957
self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
2960
class TestStackGetWithConverter(TestStackGet):
2963
super(TestStackGetWithConverter, self).setUp()
2964
self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2965
self.registry = config.option_registry
2967
def register_bool_option(self, name, default, invalid=None):
2968
b = config.Option(name, default=default, help='A boolean.',
2969
from_unicode=config.bool_from_store,
2971
self.registry.register(b)
2973
def test_get_with_bool_not_defined_default_true(self):
2974
self.register_bool_option('foo', True)
2975
self.assertEquals(True, self.conf.get('foo'))
2977
def test_get_with_bool_not_defined_default_false(self):
2978
self.register_bool_option('foo', False)
2979
self.assertEquals(False, self.conf.get('foo'))
2981
def test_get_with_bool_converter_not_default(self):
2982
self.register_bool_option('foo', False)
2983
self.conf.store._load_from_string('foo=yes')
2984
self.assertEquals(True, self.conf.get('foo'))
2986
def test_get_with_bool_converter_invalid_string(self):
2987
self.register_bool_option('foo', False)
2988
self.conf.store._load_from_string('foo=not-a-boolean')
2989
self.assertEquals(False, self.conf.get('foo'))
2991
def test_get_with_bool_converter_invalid_list(self):
2992
self.register_bool_option('foo', False)
2993
self.conf.store._load_from_string('foo=not,a,boolean')
2994
self.assertEquals(False, self.conf.get('foo'))
2996
def test_get_invalid_warns(self):
2997
self.register_bool_option('foo', False, invalid='warning')
2998
self.conf.store._load_from_string('foo=not-a-boolean')
3001
warnings.append(args[0] % args[1:])
3002
self.overrideAttr(trace, 'warning', warning)
3003
self.assertEquals(False, self.conf.get('foo'))
3004
self.assertLength(1, warnings)
3005
self.assertEquals('Value "not-a-boolean" is not valid for "foo"',
3008
def test_get_invalid_errors(self):
3009
self.register_bool_option('foo', False, invalid='error')
3010
self.conf.store._load_from_string('foo=not-a-boolean')
3011
self.assertRaises(errors.ConfigOptionValueError, self.conf.get, 'foo')
3013
def register_integer_option(self, name, default):
3014
i = config.Option(name, default=default, help='An integer.',
3015
from_unicode=config.int_from_store)
3016
self.registry.register(i)
3018
def test_get_with_integer_not_defined_returns_default(self):
3019
self.register_integer_option('foo', 42)
3020
self.assertEquals(42, self.conf.get('foo'))
3022
def test_get_with_integer_converter_not_default(self):
3023
self.register_integer_option('foo', 42)
3024
self.conf.store._load_from_string('foo=16')
3025
self.assertEquals(16, self.conf.get('foo'))
3027
def test_get_with_integer_converter_invalid_string(self):
3028
# We don't set a default value
3029
self.register_integer_option('foo', None)
3030
self.conf.store._load_from_string('foo=forty-two')
3031
# No default value, so we should get None
3032
self.assertEquals(None, self.conf.get('foo'))
3034
def test_get_with_integer_converter_invalid_list(self):
3035
# We don't set a default value
3036
self.register_integer_option('foo', None)
3037
self.conf.store._load_from_string('foo=a,list')
3038
# No default value, so we should get None
3039
self.assertEquals(None, self.conf.get('foo'))
3041
def register_list_option(self, name, default):
3042
l = config.Option(name, default=default, help='A list.',
3043
from_unicode=config.list_from_store)
3044
self.registry.register(l)
3046
def test_get_with_list_not_defined_returns_default(self):
3047
self.register_list_option('foo', [])
3048
self.assertEquals([], self.conf.get('foo'))
3050
def test_get_with_list_converter_nothing(self):
3051
self.register_list_option('foo', [1])
3052
self.conf.store._load_from_string('foo=')
3053
self.assertEquals([], self.conf.get('foo'))
3055
def test_get_with_list_converter_no_item(self):
3056
self.register_list_option('foo', [1])
3057
self.conf.store._load_from_string('foo=,')
3058
self.assertEquals([], self.conf.get('foo'))
3060
def test_get_with_list_converter_one_boolean(self):
3061
self.register_list_option('foo', [1])
3062
self.conf.store._load_from_string('foo=True')
3063
# We get a list of one string
3064
self.assertEquals(['True'], self.conf.get('foo'))
3066
def test_get_with_list_converter_one_integer(self):
3067
self.register_list_option('foo', [1])
3068
self.conf.store._load_from_string('foo=2')
3069
# We get a list of one string
3070
self.assertEquals(['2'], self.conf.get('foo'))
3072
def test_get_with_list_converter_one_string(self):
3073
self.register_list_option('foo', ['foo'])
3074
self.conf.store._load_from_string('foo=bar')
3075
# We get a list of one string
3076
self.assertEquals(['bar'], self.conf.get('foo'))
3078
def test_get_with_list_converter_many_items(self):
3079
self.register_list_option('foo', [1])
3080
self.conf.store._load_from_string('foo=m,o,r,e')
3081
self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
3084
class TestStackSet(TestStackWithTransport):
3086
def test_simple_set(self):
3087
conf = self.get_stack(self)
3088
conf.store._load_from_string('foo=bar')
3089
self.assertEquals('bar', conf.get('foo'))
3090
conf.set('foo', 'baz')
3091
# Did we get it back ?
3092
self.assertEquals('baz', conf.get('foo'))
3094
def test_set_creates_a_new_section(self):
3095
conf = self.get_stack(self)
3096
conf.set('foo', 'baz')
3097
self.assertEquals, 'baz', conf.get('foo')
3099
def test_set_hook(self):
3103
config.ConfigHooks.install_named_hook('set', hook, None)
3104
self.assertLength(0, calls)
3105
conf = self.get_stack(self)
3106
conf.set('foo', 'bar')
3107
self.assertLength(1, calls)
3108
self.assertEquals((conf, 'foo', 'bar'), calls[0])
3111
class TestStackRemove(TestStackWithTransport):
3113
def test_remove_existing(self):
3114
conf = self.get_stack(self)
3115
conf.store._load_from_string('foo=bar')
3116
self.assertEquals('bar', conf.get('foo'))
3118
# Did we get it back ?
3119
self.assertEquals(None, conf.get('foo'))
3121
def test_remove_unknown(self):
3122
conf = self.get_stack(self)
3123
self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3125
def test_remove_hook(self):
3129
config.ConfigHooks.install_named_hook('remove', hook, None)
3130
self.assertLength(0, calls)
3131
conf = self.get_stack(self)
3132
conf.store._load_from_string('foo=bar')
3134
self.assertLength(1, calls)
3135
self.assertEquals((conf, 'foo'), calls[0])
3138
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3141
super(TestConfigGetOptions, self).setUp()
3142
create_configs(self)
3144
def test_no_variable(self):
3145
# Using branch should query branch, locations and bazaar
3146
self.assertOptions([], self.branch_config)
3148
def test_option_in_bazaar(self):
3149
self.bazaar_config.set_user_option('file', 'bazaar')
3150
self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
3153
def test_option_in_locations(self):
3154
self.locations_config.set_user_option('file', 'locations')
3156
[('file', 'locations', self.tree.basedir, 'locations')],
3157
self.locations_config)
3159
def test_option_in_branch(self):
3160
self.branch_config.set_user_option('file', 'branch')
3161
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
3164
def test_option_in_bazaar_and_branch(self):
3165
self.bazaar_config.set_user_option('file', 'bazaar')
3166
self.branch_config.set_user_option('file', 'branch')
3167
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
3168
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3171
def test_option_in_branch_and_locations(self):
3172
# Hmm, locations override branch :-/
3173
self.locations_config.set_user_option('file', 'locations')
3174
self.branch_config.set_user_option('file', 'branch')
3176
[('file', 'locations', self.tree.basedir, 'locations'),
3177
('file', 'branch', 'DEFAULT', 'branch'),],
3180
def test_option_in_bazaar_locations_and_branch(self):
3181
self.bazaar_config.set_user_option('file', 'bazaar')
3182
self.locations_config.set_user_option('file', 'locations')
3183
self.branch_config.set_user_option('file', 'branch')
3185
[('file', 'locations', self.tree.basedir, 'locations'),
3186
('file', 'branch', 'DEFAULT', 'branch'),
3187
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3191
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
3194
super(TestConfigRemoveOption, self).setUp()
3195
create_configs_with_file_option(self)
3197
def test_remove_in_locations(self):
3198
self.locations_config.remove_user_option('file', self.tree.basedir)
3200
[('file', 'branch', 'DEFAULT', 'branch'),
3201
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3204
def test_remove_in_branch(self):
3205
self.branch_config.remove_user_option('file')
3207
[('file', 'locations', self.tree.basedir, 'locations'),
3208
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3211
def test_remove_in_bazaar(self):
3212
self.bazaar_config.remove_user_option('file')
3214
[('file', 'locations', self.tree.basedir, 'locations'),
3215
('file', 'branch', 'DEFAULT', 'branch'),],
3219
class TestConfigGetSections(tests.TestCaseWithTransport):
3222
super(TestConfigGetSections, self).setUp()
3223
create_configs(self)
3225
def assertSectionNames(self, expected, conf, name=None):
3226
"""Check which sections are returned for a given config.
3228
If fallback configurations exist their sections can be included.
3230
:param expected: A list of section names.
3232
:param conf: The configuration that will be queried.
3234
:param name: An optional section name that will be passed to
3237
sections = list(conf._get_sections(name))
3238
self.assertLength(len(expected), sections)
3239
self.assertEqual(expected, [name for name, _, _ in sections])
3241
def test_bazaar_default_section(self):
3242
self.assertSectionNames(['DEFAULT'], self.bazaar_config)
3244
def test_locations_default_section(self):
3245
# No sections are defined in an empty file
3246
self.assertSectionNames([], self.locations_config)
3248
def test_locations_named_section(self):
3249
self.locations_config.set_user_option('file', 'locations')
3250
self.assertSectionNames([self.tree.basedir], self.locations_config)
3252
def test_locations_matching_sections(self):
3253
loc_config = self.locations_config
3254
loc_config.set_user_option('file', 'locations')
3255
# We need to cheat a bit here to create an option in sections above and
3256
# below the 'location' one.
3257
parser = loc_config._get_parser()
3258
# locations.cong deals with '/' ignoring native os.sep
3259
location_names = self.tree.basedir.split('/')
3260
parent = '/'.join(location_names[:-1])
3261
child = '/'.join(location_names + ['child'])
3263
parser[parent]['file'] = 'parent'
3265
parser[child]['file'] = 'child'
3266
self.assertSectionNames([self.tree.basedir, parent], loc_config)
3268
def test_branch_data_default_section(self):
3269
self.assertSectionNames([None],
3270
self.branch_config._get_branch_data_config())
3272
def test_branch_default_sections(self):
3273
# No sections are defined in an empty locations file
3274
self.assertSectionNames([None, 'DEFAULT'],
3276
# Unless we define an option
3277
self.branch_config._get_location_config().set_user_option(
3278
'file', 'locations')
3279
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
3282
def test_bazaar_named_section(self):
3283
# We need to cheat as the API doesn't give direct access to sections
3284
# other than DEFAULT.
3285
self.bazaar_config.set_alias('bazaar', 'bzr')
3286
self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
3289
1220
class TestAuthenticationConfigFile(tests.TestCase):
3290
1221
"""Test the authentication.conf file matching"""