/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Jelmer Vernooij
  • Date: 2011-05-17 10:29:43 UTC
  • mto: This revision was merged to the branch mainline in revision 5877.
  • Revision ID: jelmer@samba.org-20110517102943-29y305w2uvmjtic3
Fix foreign test.

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
19
19
from cStringIO import StringIO
20
20
import os
21
21
import sys
 
22
import threading
 
23
 
 
24
 
 
25
from testtools import matchers
22
26
 
23
27
#import bzrlib specific imports here
24
28
from bzrlib import (
29
33
    errors,
30
34
    osutils,
31
35
    mail_client,
 
36
    mergetools,
32
37
    ui,
33
38
    urlutils,
 
39
    registry,
34
40
    tests,
35
41
    trace,
36
42
    transport,
37
43
    )
 
44
from bzrlib.tests import (
 
45
    features,
 
46
    TestSkipped,
 
47
    scenarios,
 
48
    )
38
49
from bzrlib.util.configobj import configobj
39
50
 
40
51
 
 
52
def lockable_config_scenarios():
 
53
    return [
 
54
        ('global',
 
55
         {'config_class': config.GlobalConfig,
 
56
          'config_args': [],
 
57
          'config_section': 'DEFAULT'}),
 
58
        ('locations',
 
59
         {'config_class': config.LocationConfig,
 
60
          'config_args': ['.'],
 
61
          'config_section': '.'}),]
 
62
 
 
63
 
 
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
 
 
88
 
 
89
 
41
90
sample_long_alias="log -r-15..-1 --line"
42
91
sample_config_text = u"""
43
92
[DEFAULT]
47
96
gpg_signing_command=gnome-gpg
48
97
log_format=short
49
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
50
102
[ALIASES]
51
103
h=help
52
104
ll=""" + sample_long_alias + "\n"
105
157
"""
106
158
 
107
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
 
108
203
class InstrumentedConfigObj(object):
109
204
    """A config obj look-enough-alike to record calls made to it."""
110
205
 
129
224
        self._calls.append(('keys',))
130
225
        return []
131
226
 
 
227
    def reload(self):
 
228
        self._calls.append(('reload',))
 
229
 
132
230
    def write(self, arg):
133
231
        self._calls.append(('write',))
134
232
 
240
338
        """
241
339
        co = config.ConfigObj()
242
340
        co['test'] = 'foo#bar'
243
 
        lines = co.write()
 
341
        outfile = StringIO()
 
342
        co.write(outfile=outfile)
 
343
        lines = outfile.getvalue().splitlines()
244
344
        self.assertEqual(lines, ['test = "foo#bar"'])
245
345
        co2 = config.ConfigObj(lines)
246
346
        self.assertEqual(co2['test'], 'foo#bar')
247
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
 
248
372
 
249
373
erroneous_config = """[section] # line 1
250
374
good=good # line 2
333
457
 
334
458
    def setUp(self):
335
459
        super(TestConfigPath, self).setUp()
336
 
        os.environ['HOME'] = '/home/bogus'
337
 
        os.environ['XDG_CACHE_DIR'] = ''
 
460
        self.overrideEnv('HOME', '/home/bogus')
 
461
        self.overrideEnv('XDG_CACHE_DIR', '')
338
462
        if sys.platform == 'win32':
339
 
            os.environ['BZR_HOME'] = \
340
 
                r'C:\Documents and Settings\bogus\Application Data'
 
463
            self.overrideEnv(
 
464
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
341
465
            self.bzr_home = \
342
466
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
343
467
        else:
350
474
        self.assertEqual(config.config_filename(),
351
475
                         self.bzr_home + '/bazaar.conf')
352
476
 
353
 
    def test_branches_config_filename(self):
354
 
        self.assertEqual(config.branches_config_filename(),
355
 
                         self.bzr_home + '/branches.conf')
356
 
 
357
477
    def test_locations_config_filename(self):
358
478
        self.assertEqual(config.locations_config_filename(),
359
479
                         self.bzr_home + '/locations.conf')
367
487
            '/home/bogus/.cache')
368
488
 
369
489
 
370
 
class TestIniConfig(tests.TestCase):
 
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
 
 
518
class TestIniConfig(tests.TestCaseInTempDir):
371
519
 
372
520
    def make_config_parser(self, s):
373
 
        conf = config.IniBasedConfig(None)
374
 
        parser = conf._get_parser(file=StringIO(s.encode('utf-8')))
375
 
        return conf, parser
 
521
        conf = config.IniBasedConfig.from_string(s)
 
522
        return conf, conf._get_parser()
376
523
 
377
524
 
378
525
class TestIniConfigBuilding(TestIniConfig):
379
526
 
380
527
    def test_contructs(self):
381
 
        my_config = config.IniBasedConfig("nothing")
 
528
        my_config = config.IniBasedConfig()
382
529
 
383
530
    def test_from_fp(self):
384
 
        config_file = StringIO(sample_config_text.encode('utf-8'))
385
 
        my_config = config.IniBasedConfig(None)
386
 
        self.failUnless(
387
 
            isinstance(my_config._get_parser(file=config_file),
388
 
                        configobj.ConfigObj))
 
531
        my_config = config.IniBasedConfig.from_string(sample_config_text)
 
532
        self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
389
533
 
390
534
    def test_cached(self):
 
535
        my_config = config.IniBasedConfig.from_string(sample_config_text)
 
536
        parser = my_config._get_parser()
 
537
        self.assertTrue(my_config._get_parser() is parser)
 
538
 
 
539
    def _dummy_chown(self, path, uid, gid):
 
540
        self.path, self.uid, self.gid = path, uid, gid
 
541
 
 
542
    def test_ini_config_ownership(self):
 
543
        """Ensure that chown is happening during _write_config_file"""
 
544
        self.requireFeature(features.chown_feature)
 
545
        self.overrideAttr(os, 'chown', self._dummy_chown)
 
546
        self.path = self.uid = self.gid = None
 
547
        conf = config.IniBasedConfig(file_name='./foo.conf')
 
548
        conf._write_config_file()
 
549
        self.assertEquals(self.path, './foo.conf')
 
550
        self.assertTrue(isinstance(self.uid, int))
 
551
        self.assertTrue(isinstance(self.gid, int))
 
552
 
 
553
    def test_get_filename_parameter_is_deprecated_(self):
 
554
        conf = self.callDeprecated([
 
555
            'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
 
556
            ' Use file_name instead.'],
 
557
            config.IniBasedConfig, lambda: 'ini.conf')
 
558
        self.assertEqual('ini.conf', conf.file_name)
 
559
 
 
560
    def test_get_parser_file_parameter_is_deprecated_(self):
391
561
        config_file = StringIO(sample_config_text.encode('utf-8'))
392
 
        my_config = config.IniBasedConfig(None)
393
 
        parser = my_config._get_parser(file=config_file)
394
 
        self.failUnless(my_config._get_parser() is parser)
 
562
        conf = config.IniBasedConfig.from_string(sample_config_text)
 
563
        conf = self.callDeprecated([
 
564
            'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
 
565
            ' Use IniBasedConfig(_content=xxx) instead.'],
 
566
            conf._get_parser, file=config_file)
 
567
 
 
568
 
 
569
class TestIniConfigSaving(tests.TestCaseInTempDir):
 
570
 
 
571
    def test_cant_save_without_a_file_name(self):
 
572
        conf = config.IniBasedConfig()
 
573
        self.assertRaises(AssertionError, conf._write_config_file)
 
574
 
 
575
    def test_saved_with_content(self):
 
576
        content = 'foo = bar\n'
 
577
        conf = config.IniBasedConfig.from_string(
 
578
            content, file_name='./test.conf', save=True)
 
579
        self.assertFileEqual(content, 'test.conf')
 
580
 
 
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
 
 
774
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
 
775
 
 
776
    def test_cannot_reload_without_name(self):
 
777
        conf = config.IniBasedConfig.from_string(sample_config_text)
 
778
        self.assertRaises(AssertionError, conf.reload)
 
779
 
 
780
    def test_reload_see_new_value(self):
 
781
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
 
782
                                               file_name='./test/conf')
 
783
        c1._write_config_file()
 
784
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
 
785
                                               file_name='./test/conf')
 
786
        c2._write_config_file()
 
787
        self.assertEqual('vim', c1.get_user_option('editor'))
 
788
        self.assertEqual('emacs', c2.get_user_option('editor'))
 
789
        # Make sure we get the Right value
 
790
        c1.reload()
 
791
        self.assertEqual('emacs', c1.get_user_option('editor'))
 
792
 
 
793
 
 
794
class TestLockableConfig(tests.TestCaseInTempDir):
 
795
 
 
796
    scenarios = lockable_config_scenarios()
 
797
 
 
798
    # Set by load_tests
 
799
    config_class = None
 
800
    config_args = None
 
801
    config_section = None
 
802
 
 
803
    def setUp(self):
 
804
        super(TestLockableConfig, self).setUp()
 
805
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
 
806
        self.config = self.create_config(self._content)
 
807
 
 
808
    def get_existing_config(self):
 
809
        return self.config_class(*self.config_args)
 
810
 
 
811
    def create_config(self, content):
 
812
        kwargs = dict(save=True)
 
813
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
 
814
        return c
 
815
 
 
816
    def test_simple_read_access(self):
 
817
        self.assertEquals('1', self.config.get_user_option('one'))
 
818
 
 
819
    def test_simple_write_access(self):
 
820
        self.config.set_user_option('one', 'one')
 
821
        self.assertEquals('one', self.config.get_user_option('one'))
 
822
 
 
823
    def test_listen_to_the_last_speaker(self):
 
824
        c1 = self.config
 
825
        c2 = self.get_existing_config()
 
826
        c1.set_user_option('one', 'ONE')
 
827
        c2.set_user_option('two', 'TWO')
 
828
        self.assertEquals('ONE', c1.get_user_option('one'))
 
829
        self.assertEquals('TWO', c2.get_user_option('two'))
 
830
        # The second update respect the first one
 
831
        self.assertEquals('ONE', c2.get_user_option('one'))
 
832
 
 
833
    def test_last_speaker_wins(self):
 
834
        # If the same config is not shared, the same variable modified twice
 
835
        # can only see a single result.
 
836
        c1 = self.config
 
837
        c2 = self.get_existing_config()
 
838
        c1.set_user_option('one', 'c1')
 
839
        c2.set_user_option('one', 'c2')
 
840
        self.assertEquals('c2', c2._get_user_option('one'))
 
841
        # The first modification is still available until another refresh
 
842
        # occur
 
843
        self.assertEquals('c1', c1._get_user_option('one'))
 
844
        c1.set_user_option('two', 'done')
 
845
        self.assertEquals('c2', c1._get_user_option('one'))
 
846
 
 
847
    def test_writes_are_serialized(self):
 
848
        c1 = self.config
 
849
        c2 = self.get_existing_config()
 
850
 
 
851
        # We spawn a thread that will pause *during* the write
 
852
        before_writing = threading.Event()
 
853
        after_writing = threading.Event()
 
854
        writing_done = threading.Event()
 
855
        c1_orig = c1._write_config_file
 
856
        def c1_write_config_file():
 
857
            before_writing.set()
 
858
            c1_orig()
 
859
            # The lock is held. We wait for the main thread to decide when to
 
860
            # continue
 
861
            after_writing.wait()
 
862
        c1._write_config_file = c1_write_config_file
 
863
        def c1_set_option():
 
864
            c1.set_user_option('one', 'c1')
 
865
            writing_done.set()
 
866
        t1 = threading.Thread(target=c1_set_option)
 
867
        # Collect the thread after the test
 
868
        self.addCleanup(t1.join)
 
869
        # Be ready to unblock the thread if the test goes wrong
 
870
        self.addCleanup(after_writing.set)
 
871
        t1.start()
 
872
        before_writing.wait()
 
873
        self.assertTrue(c1._lock.is_held)
 
874
        self.assertRaises(errors.LockContention,
 
875
                          c2.set_user_option, 'one', 'c2')
 
876
        self.assertEquals('c1', c1.get_user_option('one'))
 
877
        # Let the lock be released
 
878
        after_writing.set()
 
879
        writing_done.wait()
 
880
        c2.set_user_option('one', 'c2')
 
881
        self.assertEquals('c2', c2.get_user_option('one'))
 
882
 
 
883
    def test_read_while_writing(self):
 
884
       c1 = self.config
 
885
       # We spawn a thread that will pause *during* the write
 
886
       ready_to_write = threading.Event()
 
887
       do_writing = threading.Event()
 
888
       writing_done = threading.Event()
 
889
       c1_orig = c1._write_config_file
 
890
       def c1_write_config_file():
 
891
           ready_to_write.set()
 
892
           # The lock is held. We wait for the main thread to decide when to
 
893
           # continue
 
894
           do_writing.wait()
 
895
           c1_orig()
 
896
           writing_done.set()
 
897
       c1._write_config_file = c1_write_config_file
 
898
       def c1_set_option():
 
899
           c1.set_user_option('one', 'c1')
 
900
       t1 = threading.Thread(target=c1_set_option)
 
901
       # Collect the thread after the test
 
902
       self.addCleanup(t1.join)
 
903
       # Be ready to unblock the thread if the test goes wrong
 
904
       self.addCleanup(do_writing.set)
 
905
       t1.start()
 
906
       # Ensure the thread is ready to write
 
907
       ready_to_write.wait()
 
908
       self.assertTrue(c1._lock.is_held)
 
909
       self.assertEquals('c1', c1.get_user_option('one'))
 
910
       # If we read during the write, we get the old value
 
911
       c2 = self.get_existing_config()
 
912
       self.assertEquals('1', c2.get_user_option('one'))
 
913
       # Let the writing occur and ensure it occurred
 
914
       do_writing.set()
 
915
       writing_done.wait()
 
916
       # Now we get the updated value
 
917
       c3 = self.get_existing_config()
 
918
       self.assertEquals('c1', c3.get_user_option('one'))
395
919
 
396
920
 
397
921
class TestGetUserOptionAs(TestIniConfig):
462
986
            parser = my_config._get_parser()
463
987
        finally:
464
988
            config.ConfigObj = oldparserclass
465
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
989
        self.assertIsInstance(parser, InstrumentedConfigObj)
466
990
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
467
991
                                          'utf-8')])
468
992
 
479
1003
        my_config = config.BranchConfig(branch)
480
1004
        location_config = my_config._get_location_config()
481
1005
        self.assertEqual(branch.base, location_config.location)
482
 
        self.failUnless(location_config is my_config._get_location_config())
 
1006
        self.assertIs(location_config, my_config._get_location_config())
483
1007
 
484
1008
    def test_get_config(self):
485
1009
        """The Branch.get_config method works properly"""
505
1029
        branch = self.make_branch('branch')
506
1030
        self.assertEqual('branch', branch.nick)
507
1031
 
508
 
        locations = config.locations_config_filename()
509
 
        config.ensure_config_dir_exists()
510
1032
        local_url = urlutils.local_path_to_url('branch')
511
 
        open(locations, 'wb').write('[%s]\nnickname = foobar'
512
 
                                    % (local_url,))
 
1033
        conf = config.LocationConfig.from_string(
 
1034
            '[%s]\nnickname = foobar' % (local_url,),
 
1035
            local_url, save=True)
513
1036
        self.assertEqual('foobar', branch.nick)
514
1037
 
515
1038
    def test_config_local_path(self):
517
1040
        branch = self.make_branch('branch')
518
1041
        self.assertEqual('branch', branch.nick)
519
1042
 
520
 
        locations = config.locations_config_filename()
521
 
        config.ensure_config_dir_exists()
522
 
        open(locations, 'wb').write('[%s/branch]\nnickname = barry'
523
 
                                    % (osutils.getcwd().encode('utf8'),))
 
1043
        local_path = osutils.getcwd().encode('utf8')
 
1044
        conf = config.LocationConfig.from_string(
 
1045
            '[%s/branch]\nnickname = barry' % (local_path,),
 
1046
            'branch',  save=True)
524
1047
        self.assertEqual('barry', branch.nick)
525
1048
 
526
1049
    def test_config_creates_local(self):
527
1050
        """Creating a new entry in config uses a local path."""
528
1051
        branch = self.make_branch('branch', format='knit')
529
1052
        branch.set_push_location('http://foobar')
530
 
        locations = config.locations_config_filename()
531
1053
        local_path = osutils.getcwd().encode('utf8')
532
1054
        # Surprisingly ConfigObj doesn't create a trailing newline
533
 
        self.check_file_contents(locations,
 
1055
        self.check_file_contents(config.locations_config_filename(),
534
1056
                                 '[%s/branch]\n'
535
1057
                                 'push_location = http://foobar\n'
536
1058
                                 'push_location:policy = norecurse\n'
541
1063
        self.assertEqual('!repo', b.get_config().get_nickname())
542
1064
 
543
1065
    def test_warn_if_masked(self):
544
 
        _warning = trace.warning
545
1066
        warnings = []
546
1067
        def warning(*args):
547
1068
            warnings.append(args[0] % args[1:])
 
1069
        self.overrideAttr(trace, 'warning', warning)
548
1070
 
549
1071
        def set_option(store, warn_masked=True):
550
1072
            warnings[:] = []
556
1078
            else:
557
1079
                self.assertEqual(1, len(warnings))
558
1080
                self.assertEqual(warning, warnings[0])
559
 
        trace.warning = warning
560
 
        try:
561
 
            branch = self.make_branch('.')
562
 
            conf = branch.get_config()
563
 
            set_option(config.STORE_GLOBAL)
564
 
            assertWarning(None)
565
 
            set_option(config.STORE_BRANCH)
566
 
            assertWarning(None)
567
 
            set_option(config.STORE_GLOBAL)
568
 
            assertWarning('Value "4" is masked by "3" from branch.conf')
569
 
            set_option(config.STORE_GLOBAL, warn_masked=False)
570
 
            assertWarning(None)
571
 
            set_option(config.STORE_LOCATION)
572
 
            assertWarning(None)
573
 
            set_option(config.STORE_BRANCH)
574
 
            assertWarning('Value "3" is masked by "0" from locations.conf')
575
 
            set_option(config.STORE_BRANCH, warn_masked=False)
576
 
            assertWarning(None)
577
 
        finally:
578
 
            trace.warning = _warning
579
 
 
580
 
 
581
 
class TestGlobalConfigItems(tests.TestCase):
 
1081
        branch = self.make_branch('.')
 
1082
        conf = branch.get_config()
 
1083
        set_option(config.STORE_GLOBAL)
 
1084
        assertWarning(None)
 
1085
        set_option(config.STORE_BRANCH)
 
1086
        assertWarning(None)
 
1087
        set_option(config.STORE_GLOBAL)
 
1088
        assertWarning('Value "4" is masked by "3" from branch.conf')
 
1089
        set_option(config.STORE_GLOBAL, warn_masked=False)
 
1090
        assertWarning(None)
 
1091
        set_option(config.STORE_LOCATION)
 
1092
        assertWarning(None)
 
1093
        set_option(config.STORE_BRANCH)
 
1094
        assertWarning('Value "3" is masked by "0" from locations.conf')
 
1095
        set_option(config.STORE_BRANCH, warn_masked=False)
 
1096
        assertWarning(None)
 
1097
 
 
1098
 
 
1099
class TestGlobalConfigItems(tests.TestCaseInTempDir):
582
1100
 
583
1101
    def test_user_id(self):
584
 
        config_file = StringIO(sample_config_text.encode('utf-8'))
585
 
        my_config = config.GlobalConfig()
586
 
        my_config._parser = my_config._get_parser(file=config_file)
 
1102
        my_config = config.GlobalConfig.from_string(sample_config_text)
587
1103
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
588
1104
                         my_config._get_user_id())
589
1105
 
590
1106
    def test_absent_user_id(self):
591
 
        config_file = StringIO("")
592
1107
        my_config = config.GlobalConfig()
593
 
        my_config._parser = my_config._get_parser(file=config_file)
594
1108
        self.assertEqual(None, my_config._get_user_id())
595
1109
 
596
1110
    def test_configured_editor(self):
597
 
        config_file = StringIO(sample_config_text.encode('utf-8'))
598
 
        my_config = config.GlobalConfig()
599
 
        my_config._parser = my_config._get_parser(file=config_file)
 
1111
        my_config = config.GlobalConfig.from_string(sample_config_text)
600
1112
        self.assertEqual("vim", my_config.get_editor())
601
1113
 
602
1114
    def test_signatures_always(self):
603
 
        config_file = StringIO(sample_always_signatures)
604
 
        my_config = config.GlobalConfig()
605
 
        my_config._parser = my_config._get_parser(file=config_file)
 
1115
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
606
1116
        self.assertEqual(config.CHECK_NEVER,
607
1117
                         my_config.signature_checking())
608
1118
        self.assertEqual(config.SIGN_ALWAYS,
610
1120
        self.assertEqual(True, my_config.signature_needed())
611
1121
 
612
1122
    def test_signatures_if_possible(self):
613
 
        config_file = StringIO(sample_maybe_signatures)
614
 
        my_config = config.GlobalConfig()
615
 
        my_config._parser = my_config._get_parser(file=config_file)
 
1123
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
616
1124
        self.assertEqual(config.CHECK_NEVER,
617
1125
                         my_config.signature_checking())
618
1126
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
620
1128
        self.assertEqual(False, my_config.signature_needed())
621
1129
 
622
1130
    def test_signatures_ignore(self):
623
 
        config_file = StringIO(sample_ignore_signatures)
624
 
        my_config = config.GlobalConfig()
625
 
        my_config._parser = my_config._get_parser(file=config_file)
 
1131
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
626
1132
        self.assertEqual(config.CHECK_ALWAYS,
627
1133
                         my_config.signature_checking())
628
1134
        self.assertEqual(config.SIGN_NEVER,
630
1136
        self.assertEqual(False, my_config.signature_needed())
631
1137
 
632
1138
    def _get_sample_config(self):
633
 
        config_file = StringIO(sample_config_text.encode('utf-8'))
634
 
        my_config = config.GlobalConfig()
635
 
        my_config._parser = my_config._get_parser(file=config_file)
 
1139
        my_config = config.GlobalConfig.from_string(sample_config_text)
636
1140
        return my_config
637
1141
 
638
1142
    def test_gpg_signing_command(self):
641
1145
        self.assertEqual(False, my_config.signature_needed())
642
1146
 
643
1147
    def _get_empty_config(self):
644
 
        config_file = StringIO("")
645
1148
        my_config = config.GlobalConfig()
646
 
        my_config._parser = my_config._get_parser(file=config_file)
647
1149
        return my_config
648
1150
 
649
1151
    def test_gpg_signing_command_unset(self):
699
1201
        change_editor = my_config.get_change_editor('old', 'new')
700
1202
        self.assertIs(None, change_editor)
701
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
 
702
1239
 
703
1240
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
704
1241
 
722
1259
        self.assertIs(None, new_config.get_alias('commit'))
723
1260
 
724
1261
 
725
 
class TestLocationConfig(tests.TestCaseInTempDir):
 
1262
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
726
1263
 
727
1264
    def test_constructs(self):
728
1265
        my_config = config.LocationConfig('http://example.com')
740
1277
            parser = my_config._get_parser()
741
1278
        finally:
742
1279
            config.ConfigObj = oldparserclass
743
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
1280
        self.assertIsInstance(parser, InstrumentedConfigObj)
744
1281
        self.assertEqual(parser._calls,
745
1282
                         [('__init__', config.locations_config_filename(),
746
1283
                           'utf-8')])
747
 
        config.ensure_config_dir_exists()
748
 
        #os.mkdir(config.config_dir())
749
 
        f = file(config.branches_config_filename(), 'wb')
750
 
        f.write('')
751
 
        f.close()
752
 
        oldparserclass = config.ConfigObj
753
 
        config.ConfigObj = InstrumentedConfigObj
754
 
        try:
755
 
            my_config = config.LocationConfig('http://www.example.com')
756
 
            parser = my_config._get_parser()
757
 
        finally:
758
 
            config.ConfigObj = oldparserclass
759
1284
 
760
1285
    def test_get_global_config(self):
761
1286
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
762
1287
        global_config = my_config._get_global_config()
763
 
        self.failUnless(isinstance(global_config, config.GlobalConfig))
764
 
        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()))
765
1294
 
766
1295
    def test__get_matching_sections_no_match(self):
767
1296
        self.get_branch_config('/')
768
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1297
        self.assertLocationMatching([])
769
1298
 
770
1299
    def test__get_matching_sections_exact(self):
771
1300
        self.get_branch_config('http://www.example.com')
772
 
        self.assertEqual([('http://www.example.com', '')],
773
 
                         self.my_location_config._get_matching_sections())
 
1301
        self.assertLocationMatching([('http://www.example.com', '')])
774
1302
 
775
1303
    def test__get_matching_sections_suffix_does_not(self):
776
1304
        self.get_branch_config('http://www.example.com-com')
777
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1305
        self.assertLocationMatching([])
778
1306
 
779
1307
    def test__get_matching_sections_subdir_recursive(self):
780
1308
        self.get_branch_config('http://www.example.com/com')
781
 
        self.assertEqual([('http://www.example.com', 'com')],
782
 
                         self.my_location_config._get_matching_sections())
 
1309
        self.assertLocationMatching([('http://www.example.com', 'com')])
783
1310
 
784
1311
    def test__get_matching_sections_ignoreparent(self):
785
1312
        self.get_branch_config('http://www.example.com/ignoreparent')
786
 
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
787
 
                         self.my_location_config._get_matching_sections())
 
1313
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1314
                                      '')])
788
1315
 
789
1316
    def test__get_matching_sections_ignoreparent_subdir(self):
790
1317
        self.get_branch_config(
791
1318
            'http://www.example.com/ignoreparent/childbranch')
792
 
        self.assertEqual([('http://www.example.com/ignoreparent',
793
 
                           'childbranch')],
794
 
                         self.my_location_config._get_matching_sections())
 
1319
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1320
                                      'childbranch')])
795
1321
 
796
1322
    def test__get_matching_sections_subdir_trailing_slash(self):
797
1323
        self.get_branch_config('/b')
798
 
        self.assertEqual([('/b/', '')],
799
 
                         self.my_location_config._get_matching_sections())
 
1324
        self.assertLocationMatching([('/b/', '')])
800
1325
 
801
1326
    def test__get_matching_sections_subdir_child(self):
802
1327
        self.get_branch_config('/a/foo')
803
 
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
804
 
                         self.my_location_config._get_matching_sections())
 
1328
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
805
1329
 
806
1330
    def test__get_matching_sections_subdir_child_child(self):
807
1331
        self.get_branch_config('/a/foo/bar')
808
 
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
809
 
                         self.my_location_config._get_matching_sections())
 
1332
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
810
1333
 
811
1334
    def test__get_matching_sections_trailing_slash_with_children(self):
812
1335
        self.get_branch_config('/a/')
813
 
        self.assertEqual([('/a/', '')],
814
 
                         self.my_location_config._get_matching_sections())
 
1336
        self.assertLocationMatching([('/a/', '')])
815
1337
 
816
1338
    def test__get_matching_sections_explicit_over_glob(self):
817
1339
        # XXX: 2006-09-08 jamesh
819
1341
        # was a config section for '/a/?', it would get precedence
820
1342
        # over '/a/c'.
821
1343
        self.get_branch_config('/a/c')
822
 
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
823
 
                         self.my_location_config._get_matching_sections())
 
1344
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
824
1345
 
825
1346
    def test__get_option_policy_normal(self):
826
1347
        self.get_branch_config('http://www.example.com')
848
1369
            'http://www.example.com', 'appendpath_option'),
849
1370
            config.POLICY_APPENDPATH)
850
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
 
851
1387
    def test_location_without_username(self):
852
1388
        self.get_branch_config('http://www.example.com/ignoreparent')
853
1389
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
989
1525
        self.assertEqual('bzrlib.tests.test_config.post_commit',
990
1526
                         self.my_config.post_commit())
991
1527
 
992
 
    def get_branch_config(self, location, global_config=None):
 
1528
    def get_branch_config(self, location, global_config=None,
 
1529
                          location_config=None):
 
1530
        my_branch = FakeBranch(location)
993
1531
        if global_config is None:
994
 
            global_file = StringIO(sample_config_text.encode('utf-8'))
995
 
        else:
996
 
            global_file = StringIO(global_config.encode('utf-8'))
997
 
        branches_file = StringIO(sample_branches_text.encode('utf-8'))
998
 
        self.my_config = config.BranchConfig(FakeBranch(location))
999
 
        # Force location config to use specified file
1000
 
        self.my_location_config = self.my_config._get_location_config()
1001
 
        self.my_location_config._get_parser(branches_file)
1002
 
        # Force global config to use specified file
1003
 
        self.my_config._get_global_config()._get_parser(global_file)
 
1532
            global_config = sample_config_text
 
1533
        if location_config is None:
 
1534
            location_config = sample_branches_text
 
1535
 
 
1536
        my_global_config = config.GlobalConfig.from_string(global_config,
 
1537
                                                           save=True)
 
1538
        my_location_config = config.LocationConfig.from_string(
 
1539
            location_config, my_branch.base, save=True)
 
1540
        my_config = config.BranchConfig(my_branch)
 
1541
        self.my_config = my_config
 
1542
        self.my_location_config = my_config._get_location_config()
1004
1543
 
1005
1544
    def test_set_user_setting_sets_and_saves(self):
1006
1545
        self.get_branch_config('/a/c')
1007
1546
        record = InstrumentedConfigObj("foo")
1008
1547
        self.my_location_config._parser = record
1009
1548
 
1010
 
        real_mkdir = os.mkdir
1011
 
        self.created = False
1012
 
        def checked_mkdir(path, mode=0777):
1013
 
            self.log('making directory: %s', path)
1014
 
            real_mkdir(path, mode)
1015
 
            self.created = True
1016
 
 
1017
 
        os.mkdir = checked_mkdir
1018
 
        try:
1019
 
            self.callDeprecated(['The recurse option is deprecated as of '
1020
 
                                 '0.14.  The section "/a/c" has been '
1021
 
                                 'converted to use policies.'],
1022
 
                                self.my_config.set_user_option,
1023
 
                                'foo', 'bar', store=config.STORE_LOCATION)
1024
 
        finally:
1025
 
            os.mkdir = real_mkdir
1026
 
 
1027
 
        self.failUnless(self.created, 'Failed to create ~/.bazaar')
1028
 
        self.assertEqual([('__contains__', '/a/c'),
 
1549
        self.callDeprecated(['The recurse option is deprecated as of '
 
1550
                             '0.14.  The section "/a/c" has been '
 
1551
                             'converted to use policies.'],
 
1552
                            self.my_config.set_user_option,
 
1553
                            'foo', 'bar', store=config.STORE_LOCATION)
 
1554
        self.assertEqual([('reload',),
 
1555
                          ('__contains__', '/a/c'),
1029
1556
                          ('__contains__', '/a/c/'),
1030
1557
                          ('__setitem__', '/a/c', {}),
1031
1558
                          ('__getitem__', '/a/c'),
1060
1587
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1061
1588
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1062
1589
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1063
 
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
1590
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1064
1591
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1065
1592
 
1066
1593
 
1074
1601
option = exact
1075
1602
"""
1076
1603
 
1077
 
 
1078
1604
class TestBranchConfigItems(tests.TestCaseInTempDir):
1079
1605
 
1080
1606
    def get_branch_config(self, global_config=None, location=None,
1081
1607
                          location_config=None, branch_data_config=None):
1082
 
        my_config = config.BranchConfig(FakeBranch(location))
 
1608
        my_branch = FakeBranch(location)
1083
1609
        if global_config is not None:
1084
 
            global_file = StringIO(global_config.encode('utf-8'))
1085
 
            my_config._get_global_config()._get_parser(global_file)
1086
 
        self.my_location_config = my_config._get_location_config()
 
1610
            my_global_config = config.GlobalConfig.from_string(global_config,
 
1611
                                                               save=True)
1087
1612
        if location_config is not None:
1088
 
            location_file = StringIO(location_config.encode('utf-8'))
1089
 
            self.my_location_config._get_parser(location_file)
 
1613
            my_location_config = config.LocationConfig.from_string(
 
1614
                location_config, my_branch.base, save=True)
 
1615
        my_config = config.BranchConfig(my_branch)
1090
1616
        if branch_data_config is not None:
1091
1617
            my_config.branch.control_files.files['branch.conf'] = \
1092
1618
                branch_data_config
1106
1632
                         my_config.username())
1107
1633
 
1108
1634
    def test_not_set_in_branch(self):
1109
 
        my_config = self.get_branch_config(sample_config_text)
 
1635
        my_config = self.get_branch_config(global_config=sample_config_text)
1110
1636
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1111
1637
                         my_config._get_user_id())
1112
1638
        my_config.branch.control_files.files['email'] = "John"
1113
1639
        self.assertEqual("John", my_config._get_user_id())
1114
1640
 
1115
1641
    def test_BZR_EMAIL_OVERRIDES(self):
1116
 
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
 
1642
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1117
1643
        branch = FakeBranch()
1118
1644
        my_config = config.BranchConfig(branch)
1119
1645
        self.assertEqual("Robert Collins <robertc@example.org>",
1136
1662
 
1137
1663
    def test_gpg_signing_command(self):
1138
1664
        my_config = self.get_branch_config(
 
1665
            global_config=sample_config_text,
1139
1666
            # branch data cannot set gpg_signing_command
1140
1667
            branch_data_config="gpg_signing_command=pgp")
1141
 
        config_file = StringIO(sample_config_text.encode('utf-8'))
1142
 
        my_config._get_global_config()._get_parser(config_file)
1143
1668
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1144
1669
 
1145
1670
    def test_get_user_option_global(self):
1146
 
        branch = FakeBranch()
1147
 
        my_config = config.BranchConfig(branch)
1148
 
        config_file = StringIO(sample_config_text.encode('utf-8'))
1149
 
        (my_config._get_global_config()._get_parser(config_file))
 
1671
        my_config = self.get_branch_config(global_config=sample_config_text)
1150
1672
        self.assertEqual('something',
1151
1673
                         my_config.get_user_option('user_global_option'))
1152
1674
 
1153
1675
    def test_post_commit_default(self):
1154
 
        branch = FakeBranch()
1155
 
        my_config = self.get_branch_config(sample_config_text, '/a/c',
1156
 
                                           sample_branches_text)
 
1676
        my_config = self.get_branch_config(global_config=sample_config_text,
 
1677
                                      location='/a/c',
 
1678
                                      location_config=sample_branches_text)
1157
1679
        self.assertEqual(my_config.branch.base, '/a/c')
1158
1680
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1159
1681
                         my_config.post_commit())
1160
1682
        my_config.set_user_option('post_commit', 'rmtree_root')
1161
 
        # post-commit is ignored when bresent in branch data
 
1683
        # post-commit is ignored when present in branch data
1162
1684
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1163
1685
                         my_config.post_commit())
1164
1686
        my_config.set_user_option('post_commit', 'rmtree_root',
1166
1688
        self.assertEqual('rmtree_root', my_config.post_commit())
1167
1689
 
1168
1690
    def test_config_precedence(self):
 
1691
        # FIXME: eager test, luckily no persitent config file makes it fail
 
1692
        # -- vila 20100716
1169
1693
        my_config = self.get_branch_config(global_config=precedence_global)
1170
1694
        self.assertEqual(my_config.get_user_option('option'), 'global')
1171
1695
        my_config = self.get_branch_config(global_config=precedence_global,
1172
 
                                      branch_data_config=precedence_branch)
 
1696
                                           branch_data_config=precedence_branch)
1173
1697
        self.assertEqual(my_config.get_user_option('option'), 'branch')
1174
 
        my_config = self.get_branch_config(global_config=precedence_global,
1175
 
                                      branch_data_config=precedence_branch,
1176
 
                                      location_config=precedence_location)
 
1698
        my_config = self.get_branch_config(
 
1699
            global_config=precedence_global,
 
1700
            branch_data_config=precedence_branch,
 
1701
            location_config=precedence_location)
1177
1702
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
1178
 
        my_config = self.get_branch_config(global_config=precedence_global,
1179
 
                                      branch_data_config=precedence_branch,
1180
 
                                      location_config=precedence_location,
1181
 
                                      location='http://example.com/specific')
 
1703
        my_config = self.get_branch_config(
 
1704
            global_config=precedence_global,
 
1705
            branch_data_config=precedence_branch,
 
1706
            location_config=precedence_location,
 
1707
            location='http://example.com/specific')
1182
1708
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1183
1709
 
1184
1710
    def test_get_mail_client(self):
1312
1838
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1313
1839
 
1314
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
 
1315
2410
class TestAuthenticationConfigFile(tests.TestCase):
1316
2411
    """Test the authentication.conf file matching"""
1317
2412
 
1812
2907
# test_user_prompted ?
1813
2908
class TestAuthenticationRing(tests.TestCaseWithTransport):
1814
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