/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-03-11 15:34:14 UTC
  • mto: This revision was merged to the branch mainline in revision 5718.
  • Revision ID: jelmer@samba.org-20110311153414-i7vjkje5p8s2ozo9
Move more weave code.

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,
34
39
    tests,
35
40
    trace,
36
41
    transport,
37
42
    )
 
43
from bzrlib.tests import (
 
44
    features,
 
45
    scenarios,
 
46
    )
38
47
from bzrlib.util.configobj import configobj
39
48
 
40
49
 
 
50
def lockable_config_scenarios():
 
51
    return [
 
52
        ('global',
 
53
         {'config_class': config.GlobalConfig,
 
54
          'config_args': [],
 
55
          'config_section': 'DEFAULT'}),
 
56
        ('locations',
 
57
         {'config_class': config.LocationConfig,
 
58
          'config_args': ['.'],
 
59
          'config_section': '.'}),]
 
60
 
 
61
 
 
62
load_tests = scenarios.load_tests_apply_scenarios
 
63
 
 
64
 
41
65
sample_long_alias="log -r-15..-1 --line"
42
66
sample_config_text = u"""
43
67
[DEFAULT]
47
71
gpg_signing_command=gnome-gpg
48
72
log_format=short
49
73
user_global_option=something
 
74
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
 
75
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
 
76
bzr.default_mergetool=sometool
50
77
[ALIASES]
51
78
h=help
52
79
ll=""" + sample_long_alias + "\n"
105
132
"""
106
133
 
107
134
 
 
135
def create_configs(test):
 
136
    """Create configuration files for a given test.
 
137
 
 
138
    This requires creating a tree (and populate the ``test.tree`` attribute)
 
139
    and its associated branch and will populate the following attributes:
 
140
 
 
141
    - branch_config: A BranchConfig for the associated branch.
 
142
 
 
143
    - locations_config : A LocationConfig for the associated branch
 
144
 
 
145
    - bazaar_config: A GlobalConfig.
 
146
 
 
147
    The tree and branch are created in a 'tree' subdirectory so the tests can
 
148
    still use the test directory to stay outside of the branch.
 
149
    """
 
150
    tree = test.make_branch_and_tree('tree')
 
151
    test.tree = tree
 
152
    test.branch_config = config.BranchConfig(tree.branch)
 
153
    test.locations_config = config.LocationConfig(tree.basedir)
 
154
    test.bazaar_config = config.GlobalConfig()
 
155
 
 
156
 
 
157
def create_configs_with_file_option(test):
 
158
    """Create configuration files with a ``file`` option set in each.
 
159
 
 
160
    This builds on ``create_configs`` and add one ``file`` option in each
 
161
    configuration with a value which allows identifying the configuration file.
 
162
    """
 
163
    create_configs(test)
 
164
    test.bazaar_config.set_user_option('file', 'bazaar')
 
165
    test.locations_config.set_user_option('file', 'locations')
 
166
    test.branch_config.set_user_option('file', 'branch')
 
167
 
 
168
 
 
169
class TestOptionsMixin:
 
170
 
 
171
    def assertOptions(self, expected, conf):
 
172
        # We don't care about the parser (as it will make tests hard to write
 
173
        # and error-prone anyway)
 
174
        self.assertThat([opt[:4] for opt in conf._get_options()],
 
175
                        matchers.Equals(expected))
 
176
 
 
177
 
108
178
class InstrumentedConfigObj(object):
109
179
    """A config obj look-enough-alike to record calls made to it."""
110
180
 
129
199
        self._calls.append(('keys',))
130
200
        return []
131
201
 
 
202
    def reload(self):
 
203
        self._calls.append(('reload',))
 
204
 
132
205
    def write(self, arg):
133
206
        self._calls.append(('write',))
134
207
 
240
313
        """
241
314
        co = config.ConfigObj()
242
315
        co['test'] = 'foo#bar'
243
 
        lines = co.write()
 
316
        outfile = StringIO()
 
317
        co.write(outfile=outfile)
 
318
        lines = outfile.getvalue().splitlines()
244
319
        self.assertEqual(lines, ['test = "foo#bar"'])
245
320
        co2 = config.ConfigObj(lines)
246
321
        self.assertEqual(co2['test'], 'foo#bar')
247
322
 
 
323
    def test_triple_quotes(self):
 
324
        # Bug #710410: if the value string has triple quotes
 
325
        # then ConfigObj versions up to 4.7.2 will quote them wrong
 
326
        # and won't able to read them back
 
327
        triple_quotes_value = '''spam
 
328
""" that's my spam """
 
329
eggs'''
 
330
        co = config.ConfigObj()
 
331
        co['test'] = triple_quotes_value
 
332
        # While writing this test another bug in ConfigObj has been found:
 
333
        # method co.write() without arguments produces list of lines
 
334
        # one option per line, and multiline values are not split
 
335
        # across multiple lines,
 
336
        # and that breaks the parsing these lines back by ConfigObj.
 
337
        # This issue only affects test, but it's better to avoid
 
338
        # `co.write()` construct at all.
 
339
        # [bialix 20110222] bug report sent to ConfigObj's author
 
340
        outfile = StringIO()
 
341
        co.write(outfile=outfile)
 
342
        output = outfile.getvalue()
 
343
        # now we're trying to read it back
 
344
        co2 = config.ConfigObj(StringIO(output))
 
345
        self.assertEquals(triple_quotes_value, co2['test'])
 
346
 
248
347
 
249
348
erroneous_config = """[section] # line 1
250
349
good=good # line 2
333
432
 
334
433
    def setUp(self):
335
434
        super(TestConfigPath, self).setUp()
336
 
        os.environ['HOME'] = '/home/bogus'
337
 
        os.environ['XDG_CACHE_DIR'] = ''
 
435
        self.overrideEnv('HOME', '/home/bogus')
 
436
        self.overrideEnv('XDG_CACHE_DIR', '')
338
437
        if sys.platform == 'win32':
339
 
            os.environ['BZR_HOME'] = \
340
 
                r'C:\Documents and Settings\bogus\Application Data'
 
438
            self.overrideEnv(
 
439
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
341
440
            self.bzr_home = \
342
441
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
343
442
        else:
350
449
        self.assertEqual(config.config_filename(),
351
450
                         self.bzr_home + '/bazaar.conf')
352
451
 
353
 
    def test_branches_config_filename(self):
354
 
        self.assertEqual(config.branches_config_filename(),
355
 
                         self.bzr_home + '/branches.conf')
356
 
 
357
452
    def test_locations_config_filename(self):
358
453
        self.assertEqual(config.locations_config_filename(),
359
454
                         self.bzr_home + '/locations.conf')
367
462
            '/home/bogus/.cache')
368
463
 
369
464
 
370
 
class TestIniConfig(tests.TestCase):
 
465
class TestXDGConfigDir(tests.TestCaseInTempDir):
 
466
    # must be in temp dir because config tests for the existence of the bazaar
 
467
    # subdirectory of $XDG_CONFIG_HOME
 
468
 
 
469
    def setUp(self):
 
470
        if sys.platform in ('darwin', 'win32'):
 
471
            raise tests.TestNotApplicable(
 
472
                'XDG config dir not used on this platform')
 
473
        super(TestXDGConfigDir, self).setUp()
 
474
        self.overrideEnv('HOME', self.test_home_dir)
 
475
        # BZR_HOME overrides everything we want to test so unset it.
 
476
        self.overrideEnv('BZR_HOME', None)
 
477
 
 
478
    def test_xdg_config_dir_exists(self):
 
479
        """When ~/.config/bazaar exists, use it as the config dir."""
 
480
        newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
 
481
        os.makedirs(newdir)
 
482
        self.assertEqual(config.config_dir(), newdir)
 
483
 
 
484
    def test_xdg_config_home(self):
 
485
        """When XDG_CONFIG_HOME is set, use it."""
 
486
        xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
 
487
        self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
 
488
        newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
 
489
        os.makedirs(newdir)
 
490
        self.assertEqual(config.config_dir(), newdir)
 
491
 
 
492
 
 
493
class TestIniConfig(tests.TestCaseInTempDir):
371
494
 
372
495
    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
 
496
        conf = config.IniBasedConfig.from_string(s)
 
497
        return conf, conf._get_parser()
376
498
 
377
499
 
378
500
class TestIniConfigBuilding(TestIniConfig):
379
501
 
380
502
    def test_contructs(self):
381
 
        my_config = config.IniBasedConfig("nothing")
 
503
        my_config = config.IniBasedConfig()
382
504
 
383
505
    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))
 
506
        my_config = config.IniBasedConfig.from_string(sample_config_text)
 
507
        self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
389
508
 
390
509
    def test_cached(self):
391
 
        config_file = StringIO(sample_config_text.encode('utf-8'))
392
 
        my_config = config.IniBasedConfig(None)
393
 
        parser = my_config._get_parser(file=config_file)
 
510
        my_config = config.IniBasedConfig.from_string(sample_config_text)
 
511
        parser = my_config._get_parser()
394
512
        self.failUnless(my_config._get_parser() is parser)
395
513
 
 
514
    def _dummy_chown(self, path, uid, gid):
 
515
        self.path, self.uid, self.gid = path, uid, gid
 
516
 
 
517
    def test_ini_config_ownership(self):
 
518
        """Ensure that chown is happening during _write_config_file"""
 
519
        self.requireFeature(features.chown_feature)
 
520
        self.overrideAttr(os, 'chown', self._dummy_chown)
 
521
        self.path = self.uid = self.gid = None
 
522
        conf = config.IniBasedConfig(file_name='./foo.conf')
 
523
        conf._write_config_file()
 
524
        self.assertEquals(self.path, './foo.conf')
 
525
        self.assertTrue(isinstance(self.uid, int))
 
526
        self.assertTrue(isinstance(self.gid, int))
 
527
 
 
528
    def test_get_filename_parameter_is_deprecated_(self):
 
529
        conf = self.callDeprecated([
 
530
            'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
 
531
            ' Use file_name instead.'],
 
532
            config.IniBasedConfig, lambda: 'ini.conf')
 
533
        self.assertEqual('ini.conf', conf.file_name)
 
534
 
 
535
    def test_get_parser_file_parameter_is_deprecated_(self):
 
536
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
537
        conf = config.IniBasedConfig.from_string(sample_config_text)
 
538
        conf = self.callDeprecated([
 
539
            'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
 
540
            ' Use IniBasedConfig(_content=xxx) instead.'],
 
541
            conf._get_parser, file=config_file)
 
542
 
 
543
 
 
544
class TestIniConfigSaving(tests.TestCaseInTempDir):
 
545
 
 
546
    def test_cant_save_without_a_file_name(self):
 
547
        conf = config.IniBasedConfig()
 
548
        self.assertRaises(AssertionError, conf._write_config_file)
 
549
 
 
550
    def test_saved_with_content(self):
 
551
        content = 'foo = bar\n'
 
552
        conf = config.IniBasedConfig.from_string(
 
553
            content, file_name='./test.conf', save=True)
 
554
        self.assertFileEqual(content, 'test.conf')
 
555
 
 
556
 
 
557
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
 
558
    """What is the default value of expand for config options.
 
559
 
 
560
    This is an opt-in beta feature used to evaluate whether or not option
 
561
    references can appear in dangerous place raising exceptions, disapearing
 
562
    (and as such corrupting data) or if it's safe to activate the option by
 
563
    default.
 
564
 
 
565
    Note that these tests relies on config._expand_default_value being already
 
566
    overwritten in the parent class setUp.
 
567
    """
 
568
 
 
569
    def setUp(self):
 
570
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
 
571
        self.config = None
 
572
        self.warnings = []
 
573
        def warning(*args):
 
574
            self.warnings.append(args[0] % args[1:])
 
575
        self.overrideAttr(trace, 'warning', warning)
 
576
 
 
577
    def get_config(self, expand):
 
578
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
 
579
                                            save=True)
 
580
        return c
 
581
 
 
582
    def assertExpandIs(self, expected):
 
583
        actual = config._get_expand_default_value()
 
584
        #self.config.get_user_option_as_bool('bzr.config.expand')
 
585
        self.assertEquals(expected, actual)
 
586
 
 
587
    def test_default_is_None(self):
 
588
        self.assertEquals(None, config._expand_default_value)
 
589
 
 
590
    def test_default_is_False_even_if_None(self):
 
591
        self.config = self.get_config(None)
 
592
        self.assertExpandIs(False)
 
593
 
 
594
    def test_default_is_False_even_if_invalid(self):
 
595
        self.config = self.get_config('<your choice>')
 
596
        self.assertExpandIs(False)
 
597
        # ...
 
598
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
 
599
        # Wait, you've been warned !
 
600
        self.assertLength(1, self.warnings)
 
601
        self.assertEquals(
 
602
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
 
603
            self.warnings[0])
 
604
 
 
605
    def test_default_is_True(self):
 
606
        self.config = self.get_config(True)
 
607
        self.assertExpandIs(True)
 
608
        
 
609
    def test_default_is_False(self):
 
610
        self.config = self.get_config(False)
 
611
        self.assertExpandIs(False)
 
612
        
 
613
 
 
614
class TestIniConfigOptionExpansion(tests.TestCase):
 
615
    """Test option expansion from the IniConfig level.
 
616
 
 
617
    What we really want here is to test the Config level, but the class being
 
618
    abstract as far as storing values is concerned, this can't be done
 
619
    properly (yet).
 
620
    """
 
621
    # FIXME: This should be rewritten when all configs share a storage
 
622
    # implementation -- vila 2011-02-18
 
623
 
 
624
    def get_config(self, string=None):
 
625
        if string is None:
 
626
            string = ''
 
627
        c = config.IniBasedConfig.from_string(string)
 
628
        return c
 
629
 
 
630
    def assertExpansion(self, expected, conf, string, env=None):
 
631
        self.assertEquals(expected, conf.expand_options(string, env))
 
632
 
 
633
    def test_no_expansion(self):
 
634
        c = self.get_config('')
 
635
        self.assertExpansion('foo', c, 'foo')
 
636
 
 
637
    def test_env_adding_options(self):
 
638
        c = self.get_config('')
 
639
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
640
 
 
641
    def test_env_overriding_options(self):
 
642
        c = self.get_config('foo=baz')
 
643
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
644
 
 
645
    def test_simple_ref(self):
 
646
        c = self.get_config('foo=xxx')
 
647
        self.assertExpansion('xxx', c, '{foo}')
 
648
 
 
649
    def test_unknown_ref(self):
 
650
        c = self.get_config('')
 
651
        self.assertRaises(errors.ExpandingUnknownOption,
 
652
                          c.expand_options, '{foo}')
 
653
 
 
654
    def test_indirect_ref(self):
 
655
        c = self.get_config('''
 
656
foo=xxx
 
657
bar={foo}
 
658
''')
 
659
        self.assertExpansion('xxx', c, '{bar}')
 
660
 
 
661
    def test_embedded_ref(self):
 
662
        c = self.get_config('''
 
663
foo=xxx
 
664
bar=foo
 
665
''')
 
666
        self.assertExpansion('xxx', c, '{{bar}}')
 
667
 
 
668
    def test_simple_loop(self):
 
669
        c = self.get_config('foo={foo}')
 
670
        self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
 
671
 
 
672
    def test_indirect_loop(self):
 
673
        c = self.get_config('''
 
674
foo={bar}
 
675
bar={baz}
 
676
baz={foo}''')
 
677
        e = self.assertRaises(errors.OptionExpansionLoop,
 
678
                              c.expand_options, '{foo}')
 
679
        self.assertEquals('foo->bar->baz', e.refs)
 
680
        self.assertEquals('{foo}', e.string)
 
681
 
 
682
    def test_list(self):
 
683
        conf = self.get_config('''
 
684
foo=start
 
685
bar=middle
 
686
baz=end
 
687
list={foo},{bar},{baz}
 
688
''')
 
689
        self.assertEquals(['start', 'middle', 'end'],
 
690
                           conf.get_user_option('list', expand=True))
 
691
 
 
692
    def test_cascading_list(self):
 
693
        conf = self.get_config('''
 
694
foo=start,{bar}
 
695
bar=middle,{baz}
 
696
baz=end
 
697
list={foo}
 
698
''')
 
699
        self.assertEquals(['start', 'middle', 'end'],
 
700
                           conf.get_user_option('list', expand=True))
 
701
 
 
702
    def test_pathological_hidden_list(self):
 
703
        conf = self.get_config('''
 
704
foo=bin
 
705
bar=go
 
706
start={foo
 
707
middle=},{
 
708
end=bar}
 
709
hidden={start}{middle}{end}
 
710
''')
 
711
        # Nope, it's either a string or a list, and the list wins as soon as a
 
712
        # ',' appears, so the string concatenation never occur.
 
713
        self.assertEquals(['{foo', '}', '{', 'bar}'],
 
714
                          conf.get_user_option('hidden', expand=True))
 
715
 
 
716
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
 
717
 
 
718
    def get_config(self, location, string=None):
 
719
        if string is None:
 
720
            string = ''
 
721
        # Since we don't save the config we won't strictly require to inherit
 
722
        # from TestCaseInTempDir, but an error occurs so quickly...
 
723
        c = config.LocationConfig.from_string(string, location)
 
724
        return c
 
725
 
 
726
    def test_dont_cross_unrelated_section(self):
 
727
        c = self.get_config('/another/branch/path','''
 
728
[/one/branch/path]
 
729
foo = hello
 
730
bar = {foo}/2
 
731
 
 
732
[/another/branch/path]
 
733
bar = {foo}/2
 
734
''')
 
735
        self.assertRaises(errors.ExpandingUnknownOption,
 
736
                          c.get_user_option, 'bar', expand=True)
 
737
 
 
738
    def test_cross_related_sections(self):
 
739
        c = self.get_config('/project/branch/path','''
 
740
[/project]
 
741
foo = qu
 
742
 
 
743
[/project/branch/path]
 
744
bar = {foo}ux
 
745
''')
 
746
        self.assertEquals('quux', c.get_user_option('bar', expand=True))
 
747
 
 
748
 
 
749
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
 
750
 
 
751
    def test_cannot_reload_without_name(self):
 
752
        conf = config.IniBasedConfig.from_string(sample_config_text)
 
753
        self.assertRaises(AssertionError, conf.reload)
 
754
 
 
755
    def test_reload_see_new_value(self):
 
756
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
 
757
                                               file_name='./test/conf')
 
758
        c1._write_config_file()
 
759
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
 
760
                                               file_name='./test/conf')
 
761
        c2._write_config_file()
 
762
        self.assertEqual('vim', c1.get_user_option('editor'))
 
763
        self.assertEqual('emacs', c2.get_user_option('editor'))
 
764
        # Make sure we get the Right value
 
765
        c1.reload()
 
766
        self.assertEqual('emacs', c1.get_user_option('editor'))
 
767
 
 
768
 
 
769
class TestLockableConfig(tests.TestCaseInTempDir):
 
770
 
 
771
    scenarios = lockable_config_scenarios()
 
772
 
 
773
    # Set by load_tests
 
774
    config_class = None
 
775
    config_args = None
 
776
    config_section = None
 
777
 
 
778
    def setUp(self):
 
779
        super(TestLockableConfig, self).setUp()
 
780
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
 
781
        self.config = self.create_config(self._content)
 
782
 
 
783
    def get_existing_config(self):
 
784
        return self.config_class(*self.config_args)
 
785
 
 
786
    def create_config(self, content):
 
787
        kwargs = dict(save=True)
 
788
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
 
789
        return c
 
790
 
 
791
    def test_simple_read_access(self):
 
792
        self.assertEquals('1', self.config.get_user_option('one'))
 
793
 
 
794
    def test_simple_write_access(self):
 
795
        self.config.set_user_option('one', 'one')
 
796
        self.assertEquals('one', self.config.get_user_option('one'))
 
797
 
 
798
    def test_listen_to_the_last_speaker(self):
 
799
        c1 = self.config
 
800
        c2 = self.get_existing_config()
 
801
        c1.set_user_option('one', 'ONE')
 
802
        c2.set_user_option('two', 'TWO')
 
803
        self.assertEquals('ONE', c1.get_user_option('one'))
 
804
        self.assertEquals('TWO', c2.get_user_option('two'))
 
805
        # The second update respect the first one
 
806
        self.assertEquals('ONE', c2.get_user_option('one'))
 
807
 
 
808
    def test_last_speaker_wins(self):
 
809
        # If the same config is not shared, the same variable modified twice
 
810
        # can only see a single result.
 
811
        c1 = self.config
 
812
        c2 = self.get_existing_config()
 
813
        c1.set_user_option('one', 'c1')
 
814
        c2.set_user_option('one', 'c2')
 
815
        self.assertEquals('c2', c2._get_user_option('one'))
 
816
        # The first modification is still available until another refresh
 
817
        # occur
 
818
        self.assertEquals('c1', c1._get_user_option('one'))
 
819
        c1.set_user_option('two', 'done')
 
820
        self.assertEquals('c2', c1._get_user_option('one'))
 
821
 
 
822
    def test_writes_are_serialized(self):
 
823
        c1 = self.config
 
824
        c2 = self.get_existing_config()
 
825
 
 
826
        # We spawn a thread that will pause *during* the write
 
827
        before_writing = threading.Event()
 
828
        after_writing = threading.Event()
 
829
        writing_done = threading.Event()
 
830
        c1_orig = c1._write_config_file
 
831
        def c1_write_config_file():
 
832
            before_writing.set()
 
833
            c1_orig()
 
834
            # The lock is held we wait for the main thread to decide when to
 
835
            # continue
 
836
            after_writing.wait()
 
837
        c1._write_config_file = c1_write_config_file
 
838
        def c1_set_option():
 
839
            c1.set_user_option('one', 'c1')
 
840
            writing_done.set()
 
841
        t1 = threading.Thread(target=c1_set_option)
 
842
        # Collect the thread after the test
 
843
        self.addCleanup(t1.join)
 
844
        # Be ready to unblock the thread if the test goes wrong
 
845
        self.addCleanup(after_writing.set)
 
846
        t1.start()
 
847
        before_writing.wait()
 
848
        self.assertTrue(c1._lock.is_held)
 
849
        self.assertRaises(errors.LockContention,
 
850
                          c2.set_user_option, 'one', 'c2')
 
851
        self.assertEquals('c1', c1.get_user_option('one'))
 
852
        # Let the lock be released
 
853
        after_writing.set()
 
854
        writing_done.wait()
 
855
        c2.set_user_option('one', 'c2')
 
856
        self.assertEquals('c2', c2.get_user_option('one'))
 
857
 
 
858
    def test_read_while_writing(self):
 
859
       c1 = self.config
 
860
       # We spawn a thread that will pause *during* the write
 
861
       ready_to_write = threading.Event()
 
862
       do_writing = threading.Event()
 
863
       writing_done = threading.Event()
 
864
       c1_orig = c1._write_config_file
 
865
       def c1_write_config_file():
 
866
           ready_to_write.set()
 
867
           # The lock is held we wait for the main thread to decide when to
 
868
           # continue
 
869
           do_writing.wait()
 
870
           c1_orig()
 
871
           writing_done.set()
 
872
       c1._write_config_file = c1_write_config_file
 
873
       def c1_set_option():
 
874
           c1.set_user_option('one', 'c1')
 
875
       t1 = threading.Thread(target=c1_set_option)
 
876
       # Collect the thread after the test
 
877
       self.addCleanup(t1.join)
 
878
       # Be ready to unblock the thread if the test goes wrong
 
879
       self.addCleanup(do_writing.set)
 
880
       t1.start()
 
881
       # Ensure the thread is ready to write
 
882
       ready_to_write.wait()
 
883
       self.assertTrue(c1._lock.is_held)
 
884
       self.assertEquals('c1', c1.get_user_option('one'))
 
885
       # If we read during the write, we get the old value
 
886
       c2 = self.get_existing_config()
 
887
       self.assertEquals('1', c2.get_user_option('one'))
 
888
       # Let the writing occur and ensure it occurred
 
889
       do_writing.set()
 
890
       writing_done.wait()
 
891
       # Now we get the updated value
 
892
       c3 = self.get_existing_config()
 
893
       self.assertEquals('c1', c3.get_user_option('one'))
 
894
 
396
895
 
397
896
class TestGetUserOptionAs(TestIniConfig):
398
897
 
505
1004
        branch = self.make_branch('branch')
506
1005
        self.assertEqual('branch', branch.nick)
507
1006
 
508
 
        locations = config.locations_config_filename()
509
 
        config.ensure_config_dir_exists()
510
1007
        local_url = urlutils.local_path_to_url('branch')
511
 
        open(locations, 'wb').write('[%s]\nnickname = foobar'
512
 
                                    % (local_url,))
 
1008
        conf = config.LocationConfig.from_string(
 
1009
            '[%s]\nnickname = foobar' % (local_url,),
 
1010
            local_url, save=True)
513
1011
        self.assertEqual('foobar', branch.nick)
514
1012
 
515
1013
    def test_config_local_path(self):
517
1015
        branch = self.make_branch('branch')
518
1016
        self.assertEqual('branch', branch.nick)
519
1017
 
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'),))
 
1018
        local_path = osutils.getcwd().encode('utf8')
 
1019
        conf = config.LocationConfig.from_string(
 
1020
            '[%s/branch]\nnickname = barry' % (local_path,),
 
1021
            'branch',  save=True)
524
1022
        self.assertEqual('barry', branch.nick)
525
1023
 
526
1024
    def test_config_creates_local(self):
527
1025
        """Creating a new entry in config uses a local path."""
528
1026
        branch = self.make_branch('branch', format='knit')
529
1027
        branch.set_push_location('http://foobar')
530
 
        locations = config.locations_config_filename()
531
1028
        local_path = osutils.getcwd().encode('utf8')
532
1029
        # Surprisingly ConfigObj doesn't create a trailing newline
533
 
        self.check_file_contents(locations,
 
1030
        self.check_file_contents(config.locations_config_filename(),
534
1031
                                 '[%s/branch]\n'
535
1032
                                 'push_location = http://foobar\n'
536
1033
                                 'push_location:policy = norecurse\n'
541
1038
        self.assertEqual('!repo', b.get_config().get_nickname())
542
1039
 
543
1040
    def test_warn_if_masked(self):
544
 
        _warning = trace.warning
545
1041
        warnings = []
546
1042
        def warning(*args):
547
1043
            warnings.append(args[0] % args[1:])
 
1044
        self.overrideAttr(trace, 'warning', warning)
548
1045
 
549
1046
        def set_option(store, warn_masked=True):
550
1047
            warnings[:] = []
556
1053
            else:
557
1054
                self.assertEqual(1, len(warnings))
558
1055
                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):
 
1056
        branch = self.make_branch('.')
 
1057
        conf = branch.get_config()
 
1058
        set_option(config.STORE_GLOBAL)
 
1059
        assertWarning(None)
 
1060
        set_option(config.STORE_BRANCH)
 
1061
        assertWarning(None)
 
1062
        set_option(config.STORE_GLOBAL)
 
1063
        assertWarning('Value "4" is masked by "3" from branch.conf')
 
1064
        set_option(config.STORE_GLOBAL, warn_masked=False)
 
1065
        assertWarning(None)
 
1066
        set_option(config.STORE_LOCATION)
 
1067
        assertWarning(None)
 
1068
        set_option(config.STORE_BRANCH)
 
1069
        assertWarning('Value "3" is masked by "0" from locations.conf')
 
1070
        set_option(config.STORE_BRANCH, warn_masked=False)
 
1071
        assertWarning(None)
 
1072
 
 
1073
 
 
1074
class TestGlobalConfigItems(tests.TestCaseInTempDir):
582
1075
 
583
1076
    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)
 
1077
        my_config = config.GlobalConfig.from_string(sample_config_text)
587
1078
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
588
1079
                         my_config._get_user_id())
589
1080
 
590
1081
    def test_absent_user_id(self):
591
 
        config_file = StringIO("")
592
1082
        my_config = config.GlobalConfig()
593
 
        my_config._parser = my_config._get_parser(file=config_file)
594
1083
        self.assertEqual(None, my_config._get_user_id())
595
1084
 
596
1085
    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)
 
1086
        my_config = config.GlobalConfig.from_string(sample_config_text)
600
1087
        self.assertEqual("vim", my_config.get_editor())
601
1088
 
602
1089
    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)
 
1090
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
606
1091
        self.assertEqual(config.CHECK_NEVER,
607
1092
                         my_config.signature_checking())
608
1093
        self.assertEqual(config.SIGN_ALWAYS,
610
1095
        self.assertEqual(True, my_config.signature_needed())
611
1096
 
612
1097
    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)
 
1098
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
616
1099
        self.assertEqual(config.CHECK_NEVER,
617
1100
                         my_config.signature_checking())
618
1101
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
620
1103
        self.assertEqual(False, my_config.signature_needed())
621
1104
 
622
1105
    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)
 
1106
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
626
1107
        self.assertEqual(config.CHECK_ALWAYS,
627
1108
                         my_config.signature_checking())
628
1109
        self.assertEqual(config.SIGN_NEVER,
630
1111
        self.assertEqual(False, my_config.signature_needed())
631
1112
 
632
1113
    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)
 
1114
        my_config = config.GlobalConfig.from_string(sample_config_text)
636
1115
        return my_config
637
1116
 
638
1117
    def test_gpg_signing_command(self):
641
1120
        self.assertEqual(False, my_config.signature_needed())
642
1121
 
643
1122
    def _get_empty_config(self):
644
 
        config_file = StringIO("")
645
1123
        my_config = config.GlobalConfig()
646
 
        my_config._parser = my_config._get_parser(file=config_file)
647
1124
        return my_config
648
1125
 
649
1126
    def test_gpg_signing_command_unset(self):
699
1176
        change_editor = my_config.get_change_editor('old', 'new')
700
1177
        self.assertIs(None, change_editor)
701
1178
 
 
1179
    def test_get_merge_tools(self):
 
1180
        conf = self._get_sample_config()
 
1181
        tools = conf.get_merge_tools()
 
1182
        self.log(repr(tools))
 
1183
        self.assertEqual(
 
1184
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
 
1185
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
 
1186
            tools)
 
1187
 
 
1188
    def test_get_merge_tools_empty(self):
 
1189
        conf = self._get_empty_config()
 
1190
        tools = conf.get_merge_tools()
 
1191
        self.assertEqual({}, tools)
 
1192
 
 
1193
    def test_find_merge_tool(self):
 
1194
        conf = self._get_sample_config()
 
1195
        cmdline = conf.find_merge_tool('sometool')
 
1196
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
 
1197
 
 
1198
    def test_find_merge_tool_not_found(self):
 
1199
        conf = self._get_sample_config()
 
1200
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
 
1201
        self.assertIs(cmdline, None)
 
1202
 
 
1203
    def test_find_merge_tool_known(self):
 
1204
        conf = self._get_empty_config()
 
1205
        cmdline = conf.find_merge_tool('kdiff3')
 
1206
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
 
1207
 
 
1208
    def test_find_merge_tool_override_known(self):
 
1209
        conf = self._get_empty_config()
 
1210
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
 
1211
        cmdline = conf.find_merge_tool('kdiff3')
 
1212
        self.assertEqual('kdiff3 blah', cmdline)
 
1213
 
702
1214
 
703
1215
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
704
1216
 
722
1234
        self.assertIs(None, new_config.get_alias('commit'))
723
1235
 
724
1236
 
725
 
class TestLocationConfig(tests.TestCaseInTempDir):
 
1237
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
726
1238
 
727
1239
    def test_constructs(self):
728
1240
        my_config = config.LocationConfig('http://example.com')
744
1256
        self.assertEqual(parser._calls,
745
1257
                         [('__init__', config.locations_config_filename(),
746
1258
                           '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
1259
 
760
1260
    def test_get_global_config(self):
761
1261
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
848
1348
            'http://www.example.com', 'appendpath_option'),
849
1349
            config.POLICY_APPENDPATH)
850
1350
 
 
1351
    def test__get_options_with_policy(self):
 
1352
        self.get_branch_config('/dir/subdir',
 
1353
                               location_config="""\
 
1354
[/dir]
 
1355
other_url = /other-dir
 
1356
other_url:policy = appendpath
 
1357
[/dir/subdir]
 
1358
other_url = /other-subdir
 
1359
""")
 
1360
        self.assertOptions(
 
1361
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
 
1362
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
 
1363
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
 
1364
            self.my_location_config)
 
1365
 
851
1366
    def test_location_without_username(self):
852
1367
        self.get_branch_config('http://www.example.com/ignoreparent')
853
1368
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
989
1504
        self.assertEqual('bzrlib.tests.test_config.post_commit',
990
1505
                         self.my_config.post_commit())
991
1506
 
992
 
    def get_branch_config(self, location, global_config=None):
 
1507
    def get_branch_config(self, location, global_config=None,
 
1508
                          location_config=None):
 
1509
        my_branch = FakeBranch(location)
993
1510
        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)
 
1511
            global_config = sample_config_text
 
1512
        if location_config is None:
 
1513
            location_config = sample_branches_text
 
1514
 
 
1515
        my_global_config = config.GlobalConfig.from_string(global_config,
 
1516
                                                           save=True)
 
1517
        my_location_config = config.LocationConfig.from_string(
 
1518
            location_config, my_branch.base, save=True)
 
1519
        my_config = config.BranchConfig(my_branch)
 
1520
        self.my_config = my_config
 
1521
        self.my_location_config = my_config._get_location_config()
1004
1522
 
1005
1523
    def test_set_user_setting_sets_and_saves(self):
1006
1524
        self.get_branch_config('/a/c')
1007
1525
        record = InstrumentedConfigObj("foo")
1008
1526
        self.my_location_config._parser = record
1009
1527
 
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'),
 
1528
        self.callDeprecated(['The recurse option is deprecated as of '
 
1529
                             '0.14.  The section "/a/c" has been '
 
1530
                             'converted to use policies.'],
 
1531
                            self.my_config.set_user_option,
 
1532
                            'foo', 'bar', store=config.STORE_LOCATION)
 
1533
        self.assertEqual([('reload',),
 
1534
                          ('__contains__', '/a/c'),
1029
1535
                          ('__contains__', '/a/c/'),
1030
1536
                          ('__setitem__', '/a/c', {}),
1031
1537
                          ('__getitem__', '/a/c'),
1060
1566
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1061
1567
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1062
1568
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1063
 
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
1569
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1064
1570
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1065
1571
 
1066
1572
 
1074
1580
option = exact
1075
1581
"""
1076
1582
 
1077
 
 
1078
1583
class TestBranchConfigItems(tests.TestCaseInTempDir):
1079
1584
 
1080
1585
    def get_branch_config(self, global_config=None, location=None,
1081
1586
                          location_config=None, branch_data_config=None):
1082
 
        my_config = config.BranchConfig(FakeBranch(location))
 
1587
        my_branch = FakeBranch(location)
1083
1588
        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()
 
1589
            my_global_config = config.GlobalConfig.from_string(global_config,
 
1590
                                                               save=True)
1087
1591
        if location_config is not None:
1088
 
            location_file = StringIO(location_config.encode('utf-8'))
1089
 
            self.my_location_config._get_parser(location_file)
 
1592
            my_location_config = config.LocationConfig.from_string(
 
1593
                location_config, my_branch.base, save=True)
 
1594
        my_config = config.BranchConfig(my_branch)
1090
1595
        if branch_data_config is not None:
1091
1596
            my_config.branch.control_files.files['branch.conf'] = \
1092
1597
                branch_data_config
1106
1611
                         my_config.username())
1107
1612
 
1108
1613
    def test_not_set_in_branch(self):
1109
 
        my_config = self.get_branch_config(sample_config_text)
 
1614
        my_config = self.get_branch_config(global_config=sample_config_text)
1110
1615
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1111
1616
                         my_config._get_user_id())
1112
1617
        my_config.branch.control_files.files['email'] = "John"
1113
1618
        self.assertEqual("John", my_config._get_user_id())
1114
1619
 
1115
1620
    def test_BZR_EMAIL_OVERRIDES(self):
1116
 
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
 
1621
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1117
1622
        branch = FakeBranch()
1118
1623
        my_config = config.BranchConfig(branch)
1119
1624
        self.assertEqual("Robert Collins <robertc@example.org>",
1136
1641
 
1137
1642
    def test_gpg_signing_command(self):
1138
1643
        my_config = self.get_branch_config(
 
1644
            global_config=sample_config_text,
1139
1645
            # branch data cannot set gpg_signing_command
1140
1646
            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
1647
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1144
1648
 
1145
1649
    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))
 
1650
        my_config = self.get_branch_config(global_config=sample_config_text)
1150
1651
        self.assertEqual('something',
1151
1652
                         my_config.get_user_option('user_global_option'))
1152
1653
 
1153
1654
    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)
 
1655
        my_config = self.get_branch_config(global_config=sample_config_text,
 
1656
                                      location='/a/c',
 
1657
                                      location_config=sample_branches_text)
1157
1658
        self.assertEqual(my_config.branch.base, '/a/c')
1158
1659
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1159
1660
                         my_config.post_commit())
1160
1661
        my_config.set_user_option('post_commit', 'rmtree_root')
1161
 
        # post-commit is ignored when bresent in branch data
 
1662
        # post-commit is ignored when present in branch data
1162
1663
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1163
1664
                         my_config.post_commit())
1164
1665
        my_config.set_user_option('post_commit', 'rmtree_root',
1166
1667
        self.assertEqual('rmtree_root', my_config.post_commit())
1167
1668
 
1168
1669
    def test_config_precedence(self):
 
1670
        # FIXME: eager test, luckily no persitent config file makes it fail
 
1671
        # -- vila 20100716
1169
1672
        my_config = self.get_branch_config(global_config=precedence_global)
1170
1673
        self.assertEqual(my_config.get_user_option('option'), 'global')
1171
1674
        my_config = self.get_branch_config(global_config=precedence_global,
1172
 
                                      branch_data_config=precedence_branch)
 
1675
                                           branch_data_config=precedence_branch)
1173
1676
        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)
 
1677
        my_config = self.get_branch_config(
 
1678
            global_config=precedence_global,
 
1679
            branch_data_config=precedence_branch,
 
1680
            location_config=precedence_location)
1177
1681
        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')
 
1682
        my_config = self.get_branch_config(
 
1683
            global_config=precedence_global,
 
1684
            branch_data_config=precedence_branch,
 
1685
            location_config=precedence_location,
 
1686
            location='http://example.com/specific')
1182
1687
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1183
1688
 
1184
1689
    def test_get_mail_client(self):
1312
1817
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1313
1818
 
1314
1819
 
 
1820
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
 
1821
 
 
1822
    def setUp(self):
 
1823
        super(TestConfigGetOptions, self).setUp()
 
1824
        create_configs(self)
 
1825
 
 
1826
    # One variable in none of the above
 
1827
    def test_no_variable(self):
 
1828
        # Using branch should query branch, locations and bazaar
 
1829
        self.assertOptions([], self.branch_config)
 
1830
 
 
1831
    def test_option_in_bazaar(self):
 
1832
        self.bazaar_config.set_user_option('file', 'bazaar')
 
1833
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
 
1834
                           self.bazaar_config)
 
1835
 
 
1836
    def test_option_in_locations(self):
 
1837
        self.locations_config.set_user_option('file', 'locations')
 
1838
        self.assertOptions(
 
1839
            [('file', 'locations', self.tree.basedir, 'locations')],
 
1840
            self.locations_config)
 
1841
 
 
1842
    def test_option_in_branch(self):
 
1843
        self.branch_config.set_user_option('file', 'branch')
 
1844
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
 
1845
                           self.branch_config)
 
1846
 
 
1847
    def test_option_in_bazaar_and_branch(self):
 
1848
        self.bazaar_config.set_user_option('file', 'bazaar')
 
1849
        self.branch_config.set_user_option('file', 'branch')
 
1850
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
 
1851
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
1852
                           self.branch_config)
 
1853
 
 
1854
    def test_option_in_branch_and_locations(self):
 
1855
        # Hmm, locations override branch :-/
 
1856
        self.locations_config.set_user_option('file', 'locations')
 
1857
        self.branch_config.set_user_option('file', 'branch')
 
1858
        self.assertOptions(
 
1859
            [('file', 'locations', self.tree.basedir, 'locations'),
 
1860
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
1861
            self.branch_config)
 
1862
 
 
1863
    def test_option_in_bazaar_locations_and_branch(self):
 
1864
        self.bazaar_config.set_user_option('file', 'bazaar')
 
1865
        self.locations_config.set_user_option('file', 'locations')
 
1866
        self.branch_config.set_user_option('file', 'branch')
 
1867
        self.assertOptions(
 
1868
            [('file', 'locations', self.tree.basedir, 'locations'),
 
1869
             ('file', 'branch', 'DEFAULT', 'branch'),
 
1870
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
1871
            self.branch_config)
 
1872
 
 
1873
 
 
1874
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
 
1875
 
 
1876
    def setUp(self):
 
1877
        super(TestConfigRemoveOption, self).setUp()
 
1878
        create_configs_with_file_option(self)
 
1879
 
 
1880
    def test_remove_in_locations(self):
 
1881
        self.locations_config.remove_user_option('file', self.tree.basedir)
 
1882
        self.assertOptions(
 
1883
            [('file', 'branch', 'DEFAULT', 'branch'),
 
1884
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
1885
            self.branch_config)
 
1886
 
 
1887
    def test_remove_in_branch(self):
 
1888
        self.branch_config.remove_user_option('file')
 
1889
        self.assertOptions(
 
1890
            [('file', 'locations', self.tree.basedir, 'locations'),
 
1891
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
1892
            self.branch_config)
 
1893
 
 
1894
    def test_remove_in_bazaar(self):
 
1895
        self.bazaar_config.remove_user_option('file')
 
1896
        self.assertOptions(
 
1897
            [('file', 'locations', self.tree.basedir, 'locations'),
 
1898
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
1899
            self.branch_config)
 
1900
 
 
1901
 
 
1902
class TestConfigGetSections(tests.TestCaseWithTransport):
 
1903
 
 
1904
    def setUp(self):
 
1905
        super(TestConfigGetSections, self).setUp()
 
1906
        create_configs(self)
 
1907
 
 
1908
    def assertSectionNames(self, expected, conf, name=None):
 
1909
        """Check which sections are returned for a given config.
 
1910
 
 
1911
        If fallback configurations exist their sections can be included.
 
1912
 
 
1913
        :param expected: A list of section names.
 
1914
 
 
1915
        :param conf: The configuration that will be queried.
 
1916
 
 
1917
        :param name: An optional section name that will be passed to
 
1918
            get_sections().
 
1919
        """
 
1920
        sections = list(conf._get_sections(name))
 
1921
        self.assertLength(len(expected), sections)
 
1922
        self.assertEqual(expected, [name for name, _, _ in sections])
 
1923
 
 
1924
    def test_bazaar_default_section(self):
 
1925
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
 
1926
 
 
1927
    def test_locations_default_section(self):
 
1928
        # No sections are defined in an empty file
 
1929
        self.assertSectionNames([], self.locations_config)
 
1930
 
 
1931
    def test_locations_named_section(self):
 
1932
        self.locations_config.set_user_option('file', 'locations')
 
1933
        self.assertSectionNames([self.tree.basedir], self.locations_config)
 
1934
 
 
1935
    def test_locations_matching_sections(self):
 
1936
        loc_config = self.locations_config
 
1937
        loc_config.set_user_option('file', 'locations')
 
1938
        # We need to cheat a bit here to create an option in sections above and
 
1939
        # below the 'location' one.
 
1940
        parser = loc_config._get_parser()
 
1941
        # locations.cong deals with '/' ignoring native os.sep
 
1942
        location_names = self.tree.basedir.split('/')
 
1943
        parent = '/'.join(location_names[:-1])
 
1944
        child = '/'.join(location_names + ['child'])
 
1945
        parser[parent] = {}
 
1946
        parser[parent]['file'] = 'parent'
 
1947
        parser[child] = {}
 
1948
        parser[child]['file'] = 'child'
 
1949
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
 
1950
 
 
1951
    def test_branch_data_default_section(self):
 
1952
        self.assertSectionNames([None],
 
1953
                                self.branch_config._get_branch_data_config())
 
1954
 
 
1955
    def test_branch_default_sections(self):
 
1956
        # No sections are defined in an empty locations file
 
1957
        self.assertSectionNames([None, 'DEFAULT'],
 
1958
                                self.branch_config)
 
1959
        # Unless we define an option
 
1960
        self.branch_config._get_location_config().set_user_option(
 
1961
            'file', 'locations')
 
1962
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
 
1963
                                self.branch_config)
 
1964
 
 
1965
    def test_bazaar_named_section(self):
 
1966
        # We need to cheat as the API doesn't give direct access to sections
 
1967
        # other than DEFAULT.
 
1968
        self.bazaar_config.set_alias('bazaar', 'bzr')
 
1969
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
 
1970
 
 
1971
 
1315
1972
class TestAuthenticationConfigFile(tests.TestCase):
1316
1973
    """Test the authentication.conf file matching"""
1317
1974