~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Vincent Ladeuil
  • Date: 2011-05-17 20:58:43 UTC
  • mfrom: (5609.39.5 2.3)
  • mto: This revision was merged to the branch mainline in revision 5885.
  • Revision ID: v.ladeuil+lp@free.fr-20110517205843-uo1tntrz6kqfn1hb
Merge 2.3 into trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
21
21
import sys
22
22
import threading
23
23
 
 
24
 
 
25
from testtools import matchers
 
26
 
24
27
#import bzrlib specific imports here
25
28
from bzrlib import (
26
29
    branch,
30
33
    errors,
31
34
    osutils,
32
35
    mail_client,
 
36
    mergetools,
33
37
    ui,
34
38
    urlutils,
 
39
    registry,
35
40
    tests,
36
41
    trace,
37
42
    transport,
38
43
    )
39
 
from bzrlib.tests import features
 
44
from bzrlib.tests import (
 
45
    features,
 
46
    TestSkipped,
 
47
    scenarios,
 
48
    )
40
49
from bzrlib.util.configobj import configobj
41
50
 
42
51
 
52
61
          'config_section': '.'}),]
53
62
 
54
63
 
55
 
def load_tests(standard_tests, module, loader):
56
 
    suite = loader.suiteClass()
57
 
 
58
 
    lc_tests, remaining_tests = tests.split_suite_by_condition(
59
 
        standard_tests, tests.condition_isinstance((
60
 
                TestLockableConfig,
61
 
                )))
62
 
    tests.multiply_tests(lc_tests, lockable_config_scenarios(), suite)
63
 
    suite.addTest(remaining_tests)
64
 
    return suite
 
64
load_tests = scenarios.load_tests_apply_scenarios
 
65
 
 
66
# We need adapters that can build a config store in a test context. Test
 
67
# classes, based on TestCaseWithTransport, can use the registry to parametrize
 
68
# themselves. The builder will receive a test instance and should return a
 
69
# ready-to-use store.  Plugins that defines new stores can also register
 
70
# themselves here to be tested against the tests defined below.
 
71
 
 
72
# FIXME: plugins should *not* need to import test_config to register their
 
73
# helpers (or selftest -s xxx will be broken), the following registry should be
 
74
# moved to bzrlib.config instead so that selftest -s bt.test_config also runs
 
75
# the plugin specific tests (selftest -s bp.xxx won't, that would be against
 
76
# the spirit of '-s') -- vila 20110503
 
77
test_store_builder_registry = registry.Registry()
 
78
test_store_builder_registry.register(
 
79
    'configobj', lambda test: config.IniFileStore(test.get_transport(),
 
80
                                                  'configobj.conf'))
 
81
test_store_builder_registry.register(
 
82
    'bazaar', lambda test: config.GlobalStore())
 
83
test_store_builder_registry.register(
 
84
    'location', lambda test: config.LocationStore())
 
85
test_store_builder_registry.register(
 
86
    'branch', lambda test: config.BranchStore(test.branch))
 
87
 
65
88
 
66
89
 
67
90
sample_long_alias="log -r-15..-1 --line"
73
96
gpg_signing_command=gnome-gpg
74
97
log_format=short
75
98
user_global_option=something
 
99
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
 
100
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
 
101
bzr.default_mergetool=sometool
76
102
[ALIASES]
77
103
h=help
78
104
ll=""" + sample_long_alias + "\n"
131
157
"""
132
158
 
133
159
 
 
160
def create_configs(test):
 
161
    """Create configuration files for a given test.
 
162
 
 
163
    This requires creating a tree (and populate the ``test.tree`` attribute)
 
164
    and its associated branch and will populate the following attributes:
 
165
 
 
166
    - branch_config: A BranchConfig for the associated branch.
 
167
 
 
168
    - locations_config : A LocationConfig for the associated branch
 
169
 
 
170
    - bazaar_config: A GlobalConfig.
 
171
 
 
172
    The tree and branch are created in a 'tree' subdirectory so the tests can
 
173
    still use the test directory to stay outside of the branch.
 
174
    """
 
175
    tree = test.make_branch_and_tree('tree')
 
176
    test.tree = tree
 
177
    test.branch_config = config.BranchConfig(tree.branch)
 
178
    test.locations_config = config.LocationConfig(tree.basedir)
 
179
    test.bazaar_config = config.GlobalConfig()
 
180
 
 
181
 
 
182
def create_configs_with_file_option(test):
 
183
    """Create configuration files with a ``file`` option set in each.
 
184
 
 
185
    This builds on ``create_configs`` and add one ``file`` option in each
 
186
    configuration with a value which allows identifying the configuration file.
 
187
    """
 
188
    create_configs(test)
 
189
    test.bazaar_config.set_user_option('file', 'bazaar')
 
190
    test.locations_config.set_user_option('file', 'locations')
 
191
    test.branch_config.set_user_option('file', 'branch')
 
192
 
 
193
 
 
194
class TestOptionsMixin:
 
195
 
 
196
    def assertOptions(self, expected, conf):
 
197
        # We don't care about the parser (as it will make tests hard to write
 
198
        # and error-prone anyway)
 
199
        self.assertThat([opt[:4] for opt in conf._get_options()],
 
200
                        matchers.Equals(expected))
 
201
 
 
202
 
134
203
class InstrumentedConfigObj(object):
135
204
    """A config obj look-enough-alike to record calls made to it."""
136
205
 
269
338
        """
270
339
        co = config.ConfigObj()
271
340
        co['test'] = 'foo#bar'
272
 
        lines = co.write()
 
341
        outfile = StringIO()
 
342
        co.write(outfile=outfile)
 
343
        lines = outfile.getvalue().splitlines()
273
344
        self.assertEqual(lines, ['test = "foo#bar"'])
274
345
        co2 = config.ConfigObj(lines)
275
346
        self.assertEqual(co2['test'], 'foo#bar')
276
347
 
 
348
    def test_triple_quotes(self):
 
349
        # Bug #710410: if the value string has triple quotes
 
350
        # then ConfigObj versions up to 4.7.2 will quote them wrong
 
351
        # and won't able to read them back
 
352
        triple_quotes_value = '''spam
 
353
""" that's my spam """
 
354
eggs'''
 
355
        co = config.ConfigObj()
 
356
        co['test'] = triple_quotes_value
 
357
        # While writing this test another bug in ConfigObj has been found:
 
358
        # method co.write() without arguments produces list of lines
 
359
        # one option per line, and multiline values are not split
 
360
        # across multiple lines,
 
361
        # and that breaks the parsing these lines back by ConfigObj.
 
362
        # This issue only affects test, but it's better to avoid
 
363
        # `co.write()` construct at all.
 
364
        # [bialix 20110222] bug report sent to ConfigObj's author
 
365
        outfile = StringIO()
 
366
        co.write(outfile=outfile)
 
367
        output = outfile.getvalue()
 
368
        # now we're trying to read it back
 
369
        co2 = config.ConfigObj(StringIO(output))
 
370
        self.assertEquals(triple_quotes_value, co2['test'])
 
371
 
277
372
 
278
373
erroneous_config = """[section] # line 1
279
374
good=good # line 2
362
457
 
363
458
    def setUp(self):
364
459
        super(TestConfigPath, self).setUp()
365
 
        os.environ['HOME'] = '/home/bogus'
366
 
        os.environ['XDG_CACHE_DIR'] = ''
 
460
        self.overrideEnv('HOME', '/home/bogus')
 
461
        self.overrideEnv('XDG_CACHE_DIR', '')
367
462
        if sys.platform == 'win32':
368
 
            os.environ['BZR_HOME'] = \
369
 
                r'C:\Documents and Settings\bogus\Application Data'
 
463
            self.overrideEnv(
 
464
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
370
465
            self.bzr_home = \
371
466
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
372
467
        else:
392
487
            '/home/bogus/.cache')
393
488
 
394
489
 
 
490
class TestXDGConfigDir(tests.TestCaseInTempDir):
 
491
    # must be in temp dir because config tests for the existence of the bazaar
 
492
    # subdirectory of $XDG_CONFIG_HOME
 
493
 
 
494
    def setUp(self):
 
495
        if sys.platform in ('darwin', 'win32'):
 
496
            raise tests.TestNotApplicable(
 
497
                'XDG config dir not used on this platform')
 
498
        super(TestXDGConfigDir, self).setUp()
 
499
        self.overrideEnv('HOME', self.test_home_dir)
 
500
        # BZR_HOME overrides everything we want to test so unset it.
 
501
        self.overrideEnv('BZR_HOME', None)
 
502
 
 
503
    def test_xdg_config_dir_exists(self):
 
504
        """When ~/.config/bazaar exists, use it as the config dir."""
 
505
        newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
 
506
        os.makedirs(newdir)
 
507
        self.assertEqual(config.config_dir(), newdir)
 
508
 
 
509
    def test_xdg_config_home(self):
 
510
        """When XDG_CONFIG_HOME is set, use it."""
 
511
        xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
 
512
        self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
 
513
        newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
 
514
        os.makedirs(newdir)
 
515
        self.assertEqual(config.config_dir(), newdir)
 
516
 
 
517
 
395
518
class TestIniConfig(tests.TestCaseInTempDir):
396
519
 
397
520
    def make_config_parser(self, s):
411
534
    def test_cached(self):
412
535
        my_config = config.IniBasedConfig.from_string(sample_config_text)
413
536
        parser = my_config._get_parser()
414
 
        self.failUnless(my_config._get_parser() is parser)
 
537
        self.assertTrue(my_config._get_parser() is parser)
415
538
 
416
539
    def _dummy_chown(self, path, uid, gid):
417
540
        self.path, self.uid, self.gid = path, uid, gid
442
565
            ' Use IniBasedConfig(_content=xxx) instead.'],
443
566
            conf._get_parser, file=config_file)
444
567
 
 
568
 
445
569
class TestIniConfigSaving(tests.TestCaseInTempDir):
446
570
 
447
571
    def test_cant_save_without_a_file_name(self):
455
579
        self.assertFileEqual(content, 'test.conf')
456
580
 
457
581
 
 
582
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
 
583
    """What is the default value of expand for config options.
 
584
 
 
585
    This is an opt-in beta feature used to evaluate whether or not option
 
586
    references can appear in dangerous place raising exceptions, disapearing
 
587
    (and as such corrupting data) or if it's safe to activate the option by
 
588
    default.
 
589
 
 
590
    Note that these tests relies on config._expand_default_value being already
 
591
    overwritten in the parent class setUp.
 
592
    """
 
593
 
 
594
    def setUp(self):
 
595
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
 
596
        self.config = None
 
597
        self.warnings = []
 
598
        def warning(*args):
 
599
            self.warnings.append(args[0] % args[1:])
 
600
        self.overrideAttr(trace, 'warning', warning)
 
601
 
 
602
    def get_config(self, expand):
 
603
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
 
604
                                            save=True)
 
605
        return c
 
606
 
 
607
    def assertExpandIs(self, expected):
 
608
        actual = config._get_expand_default_value()
 
609
        #self.config.get_user_option_as_bool('bzr.config.expand')
 
610
        self.assertEquals(expected, actual)
 
611
 
 
612
    def test_default_is_None(self):
 
613
        self.assertEquals(None, config._expand_default_value)
 
614
 
 
615
    def test_default_is_False_even_if_None(self):
 
616
        self.config = self.get_config(None)
 
617
        self.assertExpandIs(False)
 
618
 
 
619
    def test_default_is_False_even_if_invalid(self):
 
620
        self.config = self.get_config('<your choice>')
 
621
        self.assertExpandIs(False)
 
622
        # ...
 
623
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
 
624
        # Wait, you've been warned !
 
625
        self.assertLength(1, self.warnings)
 
626
        self.assertEquals(
 
627
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
 
628
            self.warnings[0])
 
629
 
 
630
    def test_default_is_True(self):
 
631
        self.config = self.get_config(True)
 
632
        self.assertExpandIs(True)
 
633
        
 
634
    def test_default_is_False(self):
 
635
        self.config = self.get_config(False)
 
636
        self.assertExpandIs(False)
 
637
        
 
638
 
 
639
class TestIniConfigOptionExpansion(tests.TestCase):
 
640
    """Test option expansion from the IniConfig level.
 
641
 
 
642
    What we really want here is to test the Config level, but the class being
 
643
    abstract as far as storing values is concerned, this can't be done
 
644
    properly (yet).
 
645
    """
 
646
    # FIXME: This should be rewritten when all configs share a storage
 
647
    # implementation -- vila 2011-02-18
 
648
 
 
649
    def get_config(self, string=None):
 
650
        if string is None:
 
651
            string = ''
 
652
        c = config.IniBasedConfig.from_string(string)
 
653
        return c
 
654
 
 
655
    def assertExpansion(self, expected, conf, string, env=None):
 
656
        self.assertEquals(expected, conf.expand_options(string, env))
 
657
 
 
658
    def test_no_expansion(self):
 
659
        c = self.get_config('')
 
660
        self.assertExpansion('foo', c, 'foo')
 
661
 
 
662
    def test_env_adding_options(self):
 
663
        c = self.get_config('')
 
664
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
665
 
 
666
    def test_env_overriding_options(self):
 
667
        c = self.get_config('foo=baz')
 
668
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
669
 
 
670
    def test_simple_ref(self):
 
671
        c = self.get_config('foo=xxx')
 
672
        self.assertExpansion('xxx', c, '{foo}')
 
673
 
 
674
    def test_unknown_ref(self):
 
675
        c = self.get_config('')
 
676
        self.assertRaises(errors.ExpandingUnknownOption,
 
677
                          c.expand_options, '{foo}')
 
678
 
 
679
    def test_indirect_ref(self):
 
680
        c = self.get_config('''
 
681
foo=xxx
 
682
bar={foo}
 
683
''')
 
684
        self.assertExpansion('xxx', c, '{bar}')
 
685
 
 
686
    def test_embedded_ref(self):
 
687
        c = self.get_config('''
 
688
foo=xxx
 
689
bar=foo
 
690
''')
 
691
        self.assertExpansion('xxx', c, '{{bar}}')
 
692
 
 
693
    def test_simple_loop(self):
 
694
        c = self.get_config('foo={foo}')
 
695
        self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
 
696
 
 
697
    def test_indirect_loop(self):
 
698
        c = self.get_config('''
 
699
foo={bar}
 
700
bar={baz}
 
701
baz={foo}''')
 
702
        e = self.assertRaises(errors.OptionExpansionLoop,
 
703
                              c.expand_options, '{foo}')
 
704
        self.assertEquals('foo->bar->baz', e.refs)
 
705
        self.assertEquals('{foo}', e.string)
 
706
 
 
707
    def test_list(self):
 
708
        conf = self.get_config('''
 
709
foo=start
 
710
bar=middle
 
711
baz=end
 
712
list={foo},{bar},{baz}
 
713
''')
 
714
        self.assertEquals(['start', 'middle', 'end'],
 
715
                           conf.get_user_option('list', expand=True))
 
716
 
 
717
    def test_cascading_list(self):
 
718
        conf = self.get_config('''
 
719
foo=start,{bar}
 
720
bar=middle,{baz}
 
721
baz=end
 
722
list={foo}
 
723
''')
 
724
        self.assertEquals(['start', 'middle', 'end'],
 
725
                           conf.get_user_option('list', expand=True))
 
726
 
 
727
    def test_pathological_hidden_list(self):
 
728
        conf = self.get_config('''
 
729
foo=bin
 
730
bar=go
 
731
start={foo
 
732
middle=},{
 
733
end=bar}
 
734
hidden={start}{middle}{end}
 
735
''')
 
736
        # Nope, it's either a string or a list, and the list wins as soon as a
 
737
        # ',' appears, so the string concatenation never occur.
 
738
        self.assertEquals(['{foo', '}', '{', 'bar}'],
 
739
                          conf.get_user_option('hidden', expand=True))
 
740
 
 
741
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
 
742
 
 
743
    def get_config(self, location, string=None):
 
744
        if string is None:
 
745
            string = ''
 
746
        # Since we don't save the config we won't strictly require to inherit
 
747
        # from TestCaseInTempDir, but an error occurs so quickly...
 
748
        c = config.LocationConfig.from_string(string, location)
 
749
        return c
 
750
 
 
751
    def test_dont_cross_unrelated_section(self):
 
752
        c = self.get_config('/another/branch/path','''
 
753
[/one/branch/path]
 
754
foo = hello
 
755
bar = {foo}/2
 
756
 
 
757
[/another/branch/path]
 
758
bar = {foo}/2
 
759
''')
 
760
        self.assertRaises(errors.ExpandingUnknownOption,
 
761
                          c.get_user_option, 'bar', expand=True)
 
762
 
 
763
    def test_cross_related_sections(self):
 
764
        c = self.get_config('/project/branch/path','''
 
765
[/project]
 
766
foo = qu
 
767
 
 
768
[/project/branch/path]
 
769
bar = {foo}ux
 
770
''')
 
771
        self.assertEquals('quux', c.get_user_option('bar', expand=True))
 
772
 
 
773
 
458
774
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
459
775
 
460
776
    def test_cannot_reload_without_name(self):
477
793
 
478
794
class TestLockableConfig(tests.TestCaseInTempDir):
479
795
 
 
796
    scenarios = lockable_config_scenarios()
 
797
 
480
798
    # Set by load_tests
481
799
    config_class = None
482
800
    config_args = None
538
856
        def c1_write_config_file():
539
857
            before_writing.set()
540
858
            c1_orig()
541
 
            # The lock is held we wait for the main thread to decide when to
 
859
            # The lock is held. We wait for the main thread to decide when to
542
860
            # continue
543
861
            after_writing.wait()
544
862
        c1._write_config_file = c1_write_config_file
571
889
       c1_orig = c1._write_config_file
572
890
       def c1_write_config_file():
573
891
           ready_to_write.set()
574
 
           # The lock is held we wait for the main thread to decide when to
 
892
           # The lock is held. We wait for the main thread to decide when to
575
893
           # continue
576
894
           do_writing.wait()
577
895
           c1_orig()
668
986
            parser = my_config._get_parser()
669
987
        finally:
670
988
            config.ConfigObj = oldparserclass
671
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
989
        self.assertIsInstance(parser, InstrumentedConfigObj)
672
990
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
673
991
                                          'utf-8')])
674
992
 
685
1003
        my_config = config.BranchConfig(branch)
686
1004
        location_config = my_config._get_location_config()
687
1005
        self.assertEqual(branch.base, location_config.location)
688
 
        self.failUnless(location_config is my_config._get_location_config())
 
1006
        self.assertIs(location_config, my_config._get_location_config())
689
1007
 
690
1008
    def test_get_config(self):
691
1009
        """The Branch.get_config method works properly"""
883
1201
        change_editor = my_config.get_change_editor('old', 'new')
884
1202
        self.assertIs(None, change_editor)
885
1203
 
 
1204
    def test_get_merge_tools(self):
 
1205
        conf = self._get_sample_config()
 
1206
        tools = conf.get_merge_tools()
 
1207
        self.log(repr(tools))
 
1208
        self.assertEqual(
 
1209
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
 
1210
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
 
1211
            tools)
 
1212
 
 
1213
    def test_get_merge_tools_empty(self):
 
1214
        conf = self._get_empty_config()
 
1215
        tools = conf.get_merge_tools()
 
1216
        self.assertEqual({}, tools)
 
1217
 
 
1218
    def test_find_merge_tool(self):
 
1219
        conf = self._get_sample_config()
 
1220
        cmdline = conf.find_merge_tool('sometool')
 
1221
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
 
1222
 
 
1223
    def test_find_merge_tool_not_found(self):
 
1224
        conf = self._get_sample_config()
 
1225
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
 
1226
        self.assertIs(cmdline, None)
 
1227
 
 
1228
    def test_find_merge_tool_known(self):
 
1229
        conf = self._get_empty_config()
 
1230
        cmdline = conf.find_merge_tool('kdiff3')
 
1231
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
 
1232
 
 
1233
    def test_find_merge_tool_override_known(self):
 
1234
        conf = self._get_empty_config()
 
1235
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
 
1236
        cmdline = conf.find_merge_tool('kdiff3')
 
1237
        self.assertEqual('kdiff3 blah', cmdline)
 
1238
 
886
1239
 
887
1240
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
888
1241
 
906
1259
        self.assertIs(None, new_config.get_alias('commit'))
907
1260
 
908
1261
 
909
 
class TestLocationConfig(tests.TestCaseInTempDir):
 
1262
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
910
1263
 
911
1264
    def test_constructs(self):
912
1265
        my_config = config.LocationConfig('http://example.com')
924
1277
            parser = my_config._get_parser()
925
1278
        finally:
926
1279
            config.ConfigObj = oldparserclass
927
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
1280
        self.assertIsInstance(parser, InstrumentedConfigObj)
928
1281
        self.assertEqual(parser._calls,
929
1282
                         [('__init__', config.locations_config_filename(),
930
1283
                           'utf-8')])
932
1285
    def test_get_global_config(self):
933
1286
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
934
1287
        global_config = my_config._get_global_config()
935
 
        self.failUnless(isinstance(global_config, config.GlobalConfig))
936
 
        self.failUnless(global_config is my_config._get_global_config())
 
1288
        self.assertIsInstance(global_config, config.GlobalConfig)
 
1289
        self.assertIs(global_config, my_config._get_global_config())
 
1290
 
 
1291
    def assertLocationMatching(self, expected):
 
1292
        self.assertEqual(expected,
 
1293
                         list(self.my_location_config._get_matching_sections()))
937
1294
 
938
1295
    def test__get_matching_sections_no_match(self):
939
1296
        self.get_branch_config('/')
940
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1297
        self.assertLocationMatching([])
941
1298
 
942
1299
    def test__get_matching_sections_exact(self):
943
1300
        self.get_branch_config('http://www.example.com')
944
 
        self.assertEqual([('http://www.example.com', '')],
945
 
                         self.my_location_config._get_matching_sections())
 
1301
        self.assertLocationMatching([('http://www.example.com', '')])
946
1302
 
947
1303
    def test__get_matching_sections_suffix_does_not(self):
948
1304
        self.get_branch_config('http://www.example.com-com')
949
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1305
        self.assertLocationMatching([])
950
1306
 
951
1307
    def test__get_matching_sections_subdir_recursive(self):
952
1308
        self.get_branch_config('http://www.example.com/com')
953
 
        self.assertEqual([('http://www.example.com', 'com')],
954
 
                         self.my_location_config._get_matching_sections())
 
1309
        self.assertLocationMatching([('http://www.example.com', 'com')])
955
1310
 
956
1311
    def test__get_matching_sections_ignoreparent(self):
957
1312
        self.get_branch_config('http://www.example.com/ignoreparent')
958
 
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
959
 
                         self.my_location_config._get_matching_sections())
 
1313
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1314
                                      '')])
960
1315
 
961
1316
    def test__get_matching_sections_ignoreparent_subdir(self):
962
1317
        self.get_branch_config(
963
1318
            'http://www.example.com/ignoreparent/childbranch')
964
 
        self.assertEqual([('http://www.example.com/ignoreparent',
965
 
                           'childbranch')],
966
 
                         self.my_location_config._get_matching_sections())
 
1319
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1320
                                      'childbranch')])
967
1321
 
968
1322
    def test__get_matching_sections_subdir_trailing_slash(self):
969
1323
        self.get_branch_config('/b')
970
 
        self.assertEqual([('/b/', '')],
971
 
                         self.my_location_config._get_matching_sections())
 
1324
        self.assertLocationMatching([('/b/', '')])
972
1325
 
973
1326
    def test__get_matching_sections_subdir_child(self):
974
1327
        self.get_branch_config('/a/foo')
975
 
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
976
 
                         self.my_location_config._get_matching_sections())
 
1328
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
977
1329
 
978
1330
    def test__get_matching_sections_subdir_child_child(self):
979
1331
        self.get_branch_config('/a/foo/bar')
980
 
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
981
 
                         self.my_location_config._get_matching_sections())
 
1332
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
982
1333
 
983
1334
    def test__get_matching_sections_trailing_slash_with_children(self):
984
1335
        self.get_branch_config('/a/')
985
 
        self.assertEqual([('/a/', '')],
986
 
                         self.my_location_config._get_matching_sections())
 
1336
        self.assertLocationMatching([('/a/', '')])
987
1337
 
988
1338
    def test__get_matching_sections_explicit_over_glob(self):
989
1339
        # XXX: 2006-09-08 jamesh
991
1341
        # was a config section for '/a/?', it would get precedence
992
1342
        # over '/a/c'.
993
1343
        self.get_branch_config('/a/c')
994
 
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
995
 
                         self.my_location_config._get_matching_sections())
 
1344
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
996
1345
 
997
1346
    def test__get_option_policy_normal(self):
998
1347
        self.get_branch_config('http://www.example.com')
1020
1369
            'http://www.example.com', 'appendpath_option'),
1021
1370
            config.POLICY_APPENDPATH)
1022
1371
 
 
1372
    def test__get_options_with_policy(self):
 
1373
        self.get_branch_config('/dir/subdir',
 
1374
                               location_config="""\
 
1375
[/dir]
 
1376
other_url = /other-dir
 
1377
other_url:policy = appendpath
 
1378
[/dir/subdir]
 
1379
other_url = /other-subdir
 
1380
""")
 
1381
        self.assertOptions(
 
1382
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
 
1383
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
 
1384
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
 
1385
            self.my_location_config)
 
1386
 
1023
1387
    def test_location_without_username(self):
1024
1388
        self.get_branch_config('http://www.example.com/ignoreparent')
1025
1389
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1161
1525
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1162
1526
                         self.my_config.post_commit())
1163
1527
 
1164
 
    def get_branch_config(self, location, global_config=None):
 
1528
    def get_branch_config(self, location, global_config=None,
 
1529
                          location_config=None):
1165
1530
        my_branch = FakeBranch(location)
1166
1531
        if global_config is None:
1167
1532
            global_config = sample_config_text
 
1533
        if location_config is None:
 
1534
            location_config = sample_branches_text
1168
1535
 
1169
1536
        my_global_config = config.GlobalConfig.from_string(global_config,
1170
1537
                                                           save=True)
1171
1538
        my_location_config = config.LocationConfig.from_string(
1172
 
            sample_branches_text, my_branch.base, save=True)
 
1539
            location_config, my_branch.base, save=True)
1173
1540
        my_config = config.BranchConfig(my_branch)
1174
1541
        self.my_config = my_config
1175
1542
        self.my_location_config = my_config._get_location_config()
1220
1587
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1221
1588
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1222
1589
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1223
 
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
1590
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1224
1591
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1225
1592
 
1226
1593
 
1272
1639
        self.assertEqual("John", my_config._get_user_id())
1273
1640
 
1274
1641
    def test_BZR_EMAIL_OVERRIDES(self):
1275
 
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
 
1642
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1276
1643
        branch = FakeBranch()
1277
1644
        my_config = config.BranchConfig(branch)
1278
1645
        self.assertEqual("Robert Collins <robertc@example.org>",
1471
1838
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1472
1839
 
1473
1840
 
 
1841
class TestSection(tests.TestCase):
 
1842
 
 
1843
    # FIXME: Parametrize so that all sections produced by Stores run these
 
1844
    # tests -- vila 2011-04-01
 
1845
 
 
1846
    def test_get_a_value(self):
 
1847
        a_dict = dict(foo='bar')
 
1848
        section = config.Section('myID', a_dict)
 
1849
        self.assertEquals('bar', section.get('foo'))
 
1850
 
 
1851
    def test_get_unknown_option(self):
 
1852
        a_dict = dict()
 
1853
        section = config.Section(None, a_dict)
 
1854
        self.assertEquals('out of thin air',
 
1855
                          section.get('foo', 'out of thin air'))
 
1856
 
 
1857
    def test_options_is_shared(self):
 
1858
        a_dict = dict()
 
1859
        section = config.Section(None, a_dict)
 
1860
        self.assertIs(a_dict, section.options)
 
1861
 
 
1862
 
 
1863
class TestMutableSection(tests.TestCase):
 
1864
 
 
1865
    # FIXME: Parametrize so that all sections (including os.environ and the
 
1866
    # ones produced by Stores) run these tests -- vila 2011-04-01
 
1867
 
 
1868
    def test_set(self):
 
1869
        a_dict = dict(foo='bar')
 
1870
        section = config.MutableSection('myID', a_dict)
 
1871
        section.set('foo', 'new_value')
 
1872
        self.assertEquals('new_value', section.get('foo'))
 
1873
        # The change appears in the shared section
 
1874
        self.assertEquals('new_value', a_dict.get('foo'))
 
1875
        # We keep track of the change
 
1876
        self.assertTrue('foo' in section.orig)
 
1877
        self.assertEquals('bar', section.orig.get('foo'))
 
1878
 
 
1879
    def test_set_preserve_original_once(self):
 
1880
        a_dict = dict(foo='bar')
 
1881
        section = config.MutableSection('myID', a_dict)
 
1882
        section.set('foo', 'first_value')
 
1883
        section.set('foo', 'second_value')
 
1884
        # We keep track of the original value
 
1885
        self.assertTrue('foo' in section.orig)
 
1886
        self.assertEquals('bar', section.orig.get('foo'))
 
1887
 
 
1888
    def test_remove(self):
 
1889
        a_dict = dict(foo='bar')
 
1890
        section = config.MutableSection('myID', a_dict)
 
1891
        section.remove('foo')
 
1892
        # We get None for unknown options via the default value
 
1893
        self.assertEquals(None, section.get('foo'))
 
1894
        # Or we just get the default value
 
1895
        self.assertEquals('unknown', section.get('foo', 'unknown'))
 
1896
        self.assertFalse('foo' in section.options)
 
1897
        # We keep track of the deletion
 
1898
        self.assertTrue('foo' in section.orig)
 
1899
        self.assertEquals('bar', section.orig.get('foo'))
 
1900
 
 
1901
    def test_remove_new_option(self):
 
1902
        a_dict = dict()
 
1903
        section = config.MutableSection('myID', a_dict)
 
1904
        section.set('foo', 'bar')
 
1905
        section.remove('foo')
 
1906
        self.assertFalse('foo' in section.options)
 
1907
        # The option didn't exist initially so it we need to keep track of it
 
1908
        # with a special value
 
1909
        self.assertTrue('foo' in section.orig)
 
1910
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
 
1911
 
 
1912
 
 
1913
class TestStore(tests.TestCaseWithTransport):
 
1914
 
 
1915
    def assertSectionContent(self, expected, section):
 
1916
        """Assert that some options have the proper values in a section."""
 
1917
        expected_name, expected_options = expected
 
1918
        self.assertEquals(expected_name, section.id)
 
1919
        self.assertEquals(
 
1920
            expected_options,
 
1921
            dict([(k, section.get(k)) for k in expected_options.keys()]))
 
1922
 
 
1923
 
 
1924
class TestReadonlyStore(TestStore):
 
1925
 
 
1926
    scenarios = [(key, {'get_store': builder})
 
1927
                 for key, builder in test_store_builder_registry.iteritems()]
 
1928
 
 
1929
    def setUp(self):
 
1930
        super(TestReadonlyStore, self).setUp()
 
1931
        self.branch = self.make_branch('branch')
 
1932
 
 
1933
    def test_building_delays_load(self):
 
1934
        store = self.get_store(self)
 
1935
        self.assertEquals(False, store.is_loaded())
 
1936
        store._load_from_string('')
 
1937
        self.assertEquals(True, store.is_loaded())
 
1938
 
 
1939
    def test_get_no_sections_for_empty(self):
 
1940
        store = self.get_store(self)
 
1941
        store._load_from_string('')
 
1942
        self.assertEquals([], list(store.get_sections()))
 
1943
 
 
1944
    def test_get_default_section(self):
 
1945
        store = self.get_store(self)
 
1946
        store._load_from_string('foo=bar')
 
1947
        sections = list(store.get_sections())
 
1948
        self.assertLength(1, sections)
 
1949
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
1950
 
 
1951
    def test_get_named_section(self):
 
1952
        store = self.get_store(self)
 
1953
        store._load_from_string('[baz]\nfoo=bar')
 
1954
        sections = list(store.get_sections())
 
1955
        self.assertLength(1, sections)
 
1956
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
1957
 
 
1958
    def test_load_from_string_fails_for_non_empty_store(self):
 
1959
        store = self.get_store(self)
 
1960
        store._load_from_string('foo=bar')
 
1961
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
 
1962
 
 
1963
 
 
1964
class TestMutableStore(TestStore):
 
1965
 
 
1966
    scenarios = [(key, {'store_id': key, 'get_store': builder})
 
1967
                 for key, builder in test_store_builder_registry.iteritems()]
 
1968
 
 
1969
    def setUp(self):
 
1970
        super(TestMutableStore, self).setUp()
 
1971
        self.transport = self.get_transport()
 
1972
        self.branch = self.make_branch('branch')
 
1973
 
 
1974
    def has_store(self, store):
 
1975
        store_basename = urlutils.relative_url(self.transport.external_url(),
 
1976
                                               store.external_url())
 
1977
        return self.transport.has(store_basename)
 
1978
 
 
1979
    def test_save_empty_creates_no_file(self):
 
1980
        if self.store_id == 'branch':
 
1981
            raise tests.TestNotApplicable(
 
1982
                'branch.conf is *always* created when a branch is initialized')
 
1983
        store = self.get_store(self)
 
1984
        store.save()
 
1985
        self.assertEquals(False, self.has_store(store))
 
1986
 
 
1987
    def test_save_emptied_succeeds(self):
 
1988
        store = self.get_store(self)
 
1989
        store._load_from_string('foo=bar\n')
 
1990
        section = store.get_mutable_section(None)
 
1991
        section.remove('foo')
 
1992
        store.save()
 
1993
        self.assertEquals(True, self.has_store(store))
 
1994
        modified_store = self.get_store(self)
 
1995
        sections = list(modified_store.get_sections())
 
1996
        self.assertLength(0, sections)
 
1997
 
 
1998
    def test_save_with_content_succeeds(self):
 
1999
        if self.store_id == 'branch':
 
2000
            raise tests.TestNotApplicable(
 
2001
                'branch.conf is *always* created when a branch is initialized')
 
2002
        store = self.get_store(self)
 
2003
        store._load_from_string('foo=bar\n')
 
2004
        self.assertEquals(False, self.has_store(store))
 
2005
        store.save()
 
2006
        self.assertEquals(True, self.has_store(store))
 
2007
        modified_store = self.get_store(self)
 
2008
        sections = list(modified_store.get_sections())
 
2009
        self.assertLength(1, sections)
 
2010
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2011
 
 
2012
    def test_set_option_in_empty_store(self):
 
2013
        store = self.get_store(self)
 
2014
        section = store.get_mutable_section(None)
 
2015
        section.set('foo', 'bar')
 
2016
        store.save()
 
2017
        modified_store = self.get_store(self)
 
2018
        sections = list(modified_store.get_sections())
 
2019
        self.assertLength(1, sections)
 
2020
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2021
 
 
2022
    def test_set_option_in_default_section(self):
 
2023
        store = self.get_store(self)
 
2024
        store._load_from_string('')
 
2025
        section = store.get_mutable_section(None)
 
2026
        section.set('foo', 'bar')
 
2027
        store.save()
 
2028
        modified_store = self.get_store(self)
 
2029
        sections = list(modified_store.get_sections())
 
2030
        self.assertLength(1, sections)
 
2031
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2032
 
 
2033
    def test_set_option_in_named_section(self):
 
2034
        store = self.get_store(self)
 
2035
        store._load_from_string('')
 
2036
        section = store.get_mutable_section('baz')
 
2037
        section.set('foo', 'bar')
 
2038
        store.save()
 
2039
        modified_store = self.get_store(self)
 
2040
        sections = list(modified_store.get_sections())
 
2041
        self.assertLength(1, sections)
 
2042
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
2043
 
 
2044
 
 
2045
class TestIniFileStore(TestStore):
 
2046
 
 
2047
    def test_loading_unknown_file_fails(self):
 
2048
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
 
2049
        self.assertRaises(errors.NoSuchFile, store.load)
 
2050
 
 
2051
    def test_invalid_content(self):
 
2052
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
2053
        self.assertEquals(False, store.is_loaded())
 
2054
        exc = self.assertRaises(
 
2055
            errors.ParseConfigError, store._load_from_string,
 
2056
            'this is invalid !')
 
2057
        self.assertEndsWith(exc.filename, 'foo.conf')
 
2058
        # And the load failed
 
2059
        self.assertEquals(False, store.is_loaded())
 
2060
 
 
2061
    def test_get_embedded_sections(self):
 
2062
        # A more complicated example (which also shows that section names and
 
2063
        # option names share the same name space...)
 
2064
        # FIXME: This should be fixed by forbidding dicts as values ?
 
2065
        # -- vila 2011-04-05
 
2066
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
2067
        store._load_from_string('''
 
2068
foo=bar
 
2069
l=1,2
 
2070
[DEFAULT]
 
2071
foo_in_DEFAULT=foo_DEFAULT
 
2072
[bar]
 
2073
foo_in_bar=barbar
 
2074
[baz]
 
2075
foo_in_baz=barbaz
 
2076
[[qux]]
 
2077
foo_in_qux=quux
 
2078
''')
 
2079
        sections = list(store.get_sections())
 
2080
        self.assertLength(4, sections)
 
2081
        # The default section has no name.
 
2082
        # List values are provided as lists
 
2083
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
 
2084
                                  sections[0])
 
2085
        self.assertSectionContent(
 
2086
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
 
2087
        self.assertSectionContent(
 
2088
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
 
2089
        # sub sections are provided as embedded dicts.
 
2090
        self.assertSectionContent(
 
2091
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
 
2092
            sections[3])
 
2093
 
 
2094
 
 
2095
class TestLockableIniFileStore(TestStore):
 
2096
 
 
2097
    def test_create_store_in_created_dir(self):
 
2098
        t = self.get_transport('dir/subdir')
 
2099
        store = config.LockableIniFileStore(t, 'foo.conf')
 
2100
        store.get_mutable_section(None).set('foo', 'bar')
 
2101
        store.save()
 
2102
 
 
2103
    # FIXME: We should adapt the tests in TestLockableConfig about concurrent
 
2104
    # writes. Since this requires a clearer rewrite, I'll just rely on using
 
2105
    # the same code in LockableIniFileStore (copied from LockableConfig, but
 
2106
    # trivial enough, the main difference is that we add @needs_write_lock on
 
2107
    # save() instead of set_user_option() and remove_user_option()). The intent
 
2108
    # is to ensure that we always get a valid content for the store even when
 
2109
    # concurrent accesses occur, read/write, write/write. It may be worth
 
2110
    # looking into removing the lock dir when it;s not needed anymore and look
 
2111
    # at possible fallouts for concurrent lockers -- vila 20110-04-06
 
2112
 
 
2113
 
 
2114
class TestSectionMatcher(TestStore):
 
2115
 
 
2116
    scenarios = [('location', {'matcher': config.LocationMatcher})]
 
2117
 
 
2118
    def get_store(self, file_name):
 
2119
        return config.IniFileStore(self.get_readonly_transport(), file_name)
 
2120
 
 
2121
    def test_no_matches_for_empty_stores(self):
 
2122
        store = self.get_store('foo.conf')
 
2123
        store._load_from_string('')
 
2124
        matcher = self.matcher(store, '/bar')
 
2125
        self.assertEquals([], list(matcher.get_sections()))
 
2126
 
 
2127
    def test_build_doesnt_load_store(self):
 
2128
        store = self.get_store('foo.conf')
 
2129
        matcher = self.matcher(store, '/bar')
 
2130
        self.assertFalse(store.is_loaded())
 
2131
 
 
2132
 
 
2133
class TestLocationSection(tests.TestCase):
 
2134
 
 
2135
    def get_section(self, options, extra_path):
 
2136
        section = config.Section('foo', options)
 
2137
        # We don't care about the length so we use '0'
 
2138
        return config.LocationSection(section, 0, extra_path)
 
2139
 
 
2140
    def test_simple_option(self):
 
2141
        section = self.get_section({'foo': 'bar'}, '')
 
2142
        self.assertEquals('bar', section.get('foo'))
 
2143
 
 
2144
    def test_option_with_extra_path(self):
 
2145
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
 
2146
                                   'baz')
 
2147
        self.assertEquals('bar/baz', section.get('foo'))
 
2148
 
 
2149
    def test_invalid_policy(self):
 
2150
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
 
2151
                                   'baz')
 
2152
        # invalid policies are ignored
 
2153
        self.assertEquals('bar', section.get('foo'))
 
2154
 
 
2155
 
 
2156
class TestLocationMatcher(TestStore):
 
2157
 
 
2158
    def get_store(self, file_name):
 
2159
        return config.IniFileStore(self.get_readonly_transport(), file_name)
 
2160
 
 
2161
    def test_more_specific_sections_first(self):
 
2162
        store = self.get_store('foo.conf')
 
2163
        store._load_from_string('''
 
2164
[/foo]
 
2165
section=/foo
 
2166
[/foo/bar]
 
2167
section=/foo/bar
 
2168
''')
 
2169
        self.assertEquals(['/foo', '/foo/bar'],
 
2170
                          [section.id for section in store.get_sections()])
 
2171
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
 
2172
        sections = list(matcher.get_sections())
 
2173
        self.assertEquals([3, 2],
 
2174
                          [section.length for section in sections])
 
2175
        self.assertEquals(['/foo/bar', '/foo'],
 
2176
                          [section.id for section in sections])
 
2177
        self.assertEquals(['baz', 'bar/baz'],
 
2178
                          [section.extra_path for section in sections])
 
2179
 
 
2180
 
 
2181
 
 
2182
class TestStackGet(tests.TestCase):
 
2183
 
 
2184
    # FIXME: This should be parametrized for all known Stack or dedicated
 
2185
    # paramerized tests created to avoid bloating -- vila 2011-03-31
 
2186
 
 
2187
    def test_single_config_get(self):
 
2188
        conf = dict(foo='bar')
 
2189
        conf_stack = config.Stack([conf])
 
2190
        self.assertEquals('bar', conf_stack.get('foo'))
 
2191
 
 
2192
    def test_get_first_definition(self):
 
2193
        conf1 = dict(foo='bar')
 
2194
        conf2 = dict(foo='baz')
 
2195
        conf_stack = config.Stack([conf1, conf2])
 
2196
        self.assertEquals('bar', conf_stack.get('foo'))
 
2197
 
 
2198
    def test_get_embedded_definition(self):
 
2199
        conf1 = dict(yy='12')
 
2200
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
 
2201
        conf_stack = config.Stack([conf1, conf2])
 
2202
        self.assertEquals('baz', conf_stack.get('foo'))
 
2203
 
 
2204
    def test_get_for_empty_stack(self):
 
2205
        conf_stack = config.Stack([])
 
2206
        self.assertEquals(None, conf_stack.get('foo'))
 
2207
 
 
2208
    def test_get_for_empty_section_callable(self):
 
2209
        conf_stack = config.Stack([lambda : []])
 
2210
        self.assertEquals(None, conf_stack.get('foo'))
 
2211
 
 
2212
    def test_get_for_broken_callable(self):
 
2213
        # Trying to use and invalid callable raises an exception on first use
 
2214
        conf_stack = config.Stack([lambda : object()])
 
2215
        self.assertRaises(TypeError, conf_stack.get, 'foo')
 
2216
 
 
2217
 
 
2218
class TestStackSet(tests.TestCaseWithTransport):
 
2219
 
 
2220
    # FIXME: This should be parametrized for all known Stack or dedicated
 
2221
    # paramerized tests created to avoid bloating -- vila 2011-04-05
 
2222
 
 
2223
    def test_simple_set(self):
 
2224
        store = config.IniFileStore(self.get_transport(), 'test.conf')
 
2225
        store._load_from_string('foo=bar')
 
2226
        conf = config.Stack([store.get_sections], store)
 
2227
        self.assertEquals('bar', conf.get('foo'))
 
2228
        conf.set('foo', 'baz')
 
2229
        # Did we get it back ?
 
2230
        self.assertEquals('baz', conf.get('foo'))
 
2231
 
 
2232
    def test_set_creates_a_new_section(self):
 
2233
        store = config.IniFileStore(self.get_transport(), 'test.conf')
 
2234
        conf = config.Stack([store.get_sections], store)
 
2235
        conf.set('foo', 'baz')
 
2236
        self.assertEquals, 'baz', conf.get('foo')
 
2237
 
 
2238
 
 
2239
class TestStackRemove(tests.TestCaseWithTransport):
 
2240
 
 
2241
    # FIXME: This should be parametrized for all known Stack or dedicated
 
2242
    # paramerized tests created to avoid bloating -- vila 2011-04-06
 
2243
 
 
2244
    def test_remove_existing(self):
 
2245
        store = config.IniFileStore(self.get_transport(), 'test.conf')
 
2246
        store._load_from_string('foo=bar')
 
2247
        conf = config.Stack([store.get_sections], store)
 
2248
        self.assertEquals('bar', conf.get('foo'))
 
2249
        conf.remove('foo')
 
2250
        # Did we get it back ?
 
2251
        self.assertEquals(None, conf.get('foo'))
 
2252
 
 
2253
    def test_remove_unknown(self):
 
2254
        store = config.IniFileStore(self.get_transport(), 'test.conf')
 
2255
        conf = config.Stack([store.get_sections], store)
 
2256
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
 
2257
 
 
2258
 
 
2259
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
 
2260
 
 
2261
    def setUp(self):
 
2262
        super(TestConfigGetOptions, self).setUp()
 
2263
        create_configs(self)
 
2264
 
 
2265
    def test_no_variable(self):
 
2266
        # Using branch should query branch, locations and bazaar
 
2267
        self.assertOptions([], self.branch_config)
 
2268
 
 
2269
    def test_option_in_bazaar(self):
 
2270
        self.bazaar_config.set_user_option('file', 'bazaar')
 
2271
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
 
2272
                           self.bazaar_config)
 
2273
 
 
2274
    def test_option_in_locations(self):
 
2275
        self.locations_config.set_user_option('file', 'locations')
 
2276
        self.assertOptions(
 
2277
            [('file', 'locations', self.tree.basedir, 'locations')],
 
2278
            self.locations_config)
 
2279
 
 
2280
    def test_option_in_branch(self):
 
2281
        self.branch_config.set_user_option('file', 'branch')
 
2282
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
 
2283
                           self.branch_config)
 
2284
 
 
2285
    def test_option_in_bazaar_and_branch(self):
 
2286
        self.bazaar_config.set_user_option('file', 'bazaar')
 
2287
        self.branch_config.set_user_option('file', 'branch')
 
2288
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
 
2289
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2290
                           self.branch_config)
 
2291
 
 
2292
    def test_option_in_branch_and_locations(self):
 
2293
        # Hmm, locations override branch :-/
 
2294
        self.locations_config.set_user_option('file', 'locations')
 
2295
        self.branch_config.set_user_option('file', 'branch')
 
2296
        self.assertOptions(
 
2297
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2298
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
2299
            self.branch_config)
 
2300
 
 
2301
    def test_option_in_bazaar_locations_and_branch(self):
 
2302
        self.bazaar_config.set_user_option('file', 'bazaar')
 
2303
        self.locations_config.set_user_option('file', 'locations')
 
2304
        self.branch_config.set_user_option('file', 'branch')
 
2305
        self.assertOptions(
 
2306
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2307
             ('file', 'branch', 'DEFAULT', 'branch'),
 
2308
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2309
            self.branch_config)
 
2310
 
 
2311
 
 
2312
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
 
2313
 
 
2314
    def setUp(self):
 
2315
        super(TestConfigRemoveOption, self).setUp()
 
2316
        create_configs_with_file_option(self)
 
2317
 
 
2318
    def test_remove_in_locations(self):
 
2319
        self.locations_config.remove_user_option('file', self.tree.basedir)
 
2320
        self.assertOptions(
 
2321
            [('file', 'branch', 'DEFAULT', 'branch'),
 
2322
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2323
            self.branch_config)
 
2324
 
 
2325
    def test_remove_in_branch(self):
 
2326
        self.branch_config.remove_user_option('file')
 
2327
        self.assertOptions(
 
2328
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2329
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2330
            self.branch_config)
 
2331
 
 
2332
    def test_remove_in_bazaar(self):
 
2333
        self.bazaar_config.remove_user_option('file')
 
2334
        self.assertOptions(
 
2335
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2336
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
2337
            self.branch_config)
 
2338
 
 
2339
 
 
2340
class TestConfigGetSections(tests.TestCaseWithTransport):
 
2341
 
 
2342
    def setUp(self):
 
2343
        super(TestConfigGetSections, self).setUp()
 
2344
        create_configs(self)
 
2345
 
 
2346
    def assertSectionNames(self, expected, conf, name=None):
 
2347
        """Check which sections are returned for a given config.
 
2348
 
 
2349
        If fallback configurations exist their sections can be included.
 
2350
 
 
2351
        :param expected: A list of section names.
 
2352
 
 
2353
        :param conf: The configuration that will be queried.
 
2354
 
 
2355
        :param name: An optional section name that will be passed to
 
2356
            get_sections().
 
2357
        """
 
2358
        sections = list(conf._get_sections(name))
 
2359
        self.assertLength(len(expected), sections)
 
2360
        self.assertEqual(expected, [name for name, _, _ in sections])
 
2361
 
 
2362
    def test_bazaar_default_section(self):
 
2363
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
 
2364
 
 
2365
    def test_locations_default_section(self):
 
2366
        # No sections are defined in an empty file
 
2367
        self.assertSectionNames([], self.locations_config)
 
2368
 
 
2369
    def test_locations_named_section(self):
 
2370
        self.locations_config.set_user_option('file', 'locations')
 
2371
        self.assertSectionNames([self.tree.basedir], self.locations_config)
 
2372
 
 
2373
    def test_locations_matching_sections(self):
 
2374
        loc_config = self.locations_config
 
2375
        loc_config.set_user_option('file', 'locations')
 
2376
        # We need to cheat a bit here to create an option in sections above and
 
2377
        # below the 'location' one.
 
2378
        parser = loc_config._get_parser()
 
2379
        # locations.cong deals with '/' ignoring native os.sep
 
2380
        location_names = self.tree.basedir.split('/')
 
2381
        parent = '/'.join(location_names[:-1])
 
2382
        child = '/'.join(location_names + ['child'])
 
2383
        parser[parent] = {}
 
2384
        parser[parent]['file'] = 'parent'
 
2385
        parser[child] = {}
 
2386
        parser[child]['file'] = 'child'
 
2387
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
 
2388
 
 
2389
    def test_branch_data_default_section(self):
 
2390
        self.assertSectionNames([None],
 
2391
                                self.branch_config._get_branch_data_config())
 
2392
 
 
2393
    def test_branch_default_sections(self):
 
2394
        # No sections are defined in an empty locations file
 
2395
        self.assertSectionNames([None, 'DEFAULT'],
 
2396
                                self.branch_config)
 
2397
        # Unless we define an option
 
2398
        self.branch_config._get_location_config().set_user_option(
 
2399
            'file', 'locations')
 
2400
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
 
2401
                                self.branch_config)
 
2402
 
 
2403
    def test_bazaar_named_section(self):
 
2404
        # We need to cheat as the API doesn't give direct access to sections
 
2405
        # other than DEFAULT.
 
2406
        self.bazaar_config.set_alias('bazaar', 'bzr')
 
2407
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
 
2408
 
 
2409
 
1474
2410
class TestAuthenticationConfigFile(tests.TestCase):
1475
2411
    """Test the authentication.conf file matching"""
1476
2412
 
1971
2907
# test_user_prompted ?
1972
2908
class TestAuthenticationRing(tests.TestCaseWithTransport):
1973
2909
    pass
 
2910
 
 
2911
 
 
2912
class TestAutoUserId(tests.TestCase):
 
2913
    """Test inferring an automatic user name."""
 
2914
 
 
2915
    def test_auto_user_id(self):
 
2916
        """Automatic inference of user name.
 
2917
        
 
2918
        This is a bit hard to test in an isolated way, because it depends on
 
2919
        system functions that go direct to /etc or perhaps somewhere else.
 
2920
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
 
2921
        to be able to choose a user name with no configuration.
 
2922
        """
 
2923
        if sys.platform == 'win32':
 
2924
            raise TestSkipped("User name inference not implemented on win32")
 
2925
        realname, address = config._auto_user_id()
 
2926
        if os.path.exists('/etc/mailname'):
 
2927
            self.assertIsNot(None, realname)
 
2928
            self.assertIsNot(None, address)
 
2929
        else:
 
2930
            self.assertEquals((None, None), (realname, address))
 
2931