/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: Martin
  • Date: 2011-05-21 16:43:19 UTC
  • mto: This revision was merged to the branch mainline in revision 5907.
  • Revision ID: gzlist@googlemail.com-20110521164319-5ua6aoazejsvef0w
Avoid implicit str casting in trace methods by calling unicode() on conflict objects first

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
# FIXME: Same remark as above for the following registry -- vila 20110503
 
89
test_stack_builder_registry = registry.Registry()
 
90
test_stack_builder_registry.register(
 
91
    'bazaar', lambda test: config.GlobalStack())
 
92
test_stack_builder_registry.register(
 
93
    'location', lambda test: config.LocationStack('.'))
 
94
test_stack_builder_registry.register(
 
95
    'branch', lambda test: config.BranchStack(test.branch))
 
96
 
 
97
 
41
98
sample_long_alias="log -r-15..-1 --line"
42
99
sample_config_text = u"""
43
100
[DEFAULT]
47
104
gpg_signing_command=gnome-gpg
48
105
log_format=short
49
106
user_global_option=something
 
107
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
 
108
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
 
109
bzr.default_mergetool=sometool
50
110
[ALIASES]
51
111
h=help
52
112
ll=""" + sample_long_alias + "\n"
105
165
"""
106
166
 
107
167
 
 
168
def create_configs(test):
 
169
    """Create configuration files for a given test.
 
170
 
 
171
    This requires creating a tree (and populate the ``test.tree`` attribute)
 
172
    and its associated branch and will populate the following attributes:
 
173
 
 
174
    - branch_config: A BranchConfig for the associated branch.
 
175
 
 
176
    - locations_config : A LocationConfig for the associated branch
 
177
 
 
178
    - bazaar_config: A GlobalConfig.
 
179
 
 
180
    The tree and branch are created in a 'tree' subdirectory so the tests can
 
181
    still use the test directory to stay outside of the branch.
 
182
    """
 
183
    tree = test.make_branch_and_tree('tree')
 
184
    test.tree = tree
 
185
    test.branch_config = config.BranchConfig(tree.branch)
 
186
    test.locations_config = config.LocationConfig(tree.basedir)
 
187
    test.bazaar_config = config.GlobalConfig()
 
188
 
 
189
 
 
190
def create_configs_with_file_option(test):
 
191
    """Create configuration files with a ``file`` option set in each.
 
192
 
 
193
    This builds on ``create_configs`` and add one ``file`` option in each
 
194
    configuration with a value which allows identifying the configuration file.
 
195
    """
 
196
    create_configs(test)
 
197
    test.bazaar_config.set_user_option('file', 'bazaar')
 
198
    test.locations_config.set_user_option('file', 'locations')
 
199
    test.branch_config.set_user_option('file', 'branch')
 
200
 
 
201
 
 
202
class TestOptionsMixin:
 
203
 
 
204
    def assertOptions(self, expected, conf):
 
205
        # We don't care about the parser (as it will make tests hard to write
 
206
        # and error-prone anyway)
 
207
        self.assertThat([opt[:4] for opt in conf._get_options()],
 
208
                        matchers.Equals(expected))
 
209
 
 
210
 
108
211
class InstrumentedConfigObj(object):
109
212
    """A config obj look-enough-alike to record calls made to it."""
110
213
 
129
232
        self._calls.append(('keys',))
130
233
        return []
131
234
 
 
235
    def reload(self):
 
236
        self._calls.append(('reload',))
 
237
 
132
238
    def write(self, arg):
133
239
        self._calls.append(('write',))
134
240
 
240
346
        """
241
347
        co = config.ConfigObj()
242
348
        co['test'] = 'foo#bar'
243
 
        lines = co.write()
 
349
        outfile = StringIO()
 
350
        co.write(outfile=outfile)
 
351
        lines = outfile.getvalue().splitlines()
244
352
        self.assertEqual(lines, ['test = "foo#bar"'])
245
353
        co2 = config.ConfigObj(lines)
246
354
        self.assertEqual(co2['test'], 'foo#bar')
247
355
 
 
356
    def test_triple_quotes(self):
 
357
        # Bug #710410: if the value string has triple quotes
 
358
        # then ConfigObj versions up to 4.7.2 will quote them wrong
 
359
        # and won't able to read them back
 
360
        triple_quotes_value = '''spam
 
361
""" that's my spam """
 
362
eggs'''
 
363
        co = config.ConfigObj()
 
364
        co['test'] = triple_quotes_value
 
365
        # While writing this test another bug in ConfigObj has been found:
 
366
        # method co.write() without arguments produces list of lines
 
367
        # one option per line, and multiline values are not split
 
368
        # across multiple lines,
 
369
        # and that breaks the parsing these lines back by ConfigObj.
 
370
        # This issue only affects test, but it's better to avoid
 
371
        # `co.write()` construct at all.
 
372
        # [bialix 20110222] bug report sent to ConfigObj's author
 
373
        outfile = StringIO()
 
374
        co.write(outfile=outfile)
 
375
        output = outfile.getvalue()
 
376
        # now we're trying to read it back
 
377
        co2 = config.ConfigObj(StringIO(output))
 
378
        self.assertEquals(triple_quotes_value, co2['test'])
 
379
 
248
380
 
249
381
erroneous_config = """[section] # line 1
250
382
good=good # line 2
333
465
 
334
466
    def setUp(self):
335
467
        super(TestConfigPath, self).setUp()
336
 
        os.environ['HOME'] = '/home/bogus'
337
 
        os.environ['XDG_CACHE_DIR'] = ''
 
468
        self.overrideEnv('HOME', '/home/bogus')
 
469
        self.overrideEnv('XDG_CACHE_DIR', '')
338
470
        if sys.platform == 'win32':
339
 
            os.environ['BZR_HOME'] = \
340
 
                r'C:\Documents and Settings\bogus\Application Data'
 
471
            self.overrideEnv(
 
472
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
341
473
            self.bzr_home = \
342
474
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
343
475
        else:
350
482
        self.assertEqual(config.config_filename(),
351
483
                         self.bzr_home + '/bazaar.conf')
352
484
 
353
 
    def test_branches_config_filename(self):
354
 
        self.assertEqual(config.branches_config_filename(),
355
 
                         self.bzr_home + '/branches.conf')
356
 
 
357
485
    def test_locations_config_filename(self):
358
486
        self.assertEqual(config.locations_config_filename(),
359
487
                         self.bzr_home + '/locations.conf')
367
495
            '/home/bogus/.cache')
368
496
 
369
497
 
370
 
class TestIniConfig(tests.TestCase):
 
498
class TestXDGConfigDir(tests.TestCaseInTempDir):
 
499
    # must be in temp dir because config tests for the existence of the bazaar
 
500
    # subdirectory of $XDG_CONFIG_HOME
 
501
 
 
502
    def setUp(self):
 
503
        if sys.platform in ('darwin', 'win32'):
 
504
            raise tests.TestNotApplicable(
 
505
                'XDG config dir not used on this platform')
 
506
        super(TestXDGConfigDir, self).setUp()
 
507
        self.overrideEnv('HOME', self.test_home_dir)
 
508
        # BZR_HOME overrides everything we want to test so unset it.
 
509
        self.overrideEnv('BZR_HOME', None)
 
510
 
 
511
    def test_xdg_config_dir_exists(self):
 
512
        """When ~/.config/bazaar exists, use it as the config dir."""
 
513
        newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
 
514
        os.makedirs(newdir)
 
515
        self.assertEqual(config.config_dir(), newdir)
 
516
 
 
517
    def test_xdg_config_home(self):
 
518
        """When XDG_CONFIG_HOME is set, use it."""
 
519
        xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
 
520
        self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
 
521
        newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
 
522
        os.makedirs(newdir)
 
523
        self.assertEqual(config.config_dir(), newdir)
 
524
 
 
525
 
 
526
class TestIniConfig(tests.TestCaseInTempDir):
371
527
 
372
528
    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
 
529
        conf = config.IniBasedConfig.from_string(s)
 
530
        return conf, conf._get_parser()
376
531
 
377
532
 
378
533
class TestIniConfigBuilding(TestIniConfig):
379
534
 
380
535
    def test_contructs(self):
381
 
        my_config = config.IniBasedConfig("nothing")
 
536
        my_config = config.IniBasedConfig()
382
537
 
383
538
    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))
 
539
        my_config = config.IniBasedConfig.from_string(sample_config_text)
 
540
        self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
389
541
 
390
542
    def test_cached(self):
 
543
        my_config = config.IniBasedConfig.from_string(sample_config_text)
 
544
        parser = my_config._get_parser()
 
545
        self.assertTrue(my_config._get_parser() is parser)
 
546
 
 
547
    def _dummy_chown(self, path, uid, gid):
 
548
        self.path, self.uid, self.gid = path, uid, gid
 
549
 
 
550
    def test_ini_config_ownership(self):
 
551
        """Ensure that chown is happening during _write_config_file"""
 
552
        self.requireFeature(features.chown_feature)
 
553
        self.overrideAttr(os, 'chown', self._dummy_chown)
 
554
        self.path = self.uid = self.gid = None
 
555
        conf = config.IniBasedConfig(file_name='./foo.conf')
 
556
        conf._write_config_file()
 
557
        self.assertEquals(self.path, './foo.conf')
 
558
        self.assertTrue(isinstance(self.uid, int))
 
559
        self.assertTrue(isinstance(self.gid, int))
 
560
 
 
561
    def test_get_filename_parameter_is_deprecated_(self):
 
562
        conf = self.callDeprecated([
 
563
            'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
 
564
            ' Use file_name instead.'],
 
565
            config.IniBasedConfig, lambda: 'ini.conf')
 
566
        self.assertEqual('ini.conf', conf.file_name)
 
567
 
 
568
    def test_get_parser_file_parameter_is_deprecated_(self):
391
569
        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)
 
570
        conf = config.IniBasedConfig.from_string(sample_config_text)
 
571
        conf = self.callDeprecated([
 
572
            'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
 
573
            ' Use IniBasedConfig(_content=xxx) instead.'],
 
574
            conf._get_parser, file=config_file)
 
575
 
 
576
 
 
577
class TestIniConfigSaving(tests.TestCaseInTempDir):
 
578
 
 
579
    def test_cant_save_without_a_file_name(self):
 
580
        conf = config.IniBasedConfig()
 
581
        self.assertRaises(AssertionError, conf._write_config_file)
 
582
 
 
583
    def test_saved_with_content(self):
 
584
        content = 'foo = bar\n'
 
585
        conf = config.IniBasedConfig.from_string(
 
586
            content, file_name='./test.conf', save=True)
 
587
        self.assertFileEqual(content, 'test.conf')
 
588
 
 
589
 
 
590
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
 
591
    """What is the default value of expand for config options.
 
592
 
 
593
    This is an opt-in beta feature used to evaluate whether or not option
 
594
    references can appear in dangerous place raising exceptions, disapearing
 
595
    (and as such corrupting data) or if it's safe to activate the option by
 
596
    default.
 
597
 
 
598
    Note that these tests relies on config._expand_default_value being already
 
599
    overwritten in the parent class setUp.
 
600
    """
 
601
 
 
602
    def setUp(self):
 
603
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
 
604
        self.config = None
 
605
        self.warnings = []
 
606
        def warning(*args):
 
607
            self.warnings.append(args[0] % args[1:])
 
608
        self.overrideAttr(trace, 'warning', warning)
 
609
 
 
610
    def get_config(self, expand):
 
611
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
 
612
                                            save=True)
 
613
        return c
 
614
 
 
615
    def assertExpandIs(self, expected):
 
616
        actual = config._get_expand_default_value()
 
617
        #self.config.get_user_option_as_bool('bzr.config.expand')
 
618
        self.assertEquals(expected, actual)
 
619
 
 
620
    def test_default_is_None(self):
 
621
        self.assertEquals(None, config._expand_default_value)
 
622
 
 
623
    def test_default_is_False_even_if_None(self):
 
624
        self.config = self.get_config(None)
 
625
        self.assertExpandIs(False)
 
626
 
 
627
    def test_default_is_False_even_if_invalid(self):
 
628
        self.config = self.get_config('<your choice>')
 
629
        self.assertExpandIs(False)
 
630
        # ...
 
631
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
 
632
        # Wait, you've been warned !
 
633
        self.assertLength(1, self.warnings)
 
634
        self.assertEquals(
 
635
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
 
636
            self.warnings[0])
 
637
 
 
638
    def test_default_is_True(self):
 
639
        self.config = self.get_config(True)
 
640
        self.assertExpandIs(True)
 
641
        
 
642
    def test_default_is_False(self):
 
643
        self.config = self.get_config(False)
 
644
        self.assertExpandIs(False)
 
645
        
 
646
 
 
647
class TestIniConfigOptionExpansion(tests.TestCase):
 
648
    """Test option expansion from the IniConfig level.
 
649
 
 
650
    What we really want here is to test the Config level, but the class being
 
651
    abstract as far as storing values is concerned, this can't be done
 
652
    properly (yet).
 
653
    """
 
654
    # FIXME: This should be rewritten when all configs share a storage
 
655
    # implementation -- vila 2011-02-18
 
656
 
 
657
    def get_config(self, string=None):
 
658
        if string is None:
 
659
            string = ''
 
660
        c = config.IniBasedConfig.from_string(string)
 
661
        return c
 
662
 
 
663
    def assertExpansion(self, expected, conf, string, env=None):
 
664
        self.assertEquals(expected, conf.expand_options(string, env))
 
665
 
 
666
    def test_no_expansion(self):
 
667
        c = self.get_config('')
 
668
        self.assertExpansion('foo', c, 'foo')
 
669
 
 
670
    def test_env_adding_options(self):
 
671
        c = self.get_config('')
 
672
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
673
 
 
674
    def test_env_overriding_options(self):
 
675
        c = self.get_config('foo=baz')
 
676
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
677
 
 
678
    def test_simple_ref(self):
 
679
        c = self.get_config('foo=xxx')
 
680
        self.assertExpansion('xxx', c, '{foo}')
 
681
 
 
682
    def test_unknown_ref(self):
 
683
        c = self.get_config('')
 
684
        self.assertRaises(errors.ExpandingUnknownOption,
 
685
                          c.expand_options, '{foo}')
 
686
 
 
687
    def test_indirect_ref(self):
 
688
        c = self.get_config('''
 
689
foo=xxx
 
690
bar={foo}
 
691
''')
 
692
        self.assertExpansion('xxx', c, '{bar}')
 
693
 
 
694
    def test_embedded_ref(self):
 
695
        c = self.get_config('''
 
696
foo=xxx
 
697
bar=foo
 
698
''')
 
699
        self.assertExpansion('xxx', c, '{{bar}}')
 
700
 
 
701
    def test_simple_loop(self):
 
702
        c = self.get_config('foo={foo}')
 
703
        self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
 
704
 
 
705
    def test_indirect_loop(self):
 
706
        c = self.get_config('''
 
707
foo={bar}
 
708
bar={baz}
 
709
baz={foo}''')
 
710
        e = self.assertRaises(errors.OptionExpansionLoop,
 
711
                              c.expand_options, '{foo}')
 
712
        self.assertEquals('foo->bar->baz', e.refs)
 
713
        self.assertEquals('{foo}', e.string)
 
714
 
 
715
    def test_list(self):
 
716
        conf = self.get_config('''
 
717
foo=start
 
718
bar=middle
 
719
baz=end
 
720
list={foo},{bar},{baz}
 
721
''')
 
722
        self.assertEquals(['start', 'middle', 'end'],
 
723
                           conf.get_user_option('list', expand=True))
 
724
 
 
725
    def test_cascading_list(self):
 
726
        conf = self.get_config('''
 
727
foo=start,{bar}
 
728
bar=middle,{baz}
 
729
baz=end
 
730
list={foo}
 
731
''')
 
732
        self.assertEquals(['start', 'middle', 'end'],
 
733
                           conf.get_user_option('list', expand=True))
 
734
 
 
735
    def test_pathological_hidden_list(self):
 
736
        conf = self.get_config('''
 
737
foo=bin
 
738
bar=go
 
739
start={foo
 
740
middle=},{
 
741
end=bar}
 
742
hidden={start}{middle}{end}
 
743
''')
 
744
        # Nope, it's either a string or a list, and the list wins as soon as a
 
745
        # ',' appears, so the string concatenation never occur.
 
746
        self.assertEquals(['{foo', '}', '{', 'bar}'],
 
747
                          conf.get_user_option('hidden', expand=True))
 
748
 
 
749
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
 
750
 
 
751
    def get_config(self, location, string=None):
 
752
        if string is None:
 
753
            string = ''
 
754
        # Since we don't save the config we won't strictly require to inherit
 
755
        # from TestCaseInTempDir, but an error occurs so quickly...
 
756
        c = config.LocationConfig.from_string(string, location)
 
757
        return c
 
758
 
 
759
    def test_dont_cross_unrelated_section(self):
 
760
        c = self.get_config('/another/branch/path','''
 
761
[/one/branch/path]
 
762
foo = hello
 
763
bar = {foo}/2
 
764
 
 
765
[/another/branch/path]
 
766
bar = {foo}/2
 
767
''')
 
768
        self.assertRaises(errors.ExpandingUnknownOption,
 
769
                          c.get_user_option, 'bar', expand=True)
 
770
 
 
771
    def test_cross_related_sections(self):
 
772
        c = self.get_config('/project/branch/path','''
 
773
[/project]
 
774
foo = qu
 
775
 
 
776
[/project/branch/path]
 
777
bar = {foo}ux
 
778
''')
 
779
        self.assertEquals('quux', c.get_user_option('bar', expand=True))
 
780
 
 
781
 
 
782
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
 
783
 
 
784
    def test_cannot_reload_without_name(self):
 
785
        conf = config.IniBasedConfig.from_string(sample_config_text)
 
786
        self.assertRaises(AssertionError, conf.reload)
 
787
 
 
788
    def test_reload_see_new_value(self):
 
789
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
 
790
                                               file_name='./test/conf')
 
791
        c1._write_config_file()
 
792
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
 
793
                                               file_name='./test/conf')
 
794
        c2._write_config_file()
 
795
        self.assertEqual('vim', c1.get_user_option('editor'))
 
796
        self.assertEqual('emacs', c2.get_user_option('editor'))
 
797
        # Make sure we get the Right value
 
798
        c1.reload()
 
799
        self.assertEqual('emacs', c1.get_user_option('editor'))
 
800
 
 
801
 
 
802
class TestLockableConfig(tests.TestCaseInTempDir):
 
803
 
 
804
    scenarios = lockable_config_scenarios()
 
805
 
 
806
    # Set by load_tests
 
807
    config_class = None
 
808
    config_args = None
 
809
    config_section = None
 
810
 
 
811
    def setUp(self):
 
812
        super(TestLockableConfig, self).setUp()
 
813
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
 
814
        self.config = self.create_config(self._content)
 
815
 
 
816
    def get_existing_config(self):
 
817
        return self.config_class(*self.config_args)
 
818
 
 
819
    def create_config(self, content):
 
820
        kwargs = dict(save=True)
 
821
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
 
822
        return c
 
823
 
 
824
    def test_simple_read_access(self):
 
825
        self.assertEquals('1', self.config.get_user_option('one'))
 
826
 
 
827
    def test_simple_write_access(self):
 
828
        self.config.set_user_option('one', 'one')
 
829
        self.assertEquals('one', self.config.get_user_option('one'))
 
830
 
 
831
    def test_listen_to_the_last_speaker(self):
 
832
        c1 = self.config
 
833
        c2 = self.get_existing_config()
 
834
        c1.set_user_option('one', 'ONE')
 
835
        c2.set_user_option('two', 'TWO')
 
836
        self.assertEquals('ONE', c1.get_user_option('one'))
 
837
        self.assertEquals('TWO', c2.get_user_option('two'))
 
838
        # The second update respect the first one
 
839
        self.assertEquals('ONE', c2.get_user_option('one'))
 
840
 
 
841
    def test_last_speaker_wins(self):
 
842
        # If the same config is not shared, the same variable modified twice
 
843
        # can only see a single result.
 
844
        c1 = self.config
 
845
        c2 = self.get_existing_config()
 
846
        c1.set_user_option('one', 'c1')
 
847
        c2.set_user_option('one', 'c2')
 
848
        self.assertEquals('c2', c2._get_user_option('one'))
 
849
        # The first modification is still available until another refresh
 
850
        # occur
 
851
        self.assertEquals('c1', c1._get_user_option('one'))
 
852
        c1.set_user_option('two', 'done')
 
853
        self.assertEquals('c2', c1._get_user_option('one'))
 
854
 
 
855
    def test_writes_are_serialized(self):
 
856
        c1 = self.config
 
857
        c2 = self.get_existing_config()
 
858
 
 
859
        # We spawn a thread that will pause *during* the write
 
860
        before_writing = threading.Event()
 
861
        after_writing = threading.Event()
 
862
        writing_done = threading.Event()
 
863
        c1_orig = c1._write_config_file
 
864
        def c1_write_config_file():
 
865
            before_writing.set()
 
866
            c1_orig()
 
867
            # The lock is held. We wait for the main thread to decide when to
 
868
            # continue
 
869
            after_writing.wait()
 
870
        c1._write_config_file = c1_write_config_file
 
871
        def c1_set_option():
 
872
            c1.set_user_option('one', 'c1')
 
873
            writing_done.set()
 
874
        t1 = threading.Thread(target=c1_set_option)
 
875
        # Collect the thread after the test
 
876
        self.addCleanup(t1.join)
 
877
        # Be ready to unblock the thread if the test goes wrong
 
878
        self.addCleanup(after_writing.set)
 
879
        t1.start()
 
880
        before_writing.wait()
 
881
        self.assertTrue(c1._lock.is_held)
 
882
        self.assertRaises(errors.LockContention,
 
883
                          c2.set_user_option, 'one', 'c2')
 
884
        self.assertEquals('c1', c1.get_user_option('one'))
 
885
        # Let the lock be released
 
886
        after_writing.set()
 
887
        writing_done.wait()
 
888
        c2.set_user_option('one', 'c2')
 
889
        self.assertEquals('c2', c2.get_user_option('one'))
 
890
 
 
891
    def test_read_while_writing(self):
 
892
       c1 = self.config
 
893
       # We spawn a thread that will pause *during* the write
 
894
       ready_to_write = threading.Event()
 
895
       do_writing = threading.Event()
 
896
       writing_done = threading.Event()
 
897
       c1_orig = c1._write_config_file
 
898
       def c1_write_config_file():
 
899
           ready_to_write.set()
 
900
           # The lock is held. We wait for the main thread to decide when to
 
901
           # continue
 
902
           do_writing.wait()
 
903
           c1_orig()
 
904
           writing_done.set()
 
905
       c1._write_config_file = c1_write_config_file
 
906
       def c1_set_option():
 
907
           c1.set_user_option('one', 'c1')
 
908
       t1 = threading.Thread(target=c1_set_option)
 
909
       # Collect the thread after the test
 
910
       self.addCleanup(t1.join)
 
911
       # Be ready to unblock the thread if the test goes wrong
 
912
       self.addCleanup(do_writing.set)
 
913
       t1.start()
 
914
       # Ensure the thread is ready to write
 
915
       ready_to_write.wait()
 
916
       self.assertTrue(c1._lock.is_held)
 
917
       self.assertEquals('c1', c1.get_user_option('one'))
 
918
       # If we read during the write, we get the old value
 
919
       c2 = self.get_existing_config()
 
920
       self.assertEquals('1', c2.get_user_option('one'))
 
921
       # Let the writing occur and ensure it occurred
 
922
       do_writing.set()
 
923
       writing_done.wait()
 
924
       # Now we get the updated value
 
925
       c3 = self.get_existing_config()
 
926
       self.assertEquals('c1', c3.get_user_option('one'))
395
927
 
396
928
 
397
929
class TestGetUserOptionAs(TestIniConfig):
462
994
            parser = my_config._get_parser()
463
995
        finally:
464
996
            config.ConfigObj = oldparserclass
465
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
997
        self.assertIsInstance(parser, InstrumentedConfigObj)
466
998
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
467
999
                                          'utf-8')])
468
1000
 
479
1011
        my_config = config.BranchConfig(branch)
480
1012
        location_config = my_config._get_location_config()
481
1013
        self.assertEqual(branch.base, location_config.location)
482
 
        self.failUnless(location_config is my_config._get_location_config())
 
1014
        self.assertIs(location_config, my_config._get_location_config())
483
1015
 
484
1016
    def test_get_config(self):
485
1017
        """The Branch.get_config method works properly"""
505
1037
        branch = self.make_branch('branch')
506
1038
        self.assertEqual('branch', branch.nick)
507
1039
 
508
 
        locations = config.locations_config_filename()
509
 
        config.ensure_config_dir_exists()
510
1040
        local_url = urlutils.local_path_to_url('branch')
511
 
        open(locations, 'wb').write('[%s]\nnickname = foobar'
512
 
                                    % (local_url,))
 
1041
        conf = config.LocationConfig.from_string(
 
1042
            '[%s]\nnickname = foobar' % (local_url,),
 
1043
            local_url, save=True)
513
1044
        self.assertEqual('foobar', branch.nick)
514
1045
 
515
1046
    def test_config_local_path(self):
517
1048
        branch = self.make_branch('branch')
518
1049
        self.assertEqual('branch', branch.nick)
519
1050
 
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'),))
 
1051
        local_path = osutils.getcwd().encode('utf8')
 
1052
        conf = config.LocationConfig.from_string(
 
1053
            '[%s/branch]\nnickname = barry' % (local_path,),
 
1054
            'branch',  save=True)
524
1055
        self.assertEqual('barry', branch.nick)
525
1056
 
526
1057
    def test_config_creates_local(self):
527
1058
        """Creating a new entry in config uses a local path."""
528
1059
        branch = self.make_branch('branch', format='knit')
529
1060
        branch.set_push_location('http://foobar')
530
 
        locations = config.locations_config_filename()
531
1061
        local_path = osutils.getcwd().encode('utf8')
532
1062
        # Surprisingly ConfigObj doesn't create a trailing newline
533
 
        self.check_file_contents(locations,
 
1063
        self.check_file_contents(config.locations_config_filename(),
534
1064
                                 '[%s/branch]\n'
535
1065
                                 'push_location = http://foobar\n'
536
1066
                                 'push_location:policy = norecurse\n'
541
1071
        self.assertEqual('!repo', b.get_config().get_nickname())
542
1072
 
543
1073
    def test_warn_if_masked(self):
544
 
        _warning = trace.warning
545
1074
        warnings = []
546
1075
        def warning(*args):
547
1076
            warnings.append(args[0] % args[1:])
 
1077
        self.overrideAttr(trace, 'warning', warning)
548
1078
 
549
1079
        def set_option(store, warn_masked=True):
550
1080
            warnings[:] = []
556
1086
            else:
557
1087
                self.assertEqual(1, len(warnings))
558
1088
                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):
 
1089
        branch = self.make_branch('.')
 
1090
        conf = branch.get_config()
 
1091
        set_option(config.STORE_GLOBAL)
 
1092
        assertWarning(None)
 
1093
        set_option(config.STORE_BRANCH)
 
1094
        assertWarning(None)
 
1095
        set_option(config.STORE_GLOBAL)
 
1096
        assertWarning('Value "4" is masked by "3" from branch.conf')
 
1097
        set_option(config.STORE_GLOBAL, warn_masked=False)
 
1098
        assertWarning(None)
 
1099
        set_option(config.STORE_LOCATION)
 
1100
        assertWarning(None)
 
1101
        set_option(config.STORE_BRANCH)
 
1102
        assertWarning('Value "3" is masked by "0" from locations.conf')
 
1103
        set_option(config.STORE_BRANCH, warn_masked=False)
 
1104
        assertWarning(None)
 
1105
 
 
1106
 
 
1107
class TestGlobalConfigItems(tests.TestCaseInTempDir):
582
1108
 
583
1109
    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)
 
1110
        my_config = config.GlobalConfig.from_string(sample_config_text)
587
1111
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
588
1112
                         my_config._get_user_id())
589
1113
 
590
1114
    def test_absent_user_id(self):
591
 
        config_file = StringIO("")
592
1115
        my_config = config.GlobalConfig()
593
 
        my_config._parser = my_config._get_parser(file=config_file)
594
1116
        self.assertEqual(None, my_config._get_user_id())
595
1117
 
596
1118
    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)
 
1119
        my_config = config.GlobalConfig.from_string(sample_config_text)
600
1120
        self.assertEqual("vim", my_config.get_editor())
601
1121
 
602
1122
    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)
 
1123
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
606
1124
        self.assertEqual(config.CHECK_NEVER,
607
1125
                         my_config.signature_checking())
608
1126
        self.assertEqual(config.SIGN_ALWAYS,
610
1128
        self.assertEqual(True, my_config.signature_needed())
611
1129
 
612
1130
    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)
 
1131
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
616
1132
        self.assertEqual(config.CHECK_NEVER,
617
1133
                         my_config.signature_checking())
618
1134
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
620
1136
        self.assertEqual(False, my_config.signature_needed())
621
1137
 
622
1138
    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)
 
1139
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
626
1140
        self.assertEqual(config.CHECK_ALWAYS,
627
1141
                         my_config.signature_checking())
628
1142
        self.assertEqual(config.SIGN_NEVER,
630
1144
        self.assertEqual(False, my_config.signature_needed())
631
1145
 
632
1146
    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)
 
1147
        my_config = config.GlobalConfig.from_string(sample_config_text)
636
1148
        return my_config
637
1149
 
638
1150
    def test_gpg_signing_command(self):
641
1153
        self.assertEqual(False, my_config.signature_needed())
642
1154
 
643
1155
    def _get_empty_config(self):
644
 
        config_file = StringIO("")
645
1156
        my_config = config.GlobalConfig()
646
 
        my_config._parser = my_config._get_parser(file=config_file)
647
1157
        return my_config
648
1158
 
649
1159
    def test_gpg_signing_command_unset(self):
699
1209
        change_editor = my_config.get_change_editor('old', 'new')
700
1210
        self.assertIs(None, change_editor)
701
1211
 
 
1212
    def test_get_merge_tools(self):
 
1213
        conf = self._get_sample_config()
 
1214
        tools = conf.get_merge_tools()
 
1215
        self.log(repr(tools))
 
1216
        self.assertEqual(
 
1217
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
 
1218
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
 
1219
            tools)
 
1220
 
 
1221
    def test_get_merge_tools_empty(self):
 
1222
        conf = self._get_empty_config()
 
1223
        tools = conf.get_merge_tools()
 
1224
        self.assertEqual({}, tools)
 
1225
 
 
1226
    def test_find_merge_tool(self):
 
1227
        conf = self._get_sample_config()
 
1228
        cmdline = conf.find_merge_tool('sometool')
 
1229
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
 
1230
 
 
1231
    def test_find_merge_tool_not_found(self):
 
1232
        conf = self._get_sample_config()
 
1233
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
 
1234
        self.assertIs(cmdline, None)
 
1235
 
 
1236
    def test_find_merge_tool_known(self):
 
1237
        conf = self._get_empty_config()
 
1238
        cmdline = conf.find_merge_tool('kdiff3')
 
1239
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
 
1240
 
 
1241
    def test_find_merge_tool_override_known(self):
 
1242
        conf = self._get_empty_config()
 
1243
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
 
1244
        cmdline = conf.find_merge_tool('kdiff3')
 
1245
        self.assertEqual('kdiff3 blah', cmdline)
 
1246
 
702
1247
 
703
1248
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
704
1249
 
722
1267
        self.assertIs(None, new_config.get_alias('commit'))
723
1268
 
724
1269
 
725
 
class TestLocationConfig(tests.TestCaseInTempDir):
 
1270
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
726
1271
 
727
1272
    def test_constructs(self):
728
1273
        my_config = config.LocationConfig('http://example.com')
740
1285
            parser = my_config._get_parser()
741
1286
        finally:
742
1287
            config.ConfigObj = oldparserclass
743
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
1288
        self.assertIsInstance(parser, InstrumentedConfigObj)
744
1289
        self.assertEqual(parser._calls,
745
1290
                         [('__init__', config.locations_config_filename(),
746
1291
                           '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
1292
 
760
1293
    def test_get_global_config(self):
761
1294
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
762
1295
        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())
 
1296
        self.assertIsInstance(global_config, config.GlobalConfig)
 
1297
        self.assertIs(global_config, my_config._get_global_config())
 
1298
 
 
1299
    def assertLocationMatching(self, expected):
 
1300
        self.assertEqual(expected,
 
1301
                         list(self.my_location_config._get_matching_sections()))
765
1302
 
766
1303
    def test__get_matching_sections_no_match(self):
767
1304
        self.get_branch_config('/')
768
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1305
        self.assertLocationMatching([])
769
1306
 
770
1307
    def test__get_matching_sections_exact(self):
771
1308
        self.get_branch_config('http://www.example.com')
772
 
        self.assertEqual([('http://www.example.com', '')],
773
 
                         self.my_location_config._get_matching_sections())
 
1309
        self.assertLocationMatching([('http://www.example.com', '')])
774
1310
 
775
1311
    def test__get_matching_sections_suffix_does_not(self):
776
1312
        self.get_branch_config('http://www.example.com-com')
777
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1313
        self.assertLocationMatching([])
778
1314
 
779
1315
    def test__get_matching_sections_subdir_recursive(self):
780
1316
        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())
 
1317
        self.assertLocationMatching([('http://www.example.com', 'com')])
783
1318
 
784
1319
    def test__get_matching_sections_ignoreparent(self):
785
1320
        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())
 
1321
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1322
                                      '')])
788
1323
 
789
1324
    def test__get_matching_sections_ignoreparent_subdir(self):
790
1325
        self.get_branch_config(
791
1326
            'http://www.example.com/ignoreparent/childbranch')
792
 
        self.assertEqual([('http://www.example.com/ignoreparent',
793
 
                           'childbranch')],
794
 
                         self.my_location_config._get_matching_sections())
 
1327
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1328
                                      'childbranch')])
795
1329
 
796
1330
    def test__get_matching_sections_subdir_trailing_slash(self):
797
1331
        self.get_branch_config('/b')
798
 
        self.assertEqual([('/b/', '')],
799
 
                         self.my_location_config._get_matching_sections())
 
1332
        self.assertLocationMatching([('/b/', '')])
800
1333
 
801
1334
    def test__get_matching_sections_subdir_child(self):
802
1335
        self.get_branch_config('/a/foo')
803
 
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
804
 
                         self.my_location_config._get_matching_sections())
 
1336
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
805
1337
 
806
1338
    def test__get_matching_sections_subdir_child_child(self):
807
1339
        self.get_branch_config('/a/foo/bar')
808
 
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
809
 
                         self.my_location_config._get_matching_sections())
 
1340
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
810
1341
 
811
1342
    def test__get_matching_sections_trailing_slash_with_children(self):
812
1343
        self.get_branch_config('/a/')
813
 
        self.assertEqual([('/a/', '')],
814
 
                         self.my_location_config._get_matching_sections())
 
1344
        self.assertLocationMatching([('/a/', '')])
815
1345
 
816
1346
    def test__get_matching_sections_explicit_over_glob(self):
817
1347
        # XXX: 2006-09-08 jamesh
819
1349
        # was a config section for '/a/?', it would get precedence
820
1350
        # over '/a/c'.
821
1351
        self.get_branch_config('/a/c')
822
 
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
823
 
                         self.my_location_config._get_matching_sections())
 
1352
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
824
1353
 
825
1354
    def test__get_option_policy_normal(self):
826
1355
        self.get_branch_config('http://www.example.com')
848
1377
            'http://www.example.com', 'appendpath_option'),
849
1378
            config.POLICY_APPENDPATH)
850
1379
 
 
1380
    def test__get_options_with_policy(self):
 
1381
        self.get_branch_config('/dir/subdir',
 
1382
                               location_config="""\
 
1383
[/dir]
 
1384
other_url = /other-dir
 
1385
other_url:policy = appendpath
 
1386
[/dir/subdir]
 
1387
other_url = /other-subdir
 
1388
""")
 
1389
        self.assertOptions(
 
1390
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
 
1391
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
 
1392
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
 
1393
            self.my_location_config)
 
1394
 
851
1395
    def test_location_without_username(self):
852
1396
        self.get_branch_config('http://www.example.com/ignoreparent')
853
1397
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
989
1533
        self.assertEqual('bzrlib.tests.test_config.post_commit',
990
1534
                         self.my_config.post_commit())
991
1535
 
992
 
    def get_branch_config(self, location, global_config=None):
 
1536
    def get_branch_config(self, location, global_config=None,
 
1537
                          location_config=None):
 
1538
        my_branch = FakeBranch(location)
993
1539
        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)
 
1540
            global_config = sample_config_text
 
1541
        if location_config is None:
 
1542
            location_config = sample_branches_text
 
1543
 
 
1544
        my_global_config = config.GlobalConfig.from_string(global_config,
 
1545
                                                           save=True)
 
1546
        my_location_config = config.LocationConfig.from_string(
 
1547
            location_config, my_branch.base, save=True)
 
1548
        my_config = config.BranchConfig(my_branch)
 
1549
        self.my_config = my_config
 
1550
        self.my_location_config = my_config._get_location_config()
1004
1551
 
1005
1552
    def test_set_user_setting_sets_and_saves(self):
1006
1553
        self.get_branch_config('/a/c')
1007
1554
        record = InstrumentedConfigObj("foo")
1008
1555
        self.my_location_config._parser = record
1009
1556
 
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'),
 
1557
        self.callDeprecated(['The recurse option is deprecated as of '
 
1558
                             '0.14.  The section "/a/c" has been '
 
1559
                             'converted to use policies.'],
 
1560
                            self.my_config.set_user_option,
 
1561
                            'foo', 'bar', store=config.STORE_LOCATION)
 
1562
        self.assertEqual([('reload',),
 
1563
                          ('__contains__', '/a/c'),
1029
1564
                          ('__contains__', '/a/c/'),
1030
1565
                          ('__setitem__', '/a/c', {}),
1031
1566
                          ('__getitem__', '/a/c'),
1060
1595
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1061
1596
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1062
1597
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1063
 
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
1598
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1064
1599
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1065
1600
 
1066
1601
 
1074
1609
option = exact
1075
1610
"""
1076
1611
 
1077
 
 
1078
1612
class TestBranchConfigItems(tests.TestCaseInTempDir):
1079
1613
 
1080
1614
    def get_branch_config(self, global_config=None, location=None,
1081
1615
                          location_config=None, branch_data_config=None):
1082
 
        my_config = config.BranchConfig(FakeBranch(location))
 
1616
        my_branch = FakeBranch(location)
1083
1617
        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()
 
1618
            my_global_config = config.GlobalConfig.from_string(global_config,
 
1619
                                                               save=True)
1087
1620
        if location_config is not None:
1088
 
            location_file = StringIO(location_config.encode('utf-8'))
1089
 
            self.my_location_config._get_parser(location_file)
 
1621
            my_location_config = config.LocationConfig.from_string(
 
1622
                location_config, my_branch.base, save=True)
 
1623
        my_config = config.BranchConfig(my_branch)
1090
1624
        if branch_data_config is not None:
1091
1625
            my_config.branch.control_files.files['branch.conf'] = \
1092
1626
                branch_data_config
1106
1640
                         my_config.username())
1107
1641
 
1108
1642
    def test_not_set_in_branch(self):
1109
 
        my_config = self.get_branch_config(sample_config_text)
 
1643
        my_config = self.get_branch_config(global_config=sample_config_text)
1110
1644
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1111
1645
                         my_config._get_user_id())
1112
1646
        my_config.branch.control_files.files['email'] = "John"
1113
1647
        self.assertEqual("John", my_config._get_user_id())
1114
1648
 
1115
1649
    def test_BZR_EMAIL_OVERRIDES(self):
1116
 
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
 
1650
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1117
1651
        branch = FakeBranch()
1118
1652
        my_config = config.BranchConfig(branch)
1119
1653
        self.assertEqual("Robert Collins <robertc@example.org>",
1136
1670
 
1137
1671
    def test_gpg_signing_command(self):
1138
1672
        my_config = self.get_branch_config(
 
1673
            global_config=sample_config_text,
1139
1674
            # branch data cannot set gpg_signing_command
1140
1675
            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
1676
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1144
1677
 
1145
1678
    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))
 
1679
        my_config = self.get_branch_config(global_config=sample_config_text)
1150
1680
        self.assertEqual('something',
1151
1681
                         my_config.get_user_option('user_global_option'))
1152
1682
 
1153
1683
    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)
 
1684
        my_config = self.get_branch_config(global_config=sample_config_text,
 
1685
                                      location='/a/c',
 
1686
                                      location_config=sample_branches_text)
1157
1687
        self.assertEqual(my_config.branch.base, '/a/c')
1158
1688
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1159
1689
                         my_config.post_commit())
1160
1690
        my_config.set_user_option('post_commit', 'rmtree_root')
1161
 
        # post-commit is ignored when bresent in branch data
 
1691
        # post-commit is ignored when present in branch data
1162
1692
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1163
1693
                         my_config.post_commit())
1164
1694
        my_config.set_user_option('post_commit', 'rmtree_root',
1166
1696
        self.assertEqual('rmtree_root', my_config.post_commit())
1167
1697
 
1168
1698
    def test_config_precedence(self):
 
1699
        # FIXME: eager test, luckily no persitent config file makes it fail
 
1700
        # -- vila 20100716
1169
1701
        my_config = self.get_branch_config(global_config=precedence_global)
1170
1702
        self.assertEqual(my_config.get_user_option('option'), 'global')
1171
1703
        my_config = self.get_branch_config(global_config=precedence_global,
1172
 
                                      branch_data_config=precedence_branch)
 
1704
                                           branch_data_config=precedence_branch)
1173
1705
        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)
 
1706
        my_config = self.get_branch_config(
 
1707
            global_config=precedence_global,
 
1708
            branch_data_config=precedence_branch,
 
1709
            location_config=precedence_location)
1177
1710
        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')
 
1711
        my_config = self.get_branch_config(
 
1712
            global_config=precedence_global,
 
1713
            branch_data_config=precedence_branch,
 
1714
            location_config=precedence_location,
 
1715
            location='http://example.com/specific')
1182
1716
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1183
1717
 
1184
1718
    def test_get_mail_client(self):
1312
1846
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1313
1847
 
1314
1848
 
 
1849
class TestSection(tests.TestCase):
 
1850
 
 
1851
    # FIXME: Parametrize so that all sections produced by Stores run these
 
1852
    # tests -- vila 2011-04-01
 
1853
 
 
1854
    def test_get_a_value(self):
 
1855
        a_dict = dict(foo='bar')
 
1856
        section = config.Section('myID', a_dict)
 
1857
        self.assertEquals('bar', section.get('foo'))
 
1858
 
 
1859
    def test_get_unknown_option(self):
 
1860
        a_dict = dict()
 
1861
        section = config.Section(None, a_dict)
 
1862
        self.assertEquals('out of thin air',
 
1863
                          section.get('foo', 'out of thin air'))
 
1864
 
 
1865
    def test_options_is_shared(self):
 
1866
        a_dict = dict()
 
1867
        section = config.Section(None, a_dict)
 
1868
        self.assertIs(a_dict, section.options)
 
1869
 
 
1870
 
 
1871
class TestMutableSection(tests.TestCase):
 
1872
 
 
1873
    # FIXME: Parametrize so that all sections (including os.environ and the
 
1874
    # ones produced by Stores) run these tests -- vila 2011-04-01
 
1875
 
 
1876
    def test_set(self):
 
1877
        a_dict = dict(foo='bar')
 
1878
        section = config.MutableSection('myID', a_dict)
 
1879
        section.set('foo', 'new_value')
 
1880
        self.assertEquals('new_value', section.get('foo'))
 
1881
        # The change appears in the shared section
 
1882
        self.assertEquals('new_value', a_dict.get('foo'))
 
1883
        # We keep track of the change
 
1884
        self.assertTrue('foo' in section.orig)
 
1885
        self.assertEquals('bar', section.orig.get('foo'))
 
1886
 
 
1887
    def test_set_preserve_original_once(self):
 
1888
        a_dict = dict(foo='bar')
 
1889
        section = config.MutableSection('myID', a_dict)
 
1890
        section.set('foo', 'first_value')
 
1891
        section.set('foo', 'second_value')
 
1892
        # We keep track of the original value
 
1893
        self.assertTrue('foo' in section.orig)
 
1894
        self.assertEquals('bar', section.orig.get('foo'))
 
1895
 
 
1896
    def test_remove(self):
 
1897
        a_dict = dict(foo='bar')
 
1898
        section = config.MutableSection('myID', a_dict)
 
1899
        section.remove('foo')
 
1900
        # We get None for unknown options via the default value
 
1901
        self.assertEquals(None, section.get('foo'))
 
1902
        # Or we just get the default value
 
1903
        self.assertEquals('unknown', section.get('foo', 'unknown'))
 
1904
        self.assertFalse('foo' in section.options)
 
1905
        # We keep track of the deletion
 
1906
        self.assertTrue('foo' in section.orig)
 
1907
        self.assertEquals('bar', section.orig.get('foo'))
 
1908
 
 
1909
    def test_remove_new_option(self):
 
1910
        a_dict = dict()
 
1911
        section = config.MutableSection('myID', a_dict)
 
1912
        section.set('foo', 'bar')
 
1913
        section.remove('foo')
 
1914
        self.assertFalse('foo' in section.options)
 
1915
        # The option didn't exist initially so it we need to keep track of it
 
1916
        # with a special value
 
1917
        self.assertTrue('foo' in section.orig)
 
1918
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
 
1919
 
 
1920
 
 
1921
class TestStore(tests.TestCaseWithTransport):
 
1922
 
 
1923
    def assertSectionContent(self, expected, section):
 
1924
        """Assert that some options have the proper values in a section."""
 
1925
        expected_name, expected_options = expected
 
1926
        self.assertEquals(expected_name, section.id)
 
1927
        self.assertEquals(
 
1928
            expected_options,
 
1929
            dict([(k, section.get(k)) for k in expected_options.keys()]))
 
1930
 
 
1931
 
 
1932
class TestReadonlyStore(TestStore):
 
1933
 
 
1934
    scenarios = [(key, {'get_store': builder})
 
1935
                 for key, builder in test_store_builder_registry.iteritems()]
 
1936
 
 
1937
    def setUp(self):
 
1938
        super(TestReadonlyStore, self).setUp()
 
1939
        self.branch = self.make_branch('branch')
 
1940
 
 
1941
    def test_building_delays_load(self):
 
1942
        store = self.get_store(self)
 
1943
        self.assertEquals(False, store.is_loaded())
 
1944
        store._load_from_string('')
 
1945
        self.assertEquals(True, store.is_loaded())
 
1946
 
 
1947
    def test_get_no_sections_for_empty(self):
 
1948
        store = self.get_store(self)
 
1949
        store._load_from_string('')
 
1950
        self.assertEquals([], list(store.get_sections()))
 
1951
 
 
1952
    def test_get_default_section(self):
 
1953
        store = self.get_store(self)
 
1954
        store._load_from_string('foo=bar')
 
1955
        sections = list(store.get_sections())
 
1956
        self.assertLength(1, sections)
 
1957
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
1958
 
 
1959
    def test_get_named_section(self):
 
1960
        store = self.get_store(self)
 
1961
        store._load_from_string('[baz]\nfoo=bar')
 
1962
        sections = list(store.get_sections())
 
1963
        self.assertLength(1, sections)
 
1964
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
1965
 
 
1966
    def test_load_from_string_fails_for_non_empty_store(self):
 
1967
        store = self.get_store(self)
 
1968
        store._load_from_string('foo=bar')
 
1969
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
 
1970
 
 
1971
 
 
1972
class TestMutableStore(TestStore):
 
1973
 
 
1974
    scenarios = [(key, {'store_id': key, 'get_store': builder})
 
1975
                 for key, builder in test_store_builder_registry.iteritems()]
 
1976
 
 
1977
    def setUp(self):
 
1978
        super(TestMutableStore, self).setUp()
 
1979
        self.transport = self.get_transport()
 
1980
        self.branch = self.make_branch('branch')
 
1981
 
 
1982
    def has_store(self, store):
 
1983
        store_basename = urlutils.relative_url(self.transport.external_url(),
 
1984
                                               store.external_url())
 
1985
        return self.transport.has(store_basename)
 
1986
 
 
1987
    def test_save_empty_creates_no_file(self):
 
1988
        if self.store_id == 'branch':
 
1989
            raise tests.TestNotApplicable(
 
1990
                'branch.conf is *always* created when a branch is initialized')
 
1991
        store = self.get_store(self)
 
1992
        store.save()
 
1993
        self.assertEquals(False, self.has_store(store))
 
1994
 
 
1995
    def test_save_emptied_succeeds(self):
 
1996
        store = self.get_store(self)
 
1997
        store._load_from_string('foo=bar\n')
 
1998
        section = store.get_mutable_section(None)
 
1999
        section.remove('foo')
 
2000
        store.save()
 
2001
        self.assertEquals(True, self.has_store(store))
 
2002
        modified_store = self.get_store(self)
 
2003
        sections = list(modified_store.get_sections())
 
2004
        self.assertLength(0, sections)
 
2005
 
 
2006
    def test_save_with_content_succeeds(self):
 
2007
        if self.store_id == 'branch':
 
2008
            raise tests.TestNotApplicable(
 
2009
                'branch.conf is *always* created when a branch is initialized')
 
2010
        store = self.get_store(self)
 
2011
        store._load_from_string('foo=bar\n')
 
2012
        self.assertEquals(False, self.has_store(store))
 
2013
        store.save()
 
2014
        self.assertEquals(True, self.has_store(store))
 
2015
        modified_store = self.get_store(self)
 
2016
        sections = list(modified_store.get_sections())
 
2017
        self.assertLength(1, sections)
 
2018
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2019
 
 
2020
    def test_set_option_in_empty_store(self):
 
2021
        store = self.get_store(self)
 
2022
        section = store.get_mutable_section(None)
 
2023
        section.set('foo', 'bar')
 
2024
        store.save()
 
2025
        modified_store = self.get_store(self)
 
2026
        sections = list(modified_store.get_sections())
 
2027
        self.assertLength(1, sections)
 
2028
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2029
 
 
2030
    def test_set_option_in_default_section(self):
 
2031
        store = self.get_store(self)
 
2032
        store._load_from_string('')
 
2033
        section = store.get_mutable_section(None)
 
2034
        section.set('foo', 'bar')
 
2035
        store.save()
 
2036
        modified_store = self.get_store(self)
 
2037
        sections = list(modified_store.get_sections())
 
2038
        self.assertLength(1, sections)
 
2039
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2040
 
 
2041
    def test_set_option_in_named_section(self):
 
2042
        store = self.get_store(self)
 
2043
        store._load_from_string('')
 
2044
        section = store.get_mutable_section('baz')
 
2045
        section.set('foo', 'bar')
 
2046
        store.save()
 
2047
        modified_store = self.get_store(self)
 
2048
        sections = list(modified_store.get_sections())
 
2049
        self.assertLength(1, sections)
 
2050
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
2051
 
 
2052
 
 
2053
class TestIniFileStore(TestStore):
 
2054
 
 
2055
    def test_loading_unknown_file_fails(self):
 
2056
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
 
2057
        self.assertRaises(errors.NoSuchFile, store.load)
 
2058
 
 
2059
    def test_invalid_content(self):
 
2060
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
2061
        self.assertEquals(False, store.is_loaded())
 
2062
        exc = self.assertRaises(
 
2063
            errors.ParseConfigError, store._load_from_string,
 
2064
            'this is invalid !')
 
2065
        self.assertEndsWith(exc.filename, 'foo.conf')
 
2066
        # And the load failed
 
2067
        self.assertEquals(False, store.is_loaded())
 
2068
 
 
2069
    def test_get_embedded_sections(self):
 
2070
        # A more complicated example (which also shows that section names and
 
2071
        # option names share the same name space...)
 
2072
        # FIXME: This should be fixed by forbidding dicts as values ?
 
2073
        # -- vila 2011-04-05
 
2074
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
2075
        store._load_from_string('''
 
2076
foo=bar
 
2077
l=1,2
 
2078
[DEFAULT]
 
2079
foo_in_DEFAULT=foo_DEFAULT
 
2080
[bar]
 
2081
foo_in_bar=barbar
 
2082
[baz]
 
2083
foo_in_baz=barbaz
 
2084
[[qux]]
 
2085
foo_in_qux=quux
 
2086
''')
 
2087
        sections = list(store.get_sections())
 
2088
        self.assertLength(4, sections)
 
2089
        # The default section has no name.
 
2090
        # List values are provided as lists
 
2091
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
 
2092
                                  sections[0])
 
2093
        self.assertSectionContent(
 
2094
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
 
2095
        self.assertSectionContent(
 
2096
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
 
2097
        # sub sections are provided as embedded dicts.
 
2098
        self.assertSectionContent(
 
2099
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
 
2100
            sections[3])
 
2101
 
 
2102
 
 
2103
class TestLockableIniFileStore(TestStore):
 
2104
 
 
2105
    def test_create_store_in_created_dir(self):
 
2106
        t = self.get_transport('dir/subdir')
 
2107
        store = config.LockableIniFileStore(t, 'foo.conf')
 
2108
        store.get_mutable_section(None).set('foo', 'bar')
 
2109
        store.save()
 
2110
 
 
2111
    # FIXME: We should adapt the tests in TestLockableConfig about concurrent
 
2112
    # writes. Since this requires a clearer rewrite, I'll just rely on using
 
2113
    # the same code in LockableIniFileStore (copied from LockableConfig, but
 
2114
    # trivial enough, the main difference is that we add @needs_write_lock on
 
2115
    # save() instead of set_user_option() and remove_user_option()). The intent
 
2116
    # is to ensure that we always get a valid content for the store even when
 
2117
    # concurrent accesses occur, read/write, write/write. It may be worth
 
2118
    # looking into removing the lock dir when it;s not needed anymore and look
 
2119
    # at possible fallouts for concurrent lockers -- vila 20110-04-06
 
2120
 
 
2121
 
 
2122
class TestSectionMatcher(TestStore):
 
2123
 
 
2124
    scenarios = [('location', {'matcher': config.LocationMatcher})]
 
2125
 
 
2126
    def get_store(self, file_name):
 
2127
        return config.IniFileStore(self.get_readonly_transport(), file_name)
 
2128
 
 
2129
    def test_no_matches_for_empty_stores(self):
 
2130
        store = self.get_store('foo.conf')
 
2131
        store._load_from_string('')
 
2132
        matcher = self.matcher(store, '/bar')
 
2133
        self.assertEquals([], list(matcher.get_sections()))
 
2134
 
 
2135
    def test_build_doesnt_load_store(self):
 
2136
        store = self.get_store('foo.conf')
 
2137
        matcher = self.matcher(store, '/bar')
 
2138
        self.assertFalse(store.is_loaded())
 
2139
 
 
2140
 
 
2141
class TestLocationSection(tests.TestCase):
 
2142
 
 
2143
    def get_section(self, options, extra_path):
 
2144
        section = config.Section('foo', options)
 
2145
        # We don't care about the length so we use '0'
 
2146
        return config.LocationSection(section, 0, extra_path)
 
2147
 
 
2148
    def test_simple_option(self):
 
2149
        section = self.get_section({'foo': 'bar'}, '')
 
2150
        self.assertEquals('bar', section.get('foo'))
 
2151
 
 
2152
    def test_option_with_extra_path(self):
 
2153
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
 
2154
                                   'baz')
 
2155
        self.assertEquals('bar/baz', section.get('foo'))
 
2156
 
 
2157
    def test_invalid_policy(self):
 
2158
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
 
2159
                                   'baz')
 
2160
        # invalid policies are ignored
 
2161
        self.assertEquals('bar', section.get('foo'))
 
2162
 
 
2163
 
 
2164
class TestLocationMatcher(TestStore):
 
2165
 
 
2166
    def get_store(self, file_name):
 
2167
        return config.IniFileStore(self.get_readonly_transport(), file_name)
 
2168
 
 
2169
    def test_more_specific_sections_first(self):
 
2170
        store = self.get_store('foo.conf')
 
2171
        store._load_from_string('''
 
2172
[/foo]
 
2173
section=/foo
 
2174
[/foo/bar]
 
2175
section=/foo/bar
 
2176
''')
 
2177
        self.assertEquals(['/foo', '/foo/bar'],
 
2178
                          [section.id for section in store.get_sections()])
 
2179
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
 
2180
        sections = list(matcher.get_sections())
 
2181
        self.assertEquals([3, 2],
 
2182
                          [section.length for section in sections])
 
2183
        self.assertEquals(['/foo/bar', '/foo'],
 
2184
                          [section.id for section in sections])
 
2185
        self.assertEquals(['baz', 'bar/baz'],
 
2186
                          [section.extra_path for section in sections])
 
2187
 
 
2188
    def test_appendpath_in_no_name_section(self):
 
2189
        # It's a bit weird to allow appendpath in a no-name section, but
 
2190
        # someone may found a use for it
 
2191
        store = self.get_store('foo.conf')
 
2192
        store._load_from_string('''
 
2193
foo=bar
 
2194
foo:policy = appendpath
 
2195
''')
 
2196
        matcher = config.LocationMatcher(store, 'dir/subdir')
 
2197
        sections = list(matcher.get_sections())
 
2198
        self.assertLength(1, sections)
 
2199
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
 
2200
 
 
2201
    def test_file_urls_are_normalized(self):
 
2202
        store = self.get_store('foo.conf')
 
2203
        matcher = config.LocationMatcher(store, 'file:///dir/subdir')
 
2204
        self.assertEquals('/dir/subdir', matcher.location)
 
2205
 
 
2206
 
 
2207
class TestStackGet(tests.TestCase):
 
2208
 
 
2209
    # FIXME: This should be parametrized for all known Stack or dedicated
 
2210
    # paramerized tests created to avoid bloating -- vila 2011-03-31
 
2211
 
 
2212
    def test_single_config_get(self):
 
2213
        conf = dict(foo='bar')
 
2214
        conf_stack = config.Stack([conf])
 
2215
        self.assertEquals('bar', conf_stack.get('foo'))
 
2216
 
 
2217
    def test_get_first_definition(self):
 
2218
        conf1 = dict(foo='bar')
 
2219
        conf2 = dict(foo='baz')
 
2220
        conf_stack = config.Stack([conf1, conf2])
 
2221
        self.assertEquals('bar', conf_stack.get('foo'))
 
2222
 
 
2223
    def test_get_embedded_definition(self):
 
2224
        conf1 = dict(yy='12')
 
2225
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
 
2226
        conf_stack = config.Stack([conf1, conf2])
 
2227
        self.assertEquals('baz', conf_stack.get('foo'))
 
2228
 
 
2229
    def test_get_for_empty_stack(self):
 
2230
        conf_stack = config.Stack([])
 
2231
        self.assertEquals(None, conf_stack.get('foo'))
 
2232
 
 
2233
    def test_get_for_empty_section_callable(self):
 
2234
        conf_stack = config.Stack([lambda : []])
 
2235
        self.assertEquals(None, conf_stack.get('foo'))
 
2236
 
 
2237
    def test_get_for_broken_callable(self):
 
2238
        # Trying to use and invalid callable raises an exception on first use
 
2239
        conf_stack = config.Stack([lambda : object()])
 
2240
        self.assertRaises(TypeError, conf_stack.get, 'foo')
 
2241
 
 
2242
 
 
2243
class TestStackWithTransport(tests.TestCaseWithTransport):
 
2244
 
 
2245
    def setUp(self):
 
2246
        super(TestStackWithTransport, self).setUp()
 
2247
        # FIXME: A more elaborate builder for the stack would avoid building a
 
2248
        # branch even for tests that don't need it.
 
2249
        self.branch = self.make_branch('branch')
 
2250
 
 
2251
 
 
2252
class TestStackSet(TestStackWithTransport):
 
2253
 
 
2254
    scenarios = [(key, {'get_stack': builder})
 
2255
                 for key, builder in test_stack_builder_registry.iteritems()]
 
2256
 
 
2257
    def test_simple_set(self):
 
2258
        conf = self.get_stack(self)
 
2259
        conf.store._load_from_string('foo=bar')
 
2260
        self.assertEquals('bar', conf.get('foo'))
 
2261
        conf.set('foo', 'baz')
 
2262
        # Did we get it back ?
 
2263
        self.assertEquals('baz', conf.get('foo'))
 
2264
 
 
2265
    def test_set_creates_a_new_section(self):
 
2266
        conf = self.get_stack(self)
 
2267
        conf.set('foo', 'baz')
 
2268
        self.assertEquals, 'baz', conf.get('foo')
 
2269
 
 
2270
 
 
2271
class TestStackRemove(TestStackWithTransport):
 
2272
 
 
2273
    scenarios = [(key, {'get_stack': builder})
 
2274
                 for key, builder in test_stack_builder_registry.iteritems()]
 
2275
 
 
2276
    def test_remove_existing(self):
 
2277
        conf = self.get_stack(self)
 
2278
        conf.store._load_from_string('foo=bar')
 
2279
        self.assertEquals('bar', conf.get('foo'))
 
2280
        conf.remove('foo')
 
2281
        # Did we get it back ?
 
2282
        self.assertEquals(None, conf.get('foo'))
 
2283
 
 
2284
    def test_remove_unknown(self):
 
2285
        conf = self.get_stack(self)
 
2286
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
 
2287
 
 
2288
 
 
2289
class TestConcreteStacks(TestStackWithTransport):
 
2290
 
 
2291
    scenarios = [(key, {'get_stack': builder})
 
2292
                 for key, builder in test_stack_builder_registry.iteritems()]
 
2293
 
 
2294
    def test_build_stack(self):
 
2295
        stack = self.get_stack(self)
 
2296
 
 
2297
 
 
2298
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
 
2299
 
 
2300
    def setUp(self):
 
2301
        super(TestConfigGetOptions, self).setUp()
 
2302
        create_configs(self)
 
2303
 
 
2304
    def test_no_variable(self):
 
2305
        # Using branch should query branch, locations and bazaar
 
2306
        self.assertOptions([], self.branch_config)
 
2307
 
 
2308
    def test_option_in_bazaar(self):
 
2309
        self.bazaar_config.set_user_option('file', 'bazaar')
 
2310
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
 
2311
                           self.bazaar_config)
 
2312
 
 
2313
    def test_option_in_locations(self):
 
2314
        self.locations_config.set_user_option('file', 'locations')
 
2315
        self.assertOptions(
 
2316
            [('file', 'locations', self.tree.basedir, 'locations')],
 
2317
            self.locations_config)
 
2318
 
 
2319
    def test_option_in_branch(self):
 
2320
        self.branch_config.set_user_option('file', 'branch')
 
2321
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
 
2322
                           self.branch_config)
 
2323
 
 
2324
    def test_option_in_bazaar_and_branch(self):
 
2325
        self.bazaar_config.set_user_option('file', 'bazaar')
 
2326
        self.branch_config.set_user_option('file', 'branch')
 
2327
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
 
2328
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2329
                           self.branch_config)
 
2330
 
 
2331
    def test_option_in_branch_and_locations(self):
 
2332
        # Hmm, locations override branch :-/
 
2333
        self.locations_config.set_user_option('file', 'locations')
 
2334
        self.branch_config.set_user_option('file', 'branch')
 
2335
        self.assertOptions(
 
2336
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2337
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
2338
            self.branch_config)
 
2339
 
 
2340
    def test_option_in_bazaar_locations_and_branch(self):
 
2341
        self.bazaar_config.set_user_option('file', 'bazaar')
 
2342
        self.locations_config.set_user_option('file', 'locations')
 
2343
        self.branch_config.set_user_option('file', 'branch')
 
2344
        self.assertOptions(
 
2345
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2346
             ('file', 'branch', 'DEFAULT', 'branch'),
 
2347
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2348
            self.branch_config)
 
2349
 
 
2350
 
 
2351
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
 
2352
 
 
2353
    def setUp(self):
 
2354
        super(TestConfigRemoveOption, self).setUp()
 
2355
        create_configs_with_file_option(self)
 
2356
 
 
2357
    def test_remove_in_locations(self):
 
2358
        self.locations_config.remove_user_option('file', self.tree.basedir)
 
2359
        self.assertOptions(
 
2360
            [('file', 'branch', 'DEFAULT', 'branch'),
 
2361
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2362
            self.branch_config)
 
2363
 
 
2364
    def test_remove_in_branch(self):
 
2365
        self.branch_config.remove_user_option('file')
 
2366
        self.assertOptions(
 
2367
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2368
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2369
            self.branch_config)
 
2370
 
 
2371
    def test_remove_in_bazaar(self):
 
2372
        self.bazaar_config.remove_user_option('file')
 
2373
        self.assertOptions(
 
2374
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2375
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
2376
            self.branch_config)
 
2377
 
 
2378
 
 
2379
class TestConfigGetSections(tests.TestCaseWithTransport):
 
2380
 
 
2381
    def setUp(self):
 
2382
        super(TestConfigGetSections, self).setUp()
 
2383
        create_configs(self)
 
2384
 
 
2385
    def assertSectionNames(self, expected, conf, name=None):
 
2386
        """Check which sections are returned for a given config.
 
2387
 
 
2388
        If fallback configurations exist their sections can be included.
 
2389
 
 
2390
        :param expected: A list of section names.
 
2391
 
 
2392
        :param conf: The configuration that will be queried.
 
2393
 
 
2394
        :param name: An optional section name that will be passed to
 
2395
            get_sections().
 
2396
        """
 
2397
        sections = list(conf._get_sections(name))
 
2398
        self.assertLength(len(expected), sections)
 
2399
        self.assertEqual(expected, [name for name, _, _ in sections])
 
2400
 
 
2401
    def test_bazaar_default_section(self):
 
2402
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
 
2403
 
 
2404
    def test_locations_default_section(self):
 
2405
        # No sections are defined in an empty file
 
2406
        self.assertSectionNames([], self.locations_config)
 
2407
 
 
2408
    def test_locations_named_section(self):
 
2409
        self.locations_config.set_user_option('file', 'locations')
 
2410
        self.assertSectionNames([self.tree.basedir], self.locations_config)
 
2411
 
 
2412
    def test_locations_matching_sections(self):
 
2413
        loc_config = self.locations_config
 
2414
        loc_config.set_user_option('file', 'locations')
 
2415
        # We need to cheat a bit here to create an option in sections above and
 
2416
        # below the 'location' one.
 
2417
        parser = loc_config._get_parser()
 
2418
        # locations.cong deals with '/' ignoring native os.sep
 
2419
        location_names = self.tree.basedir.split('/')
 
2420
        parent = '/'.join(location_names[:-1])
 
2421
        child = '/'.join(location_names + ['child'])
 
2422
        parser[parent] = {}
 
2423
        parser[parent]['file'] = 'parent'
 
2424
        parser[child] = {}
 
2425
        parser[child]['file'] = 'child'
 
2426
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
 
2427
 
 
2428
    def test_branch_data_default_section(self):
 
2429
        self.assertSectionNames([None],
 
2430
                                self.branch_config._get_branch_data_config())
 
2431
 
 
2432
    def test_branch_default_sections(self):
 
2433
        # No sections are defined in an empty locations file
 
2434
        self.assertSectionNames([None, 'DEFAULT'],
 
2435
                                self.branch_config)
 
2436
        # Unless we define an option
 
2437
        self.branch_config._get_location_config().set_user_option(
 
2438
            'file', 'locations')
 
2439
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
 
2440
                                self.branch_config)
 
2441
 
 
2442
    def test_bazaar_named_section(self):
 
2443
        # We need to cheat as the API doesn't give direct access to sections
 
2444
        # other than DEFAULT.
 
2445
        self.bazaar_config.set_alias('bazaar', 'bzr')
 
2446
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
 
2447
 
 
2448
 
1315
2449
class TestAuthenticationConfigFile(tests.TestCase):
1316
2450
    """Test the authentication.conf file matching"""
1317
2451
 
1812
2946
# test_user_prompted ?
1813
2947
class TestAuthenticationRing(tests.TestCaseWithTransport):
1814
2948
    pass
 
2949
 
 
2950
 
 
2951
class TestAutoUserId(tests.TestCase):
 
2952
    """Test inferring an automatic user name."""
 
2953
 
 
2954
    def test_auto_user_id(self):
 
2955
        """Automatic inference of user name.
 
2956
        
 
2957
        This is a bit hard to test in an isolated way, because it depends on
 
2958
        system functions that go direct to /etc or perhaps somewhere else.
 
2959
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
 
2960
        to be able to choose a user name with no configuration.
 
2961
        """
 
2962
        if sys.platform == 'win32':
 
2963
            raise TestSkipped("User name inference not implemented on win32")
 
2964
        realname, address = config._auto_user_id()
 
2965
        if os.path.exists('/etc/mailname'):
 
2966
            self.assertIsNot(None, realname)
 
2967
            self.assertIsNot(None, address)
 
2968
        else:
 
2969
            self.assertEquals((None, None), (realname, address))
 
2970