/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: Vincent Ladeuil
  • Date: 2011-06-16 10:45:17 UTC
  • mto: This revision was merged to the branch mainline in revision 5981.
  • Revision ID: v.ladeuil+lp@free.fr-20110616104517-4qzhmzkxgozji88y
Add copyright notice, some docs and some cleanups.

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,
 
40
    remote,
34
41
    tests,
35
42
    trace,
36
43
    transport,
37
44
    )
 
45
from bzrlib.symbol_versioning import (
 
46
    deprecated_in,
 
47
    deprecated_method,
 
48
    )
 
49
from bzrlib.transport import remote as transport_remote
 
50
from bzrlib.tests import (
 
51
    features,
 
52
    scenarios,
 
53
    test_server,
 
54
    )
38
55
from bzrlib.util.configobj import configobj
39
56
 
40
57
 
 
58
def lockable_config_scenarios():
 
59
    return [
 
60
        ('global',
 
61
         {'config_class': config.GlobalConfig,
 
62
          'config_args': [],
 
63
          'config_section': 'DEFAULT'}),
 
64
        ('locations',
 
65
         {'config_class': config.LocationConfig,
 
66
          'config_args': ['.'],
 
67
          'config_section': '.'}),]
 
68
 
 
69
 
 
70
load_tests = scenarios.load_tests_apply_scenarios
 
71
 
 
72
# Register helpers to build stores
 
73
config.test_store_builder_registry.register(
 
74
    'configobj', lambda test: config.IniFileStore(test.get_transport(),
 
75
                                                  'configobj.conf'))
 
76
config.test_store_builder_registry.register(
 
77
    'bazaar', lambda test: config.GlobalStore())
 
78
config.test_store_builder_registry.register(
 
79
    'location', lambda test: config.LocationStore())
 
80
 
 
81
 
 
82
def build_backing_branch(test, relpath,
 
83
                         transport_class=None, server_class=None):
 
84
    """Test helper to create a backing branch only once.
 
85
 
 
86
    Some tests needs multiple stores/stacks to check concurrent update
 
87
    behaviours. As such, they need to build different branch *objects* even if
 
88
    they share the branch on disk.
 
89
 
 
90
    :param relpath: The relative path to the branch. (Note that the helper
 
91
        should always specify the same relpath).
 
92
 
 
93
    :param transport_class: The Transport class the test needs to use.
 
94
 
 
95
    :param server_class: The server associated with the ``transport_class``
 
96
        above.
 
97
 
 
98
    Either both or neither of ``transport_class`` and ``server_class`` should
 
99
    be specified.
 
100
    """
 
101
    if transport_class is not None and server_class is not None:
 
102
        test.transport_class = transport_class
 
103
        test.transport_server = server_class
 
104
    elif not (transport_class is None and server_class is None):
 
105
        raise AssertionError('Specify both ``transport_class`` and '
 
106
                             '``server_class`` or neither of them')
 
107
    if getattr(test, 'backing_branch', None) is None:
 
108
        # First call, let's build the branch on disk
 
109
        test.backing_branch = test.make_branch(relpath)
 
110
 
 
111
 
 
112
def build_branch_store(test):
 
113
    build_backing_branch(test, 'branch')
 
114
    b = branch.Branch.open('branch')
 
115
    return config.BranchStore(b)
 
116
config.test_store_builder_registry.register('branch', build_branch_store)
 
117
 
 
118
 
 
119
def build_remote_branch_store(test):
 
120
    # There is only one permutation (but we won't be able to handle more with
 
121
    # this design anyway)
 
122
    (transport_class,
 
123
     server_class) = transport_remote.get_test_permutations()[0]
 
124
    build_backing_branch(test, 'branch', transport_class, server_class)
 
125
    b = branch.Branch.open(test.get_url('branch'))
 
126
    return config.BranchStore(b)
 
127
config.test_store_builder_registry.register('remote_branch',
 
128
                                            build_remote_branch_store)
 
129
 
 
130
 
 
131
config.test_stack_builder_registry.register(
 
132
    'bazaar', lambda test: config.GlobalStack())
 
133
config.test_stack_builder_registry.register(
 
134
    'location', lambda test: config.LocationStack('.'))
 
135
 
 
136
 
 
137
def build_branch_stack(test):
 
138
    build_backing_branch(test, 'branch')
 
139
    b = branch.Branch.open('branch')
 
140
    return config.BranchStack(b)
 
141
config.test_stack_builder_registry.register('branch', build_branch_stack)
 
142
 
 
143
 
 
144
def build_remote_branch_stack(test):
 
145
    # There is only one permutation (but we won't be able to handle more with
 
146
    # this design anyway)
 
147
    (transport_class,
 
148
     server_class) = transport_remote.get_test_permutations()[0]
 
149
    build_backing_branch(test, 'branch', transport_class, server_class)
 
150
    b = branch.Branch.open(test.get_url('branch'))
 
151
    return config.BranchStack(b)
 
152
config.test_stack_builder_registry.register('remote_branch',
 
153
                                            build_remote_branch_stack)
 
154
 
 
155
 
41
156
sample_long_alias="log -r-15..-1 --line"
42
157
sample_config_text = u"""
43
158
[DEFAULT]
47
162
gpg_signing_command=gnome-gpg
48
163
log_format=short
49
164
user_global_option=something
 
165
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
 
166
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
 
167
bzr.default_mergetool=sometool
50
168
[ALIASES]
51
169
h=help
52
170
ll=""" + sample_long_alias + "\n"
105
223
"""
106
224
 
107
225
 
 
226
def create_configs(test):
 
227
    """Create configuration files for a given test.
 
228
 
 
229
    This requires creating a tree (and populate the ``test.tree`` attribute)
 
230
    and its associated branch and will populate the following attributes:
 
231
 
 
232
    - branch_config: A BranchConfig for the associated branch.
 
233
 
 
234
    - locations_config : A LocationConfig for the associated branch
 
235
 
 
236
    - bazaar_config: A GlobalConfig.
 
237
 
 
238
    The tree and branch are created in a 'tree' subdirectory so the tests can
 
239
    still use the test directory to stay outside of the branch.
 
240
    """
 
241
    tree = test.make_branch_and_tree('tree')
 
242
    test.tree = tree
 
243
    test.branch_config = config.BranchConfig(tree.branch)
 
244
    test.locations_config = config.LocationConfig(tree.basedir)
 
245
    test.bazaar_config = config.GlobalConfig()
 
246
 
 
247
 
 
248
def create_configs_with_file_option(test):
 
249
    """Create configuration files with a ``file`` option set in each.
 
250
 
 
251
    This builds on ``create_configs`` and add one ``file`` option in each
 
252
    configuration with a value which allows identifying the configuration file.
 
253
    """
 
254
    create_configs(test)
 
255
    test.bazaar_config.set_user_option('file', 'bazaar')
 
256
    test.locations_config.set_user_option('file', 'locations')
 
257
    test.branch_config.set_user_option('file', 'branch')
 
258
 
 
259
 
 
260
class TestOptionsMixin:
 
261
 
 
262
    def assertOptions(self, expected, conf):
 
263
        # We don't care about the parser (as it will make tests hard to write
 
264
        # and error-prone anyway)
 
265
        self.assertThat([opt[:4] for opt in conf._get_options()],
 
266
                        matchers.Equals(expected))
 
267
 
 
268
 
108
269
class InstrumentedConfigObj(object):
109
270
    """A config obj look-enough-alike to record calls made to it."""
110
271
 
129
290
        self._calls.append(('keys',))
130
291
        return []
131
292
 
 
293
    def reload(self):
 
294
        self._calls.append(('reload',))
 
295
 
132
296
    def write(self, arg):
133
297
        self._calls.append(('write',))
134
298
 
240
404
        """
241
405
        co = config.ConfigObj()
242
406
        co['test'] = 'foo#bar'
243
 
        lines = co.write()
 
407
        outfile = StringIO()
 
408
        co.write(outfile=outfile)
 
409
        lines = outfile.getvalue().splitlines()
244
410
        self.assertEqual(lines, ['test = "foo#bar"'])
245
411
        co2 = config.ConfigObj(lines)
246
412
        self.assertEqual(co2['test'], 'foo#bar')
247
413
 
 
414
    def test_triple_quotes(self):
 
415
        # Bug #710410: if the value string has triple quotes
 
416
        # then ConfigObj versions up to 4.7.2 will quote them wrong
 
417
        # and won't able to read them back
 
418
        triple_quotes_value = '''spam
 
419
""" that's my spam """
 
420
eggs'''
 
421
        co = config.ConfigObj()
 
422
        co['test'] = triple_quotes_value
 
423
        # While writing this test another bug in ConfigObj has been found:
 
424
        # method co.write() without arguments produces list of lines
 
425
        # one option per line, and multiline values are not split
 
426
        # across multiple lines,
 
427
        # and that breaks the parsing these lines back by ConfigObj.
 
428
        # This issue only affects test, but it's better to avoid
 
429
        # `co.write()` construct at all.
 
430
        # [bialix 20110222] bug report sent to ConfigObj's author
 
431
        outfile = StringIO()
 
432
        co.write(outfile=outfile)
 
433
        output = outfile.getvalue()
 
434
        # now we're trying to read it back
 
435
        co2 = config.ConfigObj(StringIO(output))
 
436
        self.assertEquals(triple_quotes_value, co2['test'])
 
437
 
248
438
 
249
439
erroneous_config = """[section] # line 1
250
440
good=good # line 2
271
461
        config.Config()
272
462
 
273
463
    def test_no_default_editor(self):
274
 
        self.assertRaises(NotImplementedError, config.Config().get_editor)
 
464
        self.assertRaises(
 
465
            NotImplementedError,
 
466
            self.applyDeprecated, deprecated_in((2, 4, 0)),
 
467
            config.Config().get_editor)
275
468
 
276
469
    def test_user_email(self):
277
470
        my_config = InstrumentedConfig()
333
526
 
334
527
    def setUp(self):
335
528
        super(TestConfigPath, self).setUp()
336
 
        os.environ['HOME'] = '/home/bogus'
337
 
        os.environ['XDG_CACHE_DIR'] = ''
 
529
        self.overrideEnv('HOME', '/home/bogus')
 
530
        self.overrideEnv('XDG_CACHE_DIR', '')
338
531
        if sys.platform == 'win32':
339
 
            os.environ['BZR_HOME'] = \
340
 
                r'C:\Documents and Settings\bogus\Application Data'
 
532
            self.overrideEnv(
 
533
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
341
534
            self.bzr_home = \
342
535
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
343
536
        else:
350
543
        self.assertEqual(config.config_filename(),
351
544
                         self.bzr_home + '/bazaar.conf')
352
545
 
353
 
    def test_branches_config_filename(self):
354
 
        self.assertEqual(config.branches_config_filename(),
355
 
                         self.bzr_home + '/branches.conf')
356
 
 
357
546
    def test_locations_config_filename(self):
358
547
        self.assertEqual(config.locations_config_filename(),
359
548
                         self.bzr_home + '/locations.conf')
367
556
            '/home/bogus/.cache')
368
557
 
369
558
 
370
 
class TestIniConfig(tests.TestCase):
 
559
class TestXDGConfigDir(tests.TestCaseInTempDir):
 
560
    # must be in temp dir because config tests for the existence of the bazaar
 
561
    # subdirectory of $XDG_CONFIG_HOME
 
562
 
 
563
    def setUp(self):
 
564
        if sys.platform in ('darwin', 'win32'):
 
565
            raise tests.TestNotApplicable(
 
566
                'XDG config dir not used on this platform')
 
567
        super(TestXDGConfigDir, self).setUp()
 
568
        self.overrideEnv('HOME', self.test_home_dir)
 
569
        # BZR_HOME overrides everything we want to test so unset it.
 
570
        self.overrideEnv('BZR_HOME', None)
 
571
 
 
572
    def test_xdg_config_dir_exists(self):
 
573
        """When ~/.config/bazaar exists, use it as the config dir."""
 
574
        newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
 
575
        os.makedirs(newdir)
 
576
        self.assertEqual(config.config_dir(), newdir)
 
577
 
 
578
    def test_xdg_config_home(self):
 
579
        """When XDG_CONFIG_HOME is set, use it."""
 
580
        xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
 
581
        self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
 
582
        newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
 
583
        os.makedirs(newdir)
 
584
        self.assertEqual(config.config_dir(), newdir)
 
585
 
 
586
 
 
587
class TestIniConfig(tests.TestCaseInTempDir):
371
588
 
372
589
    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
 
590
        conf = config.IniBasedConfig.from_string(s)
 
591
        return conf, conf._get_parser()
376
592
 
377
593
 
378
594
class TestIniConfigBuilding(TestIniConfig):
379
595
 
380
596
    def test_contructs(self):
381
 
        my_config = config.IniBasedConfig("nothing")
 
597
        my_config = config.IniBasedConfig()
382
598
 
383
599
    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))
 
600
        my_config = config.IniBasedConfig.from_string(sample_config_text)
 
601
        self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
389
602
 
390
603
    def test_cached(self):
 
604
        my_config = config.IniBasedConfig.from_string(sample_config_text)
 
605
        parser = my_config._get_parser()
 
606
        self.assertTrue(my_config._get_parser() is parser)
 
607
 
 
608
    def _dummy_chown(self, path, uid, gid):
 
609
        self.path, self.uid, self.gid = path, uid, gid
 
610
 
 
611
    def test_ini_config_ownership(self):
 
612
        """Ensure that chown is happening during _write_config_file"""
 
613
        self.requireFeature(features.chown_feature)
 
614
        self.overrideAttr(os, 'chown', self._dummy_chown)
 
615
        self.path = self.uid = self.gid = None
 
616
        conf = config.IniBasedConfig(file_name='./foo.conf')
 
617
        conf._write_config_file()
 
618
        self.assertEquals(self.path, './foo.conf')
 
619
        self.assertTrue(isinstance(self.uid, int))
 
620
        self.assertTrue(isinstance(self.gid, int))
 
621
 
 
622
    def test_get_filename_parameter_is_deprecated_(self):
 
623
        conf = self.callDeprecated([
 
624
            'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
 
625
            ' Use file_name instead.'],
 
626
            config.IniBasedConfig, lambda: 'ini.conf')
 
627
        self.assertEqual('ini.conf', conf.file_name)
 
628
 
 
629
    def test_get_parser_file_parameter_is_deprecated_(self):
391
630
        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)
 
631
        conf = config.IniBasedConfig.from_string(sample_config_text)
 
632
        conf = self.callDeprecated([
 
633
            'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
 
634
            ' Use IniBasedConfig(_content=xxx) instead.'],
 
635
            conf._get_parser, file=config_file)
 
636
 
 
637
 
 
638
class TestIniConfigSaving(tests.TestCaseInTempDir):
 
639
 
 
640
    def test_cant_save_without_a_file_name(self):
 
641
        conf = config.IniBasedConfig()
 
642
        self.assertRaises(AssertionError, conf._write_config_file)
 
643
 
 
644
    def test_saved_with_content(self):
 
645
        content = 'foo = bar\n'
 
646
        conf = config.IniBasedConfig.from_string(
 
647
            content, file_name='./test.conf', save=True)
 
648
        self.assertFileEqual(content, 'test.conf')
 
649
 
 
650
 
 
651
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
 
652
    """What is the default value of expand for config options.
 
653
 
 
654
    This is an opt-in beta feature used to evaluate whether or not option
 
655
    references can appear in dangerous place raising exceptions, disapearing
 
656
    (and as such corrupting data) or if it's safe to activate the option by
 
657
    default.
 
658
 
 
659
    Note that these tests relies on config._expand_default_value being already
 
660
    overwritten in the parent class setUp.
 
661
    """
 
662
 
 
663
    def setUp(self):
 
664
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
 
665
        self.config = None
 
666
        self.warnings = []
 
667
        def warning(*args):
 
668
            self.warnings.append(args[0] % args[1:])
 
669
        self.overrideAttr(trace, 'warning', warning)
 
670
 
 
671
    def get_config(self, expand):
 
672
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
 
673
                                            save=True)
 
674
        return c
 
675
 
 
676
    def assertExpandIs(self, expected):
 
677
        actual = config._get_expand_default_value()
 
678
        #self.config.get_user_option_as_bool('bzr.config.expand')
 
679
        self.assertEquals(expected, actual)
 
680
 
 
681
    def test_default_is_None(self):
 
682
        self.assertEquals(None, config._expand_default_value)
 
683
 
 
684
    def test_default_is_False_even_if_None(self):
 
685
        self.config = self.get_config(None)
 
686
        self.assertExpandIs(False)
 
687
 
 
688
    def test_default_is_False_even_if_invalid(self):
 
689
        self.config = self.get_config('<your choice>')
 
690
        self.assertExpandIs(False)
 
691
        # ...
 
692
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
 
693
        # Wait, you've been warned !
 
694
        self.assertLength(1, self.warnings)
 
695
        self.assertEquals(
 
696
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
 
697
            self.warnings[0])
 
698
 
 
699
    def test_default_is_True(self):
 
700
        self.config = self.get_config(True)
 
701
        self.assertExpandIs(True)
 
702
 
 
703
    def test_default_is_False(self):
 
704
        self.config = self.get_config(False)
 
705
        self.assertExpandIs(False)
 
706
 
 
707
 
 
708
class TestIniConfigOptionExpansion(tests.TestCase):
 
709
    """Test option expansion from the IniConfig level.
 
710
 
 
711
    What we really want here is to test the Config level, but the class being
 
712
    abstract as far as storing values is concerned, this can't be done
 
713
    properly (yet).
 
714
    """
 
715
    # FIXME: This should be rewritten when all configs share a storage
 
716
    # implementation -- vila 2011-02-18
 
717
 
 
718
    def get_config(self, string=None):
 
719
        if string is None:
 
720
            string = ''
 
721
        c = config.IniBasedConfig.from_string(string)
 
722
        return c
 
723
 
 
724
    def assertExpansion(self, expected, conf, string, env=None):
 
725
        self.assertEquals(expected, conf.expand_options(string, env))
 
726
 
 
727
    def test_no_expansion(self):
 
728
        c = self.get_config('')
 
729
        self.assertExpansion('foo', c, 'foo')
 
730
 
 
731
    def test_env_adding_options(self):
 
732
        c = self.get_config('')
 
733
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
734
 
 
735
    def test_env_overriding_options(self):
 
736
        c = self.get_config('foo=baz')
 
737
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
738
 
 
739
    def test_simple_ref(self):
 
740
        c = self.get_config('foo=xxx')
 
741
        self.assertExpansion('xxx', c, '{foo}')
 
742
 
 
743
    def test_unknown_ref(self):
 
744
        c = self.get_config('')
 
745
        self.assertRaises(errors.ExpandingUnknownOption,
 
746
                          c.expand_options, '{foo}')
 
747
 
 
748
    def test_indirect_ref(self):
 
749
        c = self.get_config('''
 
750
foo=xxx
 
751
bar={foo}
 
752
''')
 
753
        self.assertExpansion('xxx', c, '{bar}')
 
754
 
 
755
    def test_embedded_ref(self):
 
756
        c = self.get_config('''
 
757
foo=xxx
 
758
bar=foo
 
759
''')
 
760
        self.assertExpansion('xxx', c, '{{bar}}')
 
761
 
 
762
    def test_simple_loop(self):
 
763
        c = self.get_config('foo={foo}')
 
764
        self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
 
765
 
 
766
    def test_indirect_loop(self):
 
767
        c = self.get_config('''
 
768
foo={bar}
 
769
bar={baz}
 
770
baz={foo}''')
 
771
        e = self.assertRaises(errors.OptionExpansionLoop,
 
772
                              c.expand_options, '{foo}')
 
773
        self.assertEquals('foo->bar->baz', e.refs)
 
774
        self.assertEquals('{foo}', e.string)
 
775
 
 
776
    def test_list(self):
 
777
        conf = self.get_config('''
 
778
foo=start
 
779
bar=middle
 
780
baz=end
 
781
list={foo},{bar},{baz}
 
782
''')
 
783
        self.assertEquals(['start', 'middle', 'end'],
 
784
                           conf.get_user_option('list', expand=True))
 
785
 
 
786
    def test_cascading_list(self):
 
787
        conf = self.get_config('''
 
788
foo=start,{bar}
 
789
bar=middle,{baz}
 
790
baz=end
 
791
list={foo}
 
792
''')
 
793
        self.assertEquals(['start', 'middle', 'end'],
 
794
                           conf.get_user_option('list', expand=True))
 
795
 
 
796
    def test_pathological_hidden_list(self):
 
797
        conf = self.get_config('''
 
798
foo=bin
 
799
bar=go
 
800
start={foo
 
801
middle=},{
 
802
end=bar}
 
803
hidden={start}{middle}{end}
 
804
''')
 
805
        # Nope, it's either a string or a list, and the list wins as soon as a
 
806
        # ',' appears, so the string concatenation never occur.
 
807
        self.assertEquals(['{foo', '}', '{', 'bar}'],
 
808
                          conf.get_user_option('hidden', expand=True))
 
809
 
 
810
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
 
811
 
 
812
    def get_config(self, location, string=None):
 
813
        if string is None:
 
814
            string = ''
 
815
        # Since we don't save the config we won't strictly require to inherit
 
816
        # from TestCaseInTempDir, but an error occurs so quickly...
 
817
        c = config.LocationConfig.from_string(string, location)
 
818
        return c
 
819
 
 
820
    def test_dont_cross_unrelated_section(self):
 
821
        c = self.get_config('/another/branch/path','''
 
822
[/one/branch/path]
 
823
foo = hello
 
824
bar = {foo}/2
 
825
 
 
826
[/another/branch/path]
 
827
bar = {foo}/2
 
828
''')
 
829
        self.assertRaises(errors.ExpandingUnknownOption,
 
830
                          c.get_user_option, 'bar', expand=True)
 
831
 
 
832
    def test_cross_related_sections(self):
 
833
        c = self.get_config('/project/branch/path','''
 
834
[/project]
 
835
foo = qu
 
836
 
 
837
[/project/branch/path]
 
838
bar = {foo}ux
 
839
''')
 
840
        self.assertEquals('quux', c.get_user_option('bar', expand=True))
 
841
 
 
842
 
 
843
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
 
844
 
 
845
    def test_cannot_reload_without_name(self):
 
846
        conf = config.IniBasedConfig.from_string(sample_config_text)
 
847
        self.assertRaises(AssertionError, conf.reload)
 
848
 
 
849
    def test_reload_see_new_value(self):
 
850
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
 
851
                                               file_name='./test/conf')
 
852
        c1._write_config_file()
 
853
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
 
854
                                               file_name='./test/conf')
 
855
        c2._write_config_file()
 
856
        self.assertEqual('vim', c1.get_user_option('editor'))
 
857
        self.assertEqual('emacs', c2.get_user_option('editor'))
 
858
        # Make sure we get the Right value
 
859
        c1.reload()
 
860
        self.assertEqual('emacs', c1.get_user_option('editor'))
 
861
 
 
862
 
 
863
class TestLockableConfig(tests.TestCaseInTempDir):
 
864
 
 
865
    scenarios = lockable_config_scenarios()
 
866
 
 
867
    # Set by load_tests
 
868
    config_class = None
 
869
    config_args = None
 
870
    config_section = None
 
871
 
 
872
    def setUp(self):
 
873
        super(TestLockableConfig, self).setUp()
 
874
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
 
875
        self.config = self.create_config(self._content)
 
876
 
 
877
    def get_existing_config(self):
 
878
        return self.config_class(*self.config_args)
 
879
 
 
880
    def create_config(self, content):
 
881
        kwargs = dict(save=True)
 
882
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
 
883
        return c
 
884
 
 
885
    def test_simple_read_access(self):
 
886
        self.assertEquals('1', self.config.get_user_option('one'))
 
887
 
 
888
    def test_simple_write_access(self):
 
889
        self.config.set_user_option('one', 'one')
 
890
        self.assertEquals('one', self.config.get_user_option('one'))
 
891
 
 
892
    def test_listen_to_the_last_speaker(self):
 
893
        c1 = self.config
 
894
        c2 = self.get_existing_config()
 
895
        c1.set_user_option('one', 'ONE')
 
896
        c2.set_user_option('two', 'TWO')
 
897
        self.assertEquals('ONE', c1.get_user_option('one'))
 
898
        self.assertEquals('TWO', c2.get_user_option('two'))
 
899
        # The second update respect the first one
 
900
        self.assertEquals('ONE', c2.get_user_option('one'))
 
901
 
 
902
    def test_last_speaker_wins(self):
 
903
        # If the same config is not shared, the same variable modified twice
 
904
        # can only see a single result.
 
905
        c1 = self.config
 
906
        c2 = self.get_existing_config()
 
907
        c1.set_user_option('one', 'c1')
 
908
        c2.set_user_option('one', 'c2')
 
909
        self.assertEquals('c2', c2._get_user_option('one'))
 
910
        # The first modification is still available until another refresh
 
911
        # occur
 
912
        self.assertEquals('c1', c1._get_user_option('one'))
 
913
        c1.set_user_option('two', 'done')
 
914
        self.assertEquals('c2', c1._get_user_option('one'))
 
915
 
 
916
    def test_writes_are_serialized(self):
 
917
        c1 = self.config
 
918
        c2 = self.get_existing_config()
 
919
 
 
920
        # We spawn a thread that will pause *during* the write
 
921
        before_writing = threading.Event()
 
922
        after_writing = threading.Event()
 
923
        writing_done = threading.Event()
 
924
        c1_orig = c1._write_config_file
 
925
        def c1_write_config_file():
 
926
            before_writing.set()
 
927
            c1_orig()
 
928
            # The lock is held. We wait for the main thread to decide when to
 
929
            # continue
 
930
            after_writing.wait()
 
931
        c1._write_config_file = c1_write_config_file
 
932
        def c1_set_option():
 
933
            c1.set_user_option('one', 'c1')
 
934
            writing_done.set()
 
935
        t1 = threading.Thread(target=c1_set_option)
 
936
        # Collect the thread after the test
 
937
        self.addCleanup(t1.join)
 
938
        # Be ready to unblock the thread if the test goes wrong
 
939
        self.addCleanup(after_writing.set)
 
940
        t1.start()
 
941
        before_writing.wait()
 
942
        self.assertTrue(c1._lock.is_held)
 
943
        self.assertRaises(errors.LockContention,
 
944
                          c2.set_user_option, 'one', 'c2')
 
945
        self.assertEquals('c1', c1.get_user_option('one'))
 
946
        # Let the lock be released
 
947
        after_writing.set()
 
948
        writing_done.wait()
 
949
        c2.set_user_option('one', 'c2')
 
950
        self.assertEquals('c2', c2.get_user_option('one'))
 
951
 
 
952
    def test_read_while_writing(self):
 
953
       c1 = self.config
 
954
       # We spawn a thread that will pause *during* the write
 
955
       ready_to_write = threading.Event()
 
956
       do_writing = threading.Event()
 
957
       writing_done = threading.Event()
 
958
       c1_orig = c1._write_config_file
 
959
       def c1_write_config_file():
 
960
           ready_to_write.set()
 
961
           # The lock is held. We wait for the main thread to decide when to
 
962
           # continue
 
963
           do_writing.wait()
 
964
           c1_orig()
 
965
           writing_done.set()
 
966
       c1._write_config_file = c1_write_config_file
 
967
       def c1_set_option():
 
968
           c1.set_user_option('one', 'c1')
 
969
       t1 = threading.Thread(target=c1_set_option)
 
970
       # Collect the thread after the test
 
971
       self.addCleanup(t1.join)
 
972
       # Be ready to unblock the thread if the test goes wrong
 
973
       self.addCleanup(do_writing.set)
 
974
       t1.start()
 
975
       # Ensure the thread is ready to write
 
976
       ready_to_write.wait()
 
977
       self.assertTrue(c1._lock.is_held)
 
978
       self.assertEquals('c1', c1.get_user_option('one'))
 
979
       # If we read during the write, we get the old value
 
980
       c2 = self.get_existing_config()
 
981
       self.assertEquals('1', c2.get_user_option('one'))
 
982
       # Let the writing occur and ensure it occurred
 
983
       do_writing.set()
 
984
       writing_done.wait()
 
985
       # Now we get the updated value
 
986
       c3 = self.get_existing_config()
 
987
       self.assertEquals('c1', c3.get_user_option('one'))
395
988
 
396
989
 
397
990
class TestGetUserOptionAs(TestIniConfig):
462
1055
            parser = my_config._get_parser()
463
1056
        finally:
464
1057
            config.ConfigObj = oldparserclass
465
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
1058
        self.assertIsInstance(parser, InstrumentedConfigObj)
466
1059
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
467
1060
                                          'utf-8')])
468
1061
 
479
1072
        my_config = config.BranchConfig(branch)
480
1073
        location_config = my_config._get_location_config()
481
1074
        self.assertEqual(branch.base, location_config.location)
482
 
        self.failUnless(location_config is my_config._get_location_config())
 
1075
        self.assertIs(location_config, my_config._get_location_config())
483
1076
 
484
1077
    def test_get_config(self):
485
1078
        """The Branch.get_config method works properly"""
505
1098
        branch = self.make_branch('branch')
506
1099
        self.assertEqual('branch', branch.nick)
507
1100
 
508
 
        locations = config.locations_config_filename()
509
 
        config.ensure_config_dir_exists()
510
1101
        local_url = urlutils.local_path_to_url('branch')
511
 
        open(locations, 'wb').write('[%s]\nnickname = foobar'
512
 
                                    % (local_url,))
 
1102
        conf = config.LocationConfig.from_string(
 
1103
            '[%s]\nnickname = foobar' % (local_url,),
 
1104
            local_url, save=True)
513
1105
        self.assertEqual('foobar', branch.nick)
514
1106
 
515
1107
    def test_config_local_path(self):
517
1109
        branch = self.make_branch('branch')
518
1110
        self.assertEqual('branch', branch.nick)
519
1111
 
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'),))
 
1112
        local_path = osutils.getcwd().encode('utf8')
 
1113
        conf = config.LocationConfig.from_string(
 
1114
            '[%s/branch]\nnickname = barry' % (local_path,),
 
1115
            'branch',  save=True)
524
1116
        self.assertEqual('barry', branch.nick)
525
1117
 
526
1118
    def test_config_creates_local(self):
527
1119
        """Creating a new entry in config uses a local path."""
528
1120
        branch = self.make_branch('branch', format='knit')
529
1121
        branch.set_push_location('http://foobar')
530
 
        locations = config.locations_config_filename()
531
1122
        local_path = osutils.getcwd().encode('utf8')
532
1123
        # Surprisingly ConfigObj doesn't create a trailing newline
533
 
        self.check_file_contents(locations,
 
1124
        self.check_file_contents(config.locations_config_filename(),
534
1125
                                 '[%s/branch]\n'
535
1126
                                 'push_location = http://foobar\n'
536
1127
                                 'push_location:policy = norecurse\n'
541
1132
        self.assertEqual('!repo', b.get_config().get_nickname())
542
1133
 
543
1134
    def test_warn_if_masked(self):
544
 
        _warning = trace.warning
545
1135
        warnings = []
546
1136
        def warning(*args):
547
1137
            warnings.append(args[0] % args[1:])
 
1138
        self.overrideAttr(trace, 'warning', warning)
548
1139
 
549
1140
        def set_option(store, warn_masked=True):
550
1141
            warnings[:] = []
556
1147
            else:
557
1148
                self.assertEqual(1, len(warnings))
558
1149
                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):
 
1150
        branch = self.make_branch('.')
 
1151
        conf = branch.get_config()
 
1152
        set_option(config.STORE_GLOBAL)
 
1153
        assertWarning(None)
 
1154
        set_option(config.STORE_BRANCH)
 
1155
        assertWarning(None)
 
1156
        set_option(config.STORE_GLOBAL)
 
1157
        assertWarning('Value "4" is masked by "3" from branch.conf')
 
1158
        set_option(config.STORE_GLOBAL, warn_masked=False)
 
1159
        assertWarning(None)
 
1160
        set_option(config.STORE_LOCATION)
 
1161
        assertWarning(None)
 
1162
        set_option(config.STORE_BRANCH)
 
1163
        assertWarning('Value "3" is masked by "0" from locations.conf')
 
1164
        set_option(config.STORE_BRANCH, warn_masked=False)
 
1165
        assertWarning(None)
 
1166
 
 
1167
 
 
1168
class TestGlobalConfigItems(tests.TestCaseInTempDir):
582
1169
 
583
1170
    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)
 
1171
        my_config = config.GlobalConfig.from_string(sample_config_text)
587
1172
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
588
1173
                         my_config._get_user_id())
589
1174
 
590
1175
    def test_absent_user_id(self):
591
 
        config_file = StringIO("")
592
1176
        my_config = config.GlobalConfig()
593
 
        my_config._parser = my_config._get_parser(file=config_file)
594
1177
        self.assertEqual(None, my_config._get_user_id())
595
1178
 
596
1179
    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)
600
 
        self.assertEqual("vim", my_config.get_editor())
 
1180
        my_config = config.GlobalConfig.from_string(sample_config_text)
 
1181
        editor = self.applyDeprecated(
 
1182
            deprecated_in((2, 4, 0)), my_config.get_editor)
 
1183
        self.assertEqual('vim', editor)
601
1184
 
602
1185
    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)
 
1186
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
606
1187
        self.assertEqual(config.CHECK_NEVER,
607
1188
                         my_config.signature_checking())
608
1189
        self.assertEqual(config.SIGN_ALWAYS,
610
1191
        self.assertEqual(True, my_config.signature_needed())
611
1192
 
612
1193
    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)
 
1194
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
616
1195
        self.assertEqual(config.CHECK_NEVER,
617
1196
                         my_config.signature_checking())
618
1197
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
620
1199
        self.assertEqual(False, my_config.signature_needed())
621
1200
 
622
1201
    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)
 
1202
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
626
1203
        self.assertEqual(config.CHECK_ALWAYS,
627
1204
                         my_config.signature_checking())
628
1205
        self.assertEqual(config.SIGN_NEVER,
630
1207
        self.assertEqual(False, my_config.signature_needed())
631
1208
 
632
1209
    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)
 
1210
        my_config = config.GlobalConfig.from_string(sample_config_text)
636
1211
        return my_config
637
1212
 
638
1213
    def test_gpg_signing_command(self):
641
1216
        self.assertEqual(False, my_config.signature_needed())
642
1217
 
643
1218
    def _get_empty_config(self):
644
 
        config_file = StringIO("")
645
1219
        my_config = config.GlobalConfig()
646
 
        my_config._parser = my_config._get_parser(file=config_file)
647
1220
        return my_config
648
1221
 
649
1222
    def test_gpg_signing_command_unset(self):
699
1272
        change_editor = my_config.get_change_editor('old', 'new')
700
1273
        self.assertIs(None, change_editor)
701
1274
 
 
1275
    def test_get_merge_tools(self):
 
1276
        conf = self._get_sample_config()
 
1277
        tools = conf.get_merge_tools()
 
1278
        self.log(repr(tools))
 
1279
        self.assertEqual(
 
1280
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
 
1281
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
 
1282
            tools)
 
1283
 
 
1284
    def test_get_merge_tools_empty(self):
 
1285
        conf = self._get_empty_config()
 
1286
        tools = conf.get_merge_tools()
 
1287
        self.assertEqual({}, tools)
 
1288
 
 
1289
    def test_find_merge_tool(self):
 
1290
        conf = self._get_sample_config()
 
1291
        cmdline = conf.find_merge_tool('sometool')
 
1292
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
 
1293
 
 
1294
    def test_find_merge_tool_not_found(self):
 
1295
        conf = self._get_sample_config()
 
1296
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
 
1297
        self.assertIs(cmdline, None)
 
1298
 
 
1299
    def test_find_merge_tool_known(self):
 
1300
        conf = self._get_empty_config()
 
1301
        cmdline = conf.find_merge_tool('kdiff3')
 
1302
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
 
1303
 
 
1304
    def test_find_merge_tool_override_known(self):
 
1305
        conf = self._get_empty_config()
 
1306
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
 
1307
        cmdline = conf.find_merge_tool('kdiff3')
 
1308
        self.assertEqual('kdiff3 blah', cmdline)
 
1309
 
702
1310
 
703
1311
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
704
1312
 
722
1330
        self.assertIs(None, new_config.get_alias('commit'))
723
1331
 
724
1332
 
725
 
class TestLocationConfig(tests.TestCaseInTempDir):
 
1333
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
726
1334
 
727
1335
    def test_constructs(self):
728
1336
        my_config = config.LocationConfig('http://example.com')
740
1348
            parser = my_config._get_parser()
741
1349
        finally:
742
1350
            config.ConfigObj = oldparserclass
743
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
1351
        self.assertIsInstance(parser, InstrumentedConfigObj)
744
1352
        self.assertEqual(parser._calls,
745
1353
                         [('__init__', config.locations_config_filename(),
746
1354
                           '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
1355
 
760
1356
    def test_get_global_config(self):
761
1357
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
762
1358
        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())
 
1359
        self.assertIsInstance(global_config, config.GlobalConfig)
 
1360
        self.assertIs(global_config, my_config._get_global_config())
 
1361
 
 
1362
    def assertLocationMatching(self, expected):
 
1363
        self.assertEqual(expected,
 
1364
                         list(self.my_location_config._get_matching_sections()))
765
1365
 
766
1366
    def test__get_matching_sections_no_match(self):
767
1367
        self.get_branch_config('/')
768
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1368
        self.assertLocationMatching([])
769
1369
 
770
1370
    def test__get_matching_sections_exact(self):
771
1371
        self.get_branch_config('http://www.example.com')
772
 
        self.assertEqual([('http://www.example.com', '')],
773
 
                         self.my_location_config._get_matching_sections())
 
1372
        self.assertLocationMatching([('http://www.example.com', '')])
774
1373
 
775
1374
    def test__get_matching_sections_suffix_does_not(self):
776
1375
        self.get_branch_config('http://www.example.com-com')
777
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1376
        self.assertLocationMatching([])
778
1377
 
779
1378
    def test__get_matching_sections_subdir_recursive(self):
780
1379
        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())
 
1380
        self.assertLocationMatching([('http://www.example.com', 'com')])
783
1381
 
784
1382
    def test__get_matching_sections_ignoreparent(self):
785
1383
        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())
 
1384
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1385
                                      '')])
788
1386
 
789
1387
    def test__get_matching_sections_ignoreparent_subdir(self):
790
1388
        self.get_branch_config(
791
1389
            'http://www.example.com/ignoreparent/childbranch')
792
 
        self.assertEqual([('http://www.example.com/ignoreparent',
793
 
                           'childbranch')],
794
 
                         self.my_location_config._get_matching_sections())
 
1390
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1391
                                      'childbranch')])
795
1392
 
796
1393
    def test__get_matching_sections_subdir_trailing_slash(self):
797
1394
        self.get_branch_config('/b')
798
 
        self.assertEqual([('/b/', '')],
799
 
                         self.my_location_config._get_matching_sections())
 
1395
        self.assertLocationMatching([('/b/', '')])
800
1396
 
801
1397
    def test__get_matching_sections_subdir_child(self):
802
1398
        self.get_branch_config('/a/foo')
803
 
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
804
 
                         self.my_location_config._get_matching_sections())
 
1399
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
805
1400
 
806
1401
    def test__get_matching_sections_subdir_child_child(self):
807
1402
        self.get_branch_config('/a/foo/bar')
808
 
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
809
 
                         self.my_location_config._get_matching_sections())
 
1403
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
810
1404
 
811
1405
    def test__get_matching_sections_trailing_slash_with_children(self):
812
1406
        self.get_branch_config('/a/')
813
 
        self.assertEqual([('/a/', '')],
814
 
                         self.my_location_config._get_matching_sections())
 
1407
        self.assertLocationMatching([('/a/', '')])
815
1408
 
816
1409
    def test__get_matching_sections_explicit_over_glob(self):
817
1410
        # XXX: 2006-09-08 jamesh
819
1412
        # was a config section for '/a/?', it would get precedence
820
1413
        # over '/a/c'.
821
1414
        self.get_branch_config('/a/c')
822
 
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
823
 
                         self.my_location_config._get_matching_sections())
 
1415
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
824
1416
 
825
1417
    def test__get_option_policy_normal(self):
826
1418
        self.get_branch_config('http://www.example.com')
848
1440
            'http://www.example.com', 'appendpath_option'),
849
1441
            config.POLICY_APPENDPATH)
850
1442
 
 
1443
    def test__get_options_with_policy(self):
 
1444
        self.get_branch_config('/dir/subdir',
 
1445
                               location_config="""\
 
1446
[/dir]
 
1447
other_url = /other-dir
 
1448
other_url:policy = appendpath
 
1449
[/dir/subdir]
 
1450
other_url = /other-subdir
 
1451
""")
 
1452
        self.assertOptions(
 
1453
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
 
1454
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
 
1455
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
 
1456
            self.my_location_config)
 
1457
 
851
1458
    def test_location_without_username(self):
852
1459
        self.get_branch_config('http://www.example.com/ignoreparent')
853
1460
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
989
1596
        self.assertEqual('bzrlib.tests.test_config.post_commit',
990
1597
                         self.my_config.post_commit())
991
1598
 
992
 
    def get_branch_config(self, location, global_config=None):
 
1599
    def get_branch_config(self, location, global_config=None,
 
1600
                          location_config=None):
 
1601
        my_branch = FakeBranch(location)
993
1602
        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)
 
1603
            global_config = sample_config_text
 
1604
        if location_config is None:
 
1605
            location_config = sample_branches_text
 
1606
 
 
1607
        my_global_config = config.GlobalConfig.from_string(global_config,
 
1608
                                                           save=True)
 
1609
        my_location_config = config.LocationConfig.from_string(
 
1610
            location_config, my_branch.base, save=True)
 
1611
        my_config = config.BranchConfig(my_branch)
 
1612
        self.my_config = my_config
 
1613
        self.my_location_config = my_config._get_location_config()
1004
1614
 
1005
1615
    def test_set_user_setting_sets_and_saves(self):
1006
1616
        self.get_branch_config('/a/c')
1007
1617
        record = InstrumentedConfigObj("foo")
1008
1618
        self.my_location_config._parser = record
1009
1619
 
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'),
 
1620
        self.callDeprecated(['The recurse option is deprecated as of '
 
1621
                             '0.14.  The section "/a/c" has been '
 
1622
                             'converted to use policies.'],
 
1623
                            self.my_config.set_user_option,
 
1624
                            'foo', 'bar', store=config.STORE_LOCATION)
 
1625
        self.assertEqual([('reload',),
 
1626
                          ('__contains__', '/a/c'),
1029
1627
                          ('__contains__', '/a/c/'),
1030
1628
                          ('__setitem__', '/a/c', {}),
1031
1629
                          ('__getitem__', '/a/c'),
1060
1658
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1061
1659
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1062
1660
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1063
 
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
1661
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1064
1662
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1065
1663
 
1066
1664
 
1074
1672
option = exact
1075
1673
"""
1076
1674
 
1077
 
 
1078
1675
class TestBranchConfigItems(tests.TestCaseInTempDir):
1079
1676
 
1080
1677
    def get_branch_config(self, global_config=None, location=None,
1081
1678
                          location_config=None, branch_data_config=None):
1082
 
        my_config = config.BranchConfig(FakeBranch(location))
 
1679
        my_branch = FakeBranch(location)
1083
1680
        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()
 
1681
            my_global_config = config.GlobalConfig.from_string(global_config,
 
1682
                                                               save=True)
1087
1683
        if location_config is not None:
1088
 
            location_file = StringIO(location_config.encode('utf-8'))
1089
 
            self.my_location_config._get_parser(location_file)
 
1684
            my_location_config = config.LocationConfig.from_string(
 
1685
                location_config, my_branch.base, save=True)
 
1686
        my_config = config.BranchConfig(my_branch)
1090
1687
        if branch_data_config is not None:
1091
1688
            my_config.branch.control_files.files['branch.conf'] = \
1092
1689
                branch_data_config
1106
1703
                         my_config.username())
1107
1704
 
1108
1705
    def test_not_set_in_branch(self):
1109
 
        my_config = self.get_branch_config(sample_config_text)
 
1706
        my_config = self.get_branch_config(global_config=sample_config_text)
1110
1707
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1111
1708
                         my_config._get_user_id())
1112
1709
        my_config.branch.control_files.files['email'] = "John"
1113
1710
        self.assertEqual("John", my_config._get_user_id())
1114
1711
 
1115
1712
    def test_BZR_EMAIL_OVERRIDES(self):
1116
 
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
 
1713
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1117
1714
        branch = FakeBranch()
1118
1715
        my_config = config.BranchConfig(branch)
1119
1716
        self.assertEqual("Robert Collins <robertc@example.org>",
1136
1733
 
1137
1734
    def test_gpg_signing_command(self):
1138
1735
        my_config = self.get_branch_config(
 
1736
            global_config=sample_config_text,
1139
1737
            # branch data cannot set gpg_signing_command
1140
1738
            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
1739
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1144
1740
 
1145
1741
    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))
 
1742
        my_config = self.get_branch_config(global_config=sample_config_text)
1150
1743
        self.assertEqual('something',
1151
1744
                         my_config.get_user_option('user_global_option'))
1152
1745
 
1153
1746
    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)
 
1747
        my_config = self.get_branch_config(global_config=sample_config_text,
 
1748
                                      location='/a/c',
 
1749
                                      location_config=sample_branches_text)
1157
1750
        self.assertEqual(my_config.branch.base, '/a/c')
1158
1751
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1159
1752
                         my_config.post_commit())
1160
1753
        my_config.set_user_option('post_commit', 'rmtree_root')
1161
 
        # post-commit is ignored when bresent in branch data
 
1754
        # post-commit is ignored when present in branch data
1162
1755
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1163
1756
                         my_config.post_commit())
1164
1757
        my_config.set_user_option('post_commit', 'rmtree_root',
1166
1759
        self.assertEqual('rmtree_root', my_config.post_commit())
1167
1760
 
1168
1761
    def test_config_precedence(self):
 
1762
        # FIXME: eager test, luckily no persitent config file makes it fail
 
1763
        # -- vila 20100716
1169
1764
        my_config = self.get_branch_config(global_config=precedence_global)
1170
1765
        self.assertEqual(my_config.get_user_option('option'), 'global')
1171
1766
        my_config = self.get_branch_config(global_config=precedence_global,
1172
 
                                      branch_data_config=precedence_branch)
 
1767
                                           branch_data_config=precedence_branch)
1173
1768
        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)
 
1769
        my_config = self.get_branch_config(
 
1770
            global_config=precedence_global,
 
1771
            branch_data_config=precedence_branch,
 
1772
            location_config=precedence_location)
1177
1773
        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')
 
1774
        my_config = self.get_branch_config(
 
1775
            global_config=precedence_global,
 
1776
            branch_data_config=precedence_branch,
 
1777
            location_config=precedence_location,
 
1778
            location='http://example.com/specific')
1182
1779
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1183
1780
 
1184
1781
    def test_get_mail_client(self):
1312
1909
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1313
1910
 
1314
1911
 
 
1912
class TestOldConfigHooks(tests.TestCaseWithTransport):
 
1913
 
 
1914
    def setUp(self):
 
1915
        super(TestOldConfigHooks, self).setUp()
 
1916
        create_configs_with_file_option(self)
 
1917
 
 
1918
    def assertGetHook(self, conf, name, value):
 
1919
        calls = []
 
1920
        def hook(*args):
 
1921
            calls.append(args)
 
1922
        config.OldConfigHooks.install_named_hook('get', hook, None)
 
1923
        self.addCleanup(
 
1924
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
 
1925
        self.assertLength(0, calls)
 
1926
        actual_value = conf.get_user_option(name)
 
1927
        self.assertEquals(value, actual_value)
 
1928
        self.assertLength(1, calls)
 
1929
        self.assertEquals((conf, name, value), calls[0])
 
1930
 
 
1931
    def test_get_hook_bazaar(self):
 
1932
        self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
 
1933
 
 
1934
    def test_get_hook_locations(self):
 
1935
        self.assertGetHook(self.locations_config, 'file', 'locations')
 
1936
 
 
1937
    def test_get_hook_branch(self):
 
1938
        # Since locations masks branch, we define a different option
 
1939
        self.branch_config.set_user_option('file2', 'branch')
 
1940
        self.assertGetHook(self.branch_config, 'file2', 'branch')
 
1941
 
 
1942
    def assertSetHook(self, conf, name, value):
 
1943
        calls = []
 
1944
        def hook(*args):
 
1945
            calls.append(args)
 
1946
        config.OldConfigHooks.install_named_hook('set', hook, None)
 
1947
        self.addCleanup(
 
1948
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
 
1949
        self.assertLength(0, calls)
 
1950
        conf.set_user_option(name, value)
 
1951
        self.assertLength(1, calls)
 
1952
        # We can't assert the conf object below as different configs use
 
1953
        # different means to implement set_user_option and we care only about
 
1954
        # coverage here.
 
1955
        self.assertEquals((name, value), calls[0][1:])
 
1956
 
 
1957
    def test_set_hook_bazaar(self):
 
1958
        self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
 
1959
 
 
1960
    def test_set_hook_locations(self):
 
1961
        self.assertSetHook(self.locations_config, 'foo', 'locations')
 
1962
 
 
1963
    def test_set_hook_branch(self):
 
1964
        self.assertSetHook(self.branch_config, 'foo', 'branch')
 
1965
 
 
1966
    def assertRemoveHook(self, conf, name, section_name=None):
 
1967
        calls = []
 
1968
        def hook(*args):
 
1969
            calls.append(args)
 
1970
        config.OldConfigHooks.install_named_hook('remove', hook, None)
 
1971
        self.addCleanup(
 
1972
            config.OldConfigHooks.uninstall_named_hook, 'remove', None)
 
1973
        self.assertLength(0, calls)
 
1974
        conf.remove_user_option(name, section_name)
 
1975
        self.assertLength(1, calls)
 
1976
        # We can't assert the conf object below as different configs use
 
1977
        # different means to implement remove_user_option and we care only about
 
1978
        # coverage here.
 
1979
        self.assertEquals((name,), calls[0][1:])
 
1980
 
 
1981
    def test_remove_hook_bazaar(self):
 
1982
        self.assertRemoveHook(self.bazaar_config, 'file')
 
1983
 
 
1984
    def test_remove_hook_locations(self):
 
1985
        self.assertRemoveHook(self.locations_config, 'file',
 
1986
                              self.locations_config.location)
 
1987
 
 
1988
    def test_remove_hook_branch(self):
 
1989
        self.assertRemoveHook(self.branch_config, 'file')
 
1990
 
 
1991
    def assertLoadHook(self, name, conf_class, *conf_args):
 
1992
        calls = []
 
1993
        def hook(*args):
 
1994
            calls.append(args)
 
1995
        config.OldConfigHooks.install_named_hook('load', hook, None)
 
1996
        self.addCleanup(
 
1997
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
 
1998
        self.assertLength(0, calls)
 
1999
        # Build a config
 
2000
        conf = conf_class(*conf_args)
 
2001
        # Access an option to trigger a load
 
2002
        conf.get_user_option(name)
 
2003
        self.assertLength(1, calls)
 
2004
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2005
 
 
2006
    def test_load_hook_bazaar(self):
 
2007
        self.assertLoadHook('file', config.GlobalConfig)
 
2008
 
 
2009
    def test_load_hook_locations(self):
 
2010
        self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
 
2011
 
 
2012
    def test_load_hook_branch(self):
 
2013
        self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
 
2014
 
 
2015
    def assertSaveHook(self, conf):
 
2016
        calls = []
 
2017
        def hook(*args):
 
2018
            calls.append(args)
 
2019
        config.OldConfigHooks.install_named_hook('save', hook, None)
 
2020
        self.addCleanup(
 
2021
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
 
2022
        self.assertLength(0, calls)
 
2023
        # Setting an option triggers a save
 
2024
        conf.set_user_option('foo', 'bar')
 
2025
        self.assertLength(1, calls)
 
2026
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2027
 
 
2028
    def test_save_hook_bazaar(self):
 
2029
        self.assertSaveHook(self.bazaar_config)
 
2030
 
 
2031
    def test_save_hook_locations(self):
 
2032
        self.assertSaveHook(self.locations_config)
 
2033
 
 
2034
    def test_save_hook_branch(self):
 
2035
        self.assertSaveHook(self.branch_config)
 
2036
 
 
2037
 
 
2038
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
 
2039
    """Tests config hooks for remote configs.
 
2040
 
 
2041
    No tests for the remove hook as this is not implemented there.
 
2042
    """
 
2043
 
 
2044
    def setUp(self):
 
2045
        super(TestOldConfigHooksForRemote, self).setUp()
 
2046
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2047
        create_configs_with_file_option(self)
 
2048
 
 
2049
    def assertGetHook(self, conf, name, value):
 
2050
        calls = []
 
2051
        def hook(*args):
 
2052
            calls.append(args)
 
2053
        config.OldConfigHooks.install_named_hook('get', hook, None)
 
2054
        self.addCleanup(
 
2055
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
 
2056
        self.assertLength(0, calls)
 
2057
        actual_value = conf.get_option(name)
 
2058
        self.assertEquals(value, actual_value)
 
2059
        self.assertLength(1, calls)
 
2060
        self.assertEquals((conf, name, value), calls[0])
 
2061
 
 
2062
    def test_get_hook_remote_branch(self):
 
2063
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2064
        self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
 
2065
 
 
2066
    def test_get_hook_remote_bzrdir(self):
 
2067
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2068
        conf = remote_bzrdir._get_config()
 
2069
        conf.set_option('remotedir', 'file')
 
2070
        self.assertGetHook(conf, 'file', 'remotedir')
 
2071
 
 
2072
    def assertSetHook(self, conf, name, value):
 
2073
        calls = []
 
2074
        def hook(*args):
 
2075
            calls.append(args)
 
2076
        config.OldConfigHooks.install_named_hook('set', hook, None)
 
2077
        self.addCleanup(
 
2078
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
 
2079
        self.assertLength(0, calls)
 
2080
        conf.set_option(value, name)
 
2081
        self.assertLength(1, calls)
 
2082
        # We can't assert the conf object below as different configs use
 
2083
        # different means to implement set_user_option and we care only about
 
2084
        # coverage here.
 
2085
        self.assertEquals((name, value), calls[0][1:])
 
2086
 
 
2087
    def test_set_hook_remote_branch(self):
 
2088
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2089
        self.addCleanup(remote_branch.lock_write().unlock)
 
2090
        self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
 
2091
 
 
2092
    def test_set_hook_remote_bzrdir(self):
 
2093
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2094
        self.addCleanup(remote_branch.lock_write().unlock)
 
2095
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2096
        self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
 
2097
 
 
2098
    def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
 
2099
        calls = []
 
2100
        def hook(*args):
 
2101
            calls.append(args)
 
2102
        config.OldConfigHooks.install_named_hook('load', hook, None)
 
2103
        self.addCleanup(
 
2104
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
 
2105
        self.assertLength(0, calls)
 
2106
        # Build a config
 
2107
        conf = conf_class(*conf_args)
 
2108
        # Access an option to trigger a load
 
2109
        conf.get_option(name)
 
2110
        self.assertLength(expected_nb_calls, calls)
 
2111
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2112
 
 
2113
    def test_load_hook_remote_branch(self):
 
2114
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2115
        self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
 
2116
 
 
2117
    def test_load_hook_remote_bzrdir(self):
 
2118
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2119
        # The config file doesn't exist, set an option to force its creation
 
2120
        conf = remote_bzrdir._get_config()
 
2121
        conf.set_option('remotedir', 'file')
 
2122
        # We get one call for the server and one call for the client, this is
 
2123
        # caused by the differences in implementations betwen
 
2124
        # SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
 
2125
        # SmartServerBranchGetConfigFile (in smart/branch.py)
 
2126
        self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
 
2127
 
 
2128
    def assertSaveHook(self, conf):
 
2129
        calls = []
 
2130
        def hook(*args):
 
2131
            calls.append(args)
 
2132
        config.OldConfigHooks.install_named_hook('save', hook, None)
 
2133
        self.addCleanup(
 
2134
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
 
2135
        self.assertLength(0, calls)
 
2136
        # Setting an option triggers a save
 
2137
        conf.set_option('foo', 'bar')
 
2138
        self.assertLength(1, calls)
 
2139
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2140
 
 
2141
    def test_save_hook_remote_branch(self):
 
2142
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2143
        self.addCleanup(remote_branch.lock_write().unlock)
 
2144
        self.assertSaveHook(remote_branch._get_config())
 
2145
 
 
2146
    def test_save_hook_remote_bzrdir(self):
 
2147
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2148
        self.addCleanup(remote_branch.lock_write().unlock)
 
2149
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2150
        self.assertSaveHook(remote_bzrdir._get_config())
 
2151
 
 
2152
 
 
2153
class TestOption(tests.TestCase):
 
2154
 
 
2155
    def test_default_value(self):
 
2156
        opt = config.Option('foo', default='bar')
 
2157
        self.assertEquals('bar', opt.get_default())
 
2158
 
 
2159
 
 
2160
class TestOptionRegistry(tests.TestCase):
 
2161
 
 
2162
    def setUp(self):
 
2163
        super(TestOptionRegistry, self).setUp()
 
2164
        # Always start with an empty registry
 
2165
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
2166
        self.registry = config.option_registry
 
2167
 
 
2168
    def test_register(self):
 
2169
        opt = config.Option('foo')
 
2170
        self.registry.register('foo', opt)
 
2171
        self.assertIs(opt, self.registry.get('foo'))
 
2172
 
 
2173
    lazy_option = config.Option('lazy_foo')
 
2174
 
 
2175
    def test_register_lazy(self):
 
2176
        self.registry.register_lazy('foo', self.__module__,
 
2177
                                    'TestOptionRegistry.lazy_option')
 
2178
        self.assertIs(self.lazy_option, self.registry.get('foo'))
 
2179
 
 
2180
    def test_registered_help(self):
 
2181
        opt = config.Option('foo')
 
2182
        self.registry.register('foo', opt, help='A simple option')
 
2183
        self.assertEquals('A simple option', self.registry.get_help('foo'))
 
2184
 
 
2185
 
 
2186
class TestRegisteredOptions(tests.TestCase):
 
2187
    """All registered options should verify some constraints."""
 
2188
 
 
2189
    scenarios = [(key, {'option_name': key, 'option': option}) for key, option
 
2190
                 in config.option_registry.iteritems()]
 
2191
 
 
2192
    def setUp(self):
 
2193
        super(TestRegisteredOptions, self).setUp()
 
2194
        self.registry = config.option_registry
 
2195
 
 
2196
    def test_proper_name(self):
 
2197
        # An option should be registered under its own name, this can't be
 
2198
        # checked at registration time for the lazy ones.
 
2199
        self.assertEquals(self.option_name, self.option.name)
 
2200
 
 
2201
    def test_help_is_set(self):
 
2202
        option_help = self.registry.get_help(self.option_name)
 
2203
        self.assertNotEquals(None, option_help)
 
2204
        # Come on, think about the user, he really wants to know whst the
 
2205
        # option is about
 
2206
        self.assertNotEquals('', option_help)
 
2207
 
 
2208
 
 
2209
class TestSection(tests.TestCase):
 
2210
 
 
2211
    # FIXME: Parametrize so that all sections produced by Stores run these
 
2212
    # tests -- vila 2011-04-01
 
2213
 
 
2214
    def test_get_a_value(self):
 
2215
        a_dict = dict(foo='bar')
 
2216
        section = config.Section('myID', a_dict)
 
2217
        self.assertEquals('bar', section.get('foo'))
 
2218
 
 
2219
    def test_get_unknown_option(self):
 
2220
        a_dict = dict()
 
2221
        section = config.Section(None, a_dict)
 
2222
        self.assertEquals('out of thin air',
 
2223
                          section.get('foo', 'out of thin air'))
 
2224
 
 
2225
    def test_options_is_shared(self):
 
2226
        a_dict = dict()
 
2227
        section = config.Section(None, a_dict)
 
2228
        self.assertIs(a_dict, section.options)
 
2229
 
 
2230
 
 
2231
class TestMutableSection(tests.TestCase):
 
2232
 
 
2233
    # FIXME: Parametrize so that all sections (including os.environ and the
 
2234
    # ones produced by Stores) run these tests -- vila 2011-04-01
 
2235
 
 
2236
    def test_set(self):
 
2237
        a_dict = dict(foo='bar')
 
2238
        section = config.MutableSection('myID', a_dict)
 
2239
        section.set('foo', 'new_value')
 
2240
        self.assertEquals('new_value', section.get('foo'))
 
2241
        # The change appears in the shared section
 
2242
        self.assertEquals('new_value', a_dict.get('foo'))
 
2243
        # We keep track of the change
 
2244
        self.assertTrue('foo' in section.orig)
 
2245
        self.assertEquals('bar', section.orig.get('foo'))
 
2246
 
 
2247
    def test_set_preserve_original_once(self):
 
2248
        a_dict = dict(foo='bar')
 
2249
        section = config.MutableSection('myID', a_dict)
 
2250
        section.set('foo', 'first_value')
 
2251
        section.set('foo', 'second_value')
 
2252
        # We keep track of the original value
 
2253
        self.assertTrue('foo' in section.orig)
 
2254
        self.assertEquals('bar', section.orig.get('foo'))
 
2255
 
 
2256
    def test_remove(self):
 
2257
        a_dict = dict(foo='bar')
 
2258
        section = config.MutableSection('myID', a_dict)
 
2259
        section.remove('foo')
 
2260
        # We get None for unknown options via the default value
 
2261
        self.assertEquals(None, section.get('foo'))
 
2262
        # Or we just get the default value
 
2263
        self.assertEquals('unknown', section.get('foo', 'unknown'))
 
2264
        self.assertFalse('foo' in section.options)
 
2265
        # We keep track of the deletion
 
2266
        self.assertTrue('foo' in section.orig)
 
2267
        self.assertEquals('bar', section.orig.get('foo'))
 
2268
 
 
2269
    def test_remove_new_option(self):
 
2270
        a_dict = dict()
 
2271
        section = config.MutableSection('myID', a_dict)
 
2272
        section.set('foo', 'bar')
 
2273
        section.remove('foo')
 
2274
        self.assertFalse('foo' in section.options)
 
2275
        # The option didn't exist initially so it we need to keep track of it
 
2276
        # with a special value
 
2277
        self.assertTrue('foo' in section.orig)
 
2278
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
 
2279
 
 
2280
 
 
2281
class TestStore(tests.TestCaseWithTransport):
 
2282
 
 
2283
    def assertSectionContent(self, expected, section):
 
2284
        """Assert that some options have the proper values in a section."""
 
2285
        expected_name, expected_options = expected
 
2286
        self.assertEquals(expected_name, section.id)
 
2287
        self.assertEquals(
 
2288
            expected_options,
 
2289
            dict([(k, section.get(k)) for k in expected_options.keys()]))
 
2290
 
 
2291
 
 
2292
class TestReadonlyStore(TestStore):
 
2293
 
 
2294
    scenarios = [(key, {'get_store': builder}) for key, builder
 
2295
                 in config.test_store_builder_registry.iteritems()]
 
2296
 
 
2297
    def setUp(self):
 
2298
        super(TestReadonlyStore, self).setUp()
 
2299
 
 
2300
    def test_building_delays_load(self):
 
2301
        store = self.get_store(self)
 
2302
        self.assertEquals(False, store.is_loaded())
 
2303
        store._load_from_string('')
 
2304
        self.assertEquals(True, store.is_loaded())
 
2305
 
 
2306
    def test_get_no_sections_for_empty(self):
 
2307
        store = self.get_store(self)
 
2308
        store._load_from_string('')
 
2309
        self.assertEquals([], list(store.get_sections()))
 
2310
 
 
2311
    def test_get_default_section(self):
 
2312
        store = self.get_store(self)
 
2313
        store._load_from_string('foo=bar')
 
2314
        sections = list(store.get_sections())
 
2315
        self.assertLength(1, sections)
 
2316
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2317
 
 
2318
    def test_get_named_section(self):
 
2319
        store = self.get_store(self)
 
2320
        store._load_from_string('[baz]\nfoo=bar')
 
2321
        sections = list(store.get_sections())
 
2322
        self.assertLength(1, sections)
 
2323
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
2324
 
 
2325
    def test_load_from_string_fails_for_non_empty_store(self):
 
2326
        store = self.get_store(self)
 
2327
        store._load_from_string('foo=bar')
 
2328
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
 
2329
 
 
2330
 
 
2331
class TestMutableStore(TestStore):
 
2332
 
 
2333
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
 
2334
                 in config.test_store_builder_registry.iteritems()]
 
2335
 
 
2336
    def setUp(self):
 
2337
        super(TestMutableStore, self).setUp()
 
2338
        self.transport = self.get_transport()
 
2339
 
 
2340
    def has_store(self, store):
 
2341
        store_basename = urlutils.relative_url(self.transport.external_url(),
 
2342
                                               store.external_url())
 
2343
        return self.transport.has(store_basename)
 
2344
 
 
2345
    def test_save_empty_creates_no_file(self):
 
2346
        # FIXME: There should be a better way than relying on the test
 
2347
        # parametrization to identify branch.conf -- vila 2011-0526
 
2348
        if self.store_id in ('branch', 'remote_branch'):
 
2349
            raise tests.TestNotApplicable(
 
2350
                'branch.conf is *always* created when a branch is initialized')
 
2351
        store = self.get_store(self)
 
2352
        store.save()
 
2353
        self.assertEquals(False, self.has_store(store))
 
2354
 
 
2355
    def test_save_emptied_succeeds(self):
 
2356
        store = self.get_store(self)
 
2357
        store._load_from_string('foo=bar\n')
 
2358
        section = store.get_mutable_section(None)
 
2359
        section.remove('foo')
 
2360
        store.save()
 
2361
        self.assertEquals(True, self.has_store(store))
 
2362
        modified_store = self.get_store(self)
 
2363
        sections = list(modified_store.get_sections())
 
2364
        self.assertLength(0, sections)
 
2365
 
 
2366
    def test_save_with_content_succeeds(self):
 
2367
        # FIXME: There should be a better way than relying on the test
 
2368
        # parametrization to identify branch.conf -- vila 2011-0526
 
2369
        if self.store_id in ('branch', 'remote_branch'):
 
2370
            raise tests.TestNotApplicable(
 
2371
                'branch.conf is *always* created when a branch is initialized')
 
2372
        store = self.get_store(self)
 
2373
        store._load_from_string('foo=bar\n')
 
2374
        self.assertEquals(False, self.has_store(store))
 
2375
        store.save()
 
2376
        self.assertEquals(True, self.has_store(store))
 
2377
        modified_store = self.get_store(self)
 
2378
        sections = list(modified_store.get_sections())
 
2379
        self.assertLength(1, sections)
 
2380
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2381
 
 
2382
    def test_set_option_in_empty_store(self):
 
2383
        store = self.get_store(self)
 
2384
        section = store.get_mutable_section(None)
 
2385
        section.set('foo', 'bar')
 
2386
        store.save()
 
2387
        modified_store = self.get_store(self)
 
2388
        sections = list(modified_store.get_sections())
 
2389
        self.assertLength(1, sections)
 
2390
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2391
 
 
2392
    def test_set_option_in_default_section(self):
 
2393
        store = self.get_store(self)
 
2394
        store._load_from_string('')
 
2395
        section = store.get_mutable_section(None)
 
2396
        section.set('foo', 'bar')
 
2397
        store.save()
 
2398
        modified_store = self.get_store(self)
 
2399
        sections = list(modified_store.get_sections())
 
2400
        self.assertLength(1, sections)
 
2401
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2402
 
 
2403
    def test_set_option_in_named_section(self):
 
2404
        store = self.get_store(self)
 
2405
        store._load_from_string('')
 
2406
        section = store.get_mutable_section('baz')
 
2407
        section.set('foo', 'bar')
 
2408
        store.save()
 
2409
        modified_store = self.get_store(self)
 
2410
        sections = list(modified_store.get_sections())
 
2411
        self.assertLength(1, sections)
 
2412
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
2413
 
 
2414
    def test_load_hook(self):
 
2415
        # We first needs to ensure that the store exists
 
2416
        store = self.get_store(self)
 
2417
        section = store.get_mutable_section('baz')
 
2418
        section.set('foo', 'bar')
 
2419
        store.save()
 
2420
        # Now we can try to load it
 
2421
        store = self.get_store(self)
 
2422
        calls = []
 
2423
        def hook(*args):
 
2424
            calls.append(args)
 
2425
        config.ConfigHooks.install_named_hook('load', hook, None)
 
2426
        self.assertLength(0, calls)
 
2427
        store.load()
 
2428
        self.assertLength(1, calls)
 
2429
        self.assertEquals((store,), calls[0])
 
2430
 
 
2431
    def test_save_hook(self):
 
2432
        calls = []
 
2433
        def hook(*args):
 
2434
            calls.append(args)
 
2435
        config.ConfigHooks.install_named_hook('save', hook, None)
 
2436
        self.assertLength(0, calls)
 
2437
        store = self.get_store(self)
 
2438
        section = store.get_mutable_section('baz')
 
2439
        section.set('foo', 'bar')
 
2440
        store.save()
 
2441
        self.assertLength(1, calls)
 
2442
        self.assertEquals((store,), calls[0])
 
2443
 
 
2444
 
 
2445
class TestIniFileStore(TestStore):
 
2446
 
 
2447
    def test_loading_unknown_file_fails(self):
 
2448
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
 
2449
        self.assertRaises(errors.NoSuchFile, store.load)
 
2450
 
 
2451
    def test_invalid_content(self):
 
2452
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
2453
        self.assertEquals(False, store.is_loaded())
 
2454
        exc = self.assertRaises(
 
2455
            errors.ParseConfigError, store._load_from_string,
 
2456
            'this is invalid !')
 
2457
        self.assertEndsWith(exc.filename, 'foo.conf')
 
2458
        # And the load failed
 
2459
        self.assertEquals(False, store.is_loaded())
 
2460
 
 
2461
    def test_get_embedded_sections(self):
 
2462
        # A more complicated example (which also shows that section names and
 
2463
        # option names share the same name space...)
 
2464
        # FIXME: This should be fixed by forbidding dicts as values ?
 
2465
        # -- vila 2011-04-05
 
2466
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
2467
        store._load_from_string('''
 
2468
foo=bar
 
2469
l=1,2
 
2470
[DEFAULT]
 
2471
foo_in_DEFAULT=foo_DEFAULT
 
2472
[bar]
 
2473
foo_in_bar=barbar
 
2474
[baz]
 
2475
foo_in_baz=barbaz
 
2476
[[qux]]
 
2477
foo_in_qux=quux
 
2478
''')
 
2479
        sections = list(store.get_sections())
 
2480
        self.assertLength(4, sections)
 
2481
        # The default section has no name.
 
2482
        # List values are provided as lists
 
2483
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
 
2484
                                  sections[0])
 
2485
        self.assertSectionContent(
 
2486
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
 
2487
        self.assertSectionContent(
 
2488
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
 
2489
        # sub sections are provided as embedded dicts.
 
2490
        self.assertSectionContent(
 
2491
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
 
2492
            sections[3])
 
2493
 
 
2494
 
 
2495
class TestLockableIniFileStore(TestStore):
 
2496
 
 
2497
    def test_create_store_in_created_dir(self):
 
2498
        self.assertPathDoesNotExist('dir')
 
2499
        t = self.get_transport('dir/subdir')
 
2500
        store = config.LockableIniFileStore(t, 'foo.conf')
 
2501
        store.get_mutable_section(None).set('foo', 'bar')
 
2502
        store.save()
 
2503
        self.assertPathExists('dir/subdir')
 
2504
 
 
2505
 
 
2506
class TestConcurrentStoreUpdates(TestStore):
 
2507
    """Test that Stores properly handle conccurent updates.
 
2508
 
 
2509
    New Store implementation may fail some of these tests but until such
 
2510
    implementations exist it's hard to properly filter them from the scenarios
 
2511
    applied here. If you encounter such a case, contact the bzr devs.
 
2512
    """
 
2513
 
 
2514
    scenarios = [(key, {'get_stack': builder}) for key, builder
 
2515
                 in config.test_stack_builder_registry.iteritems()]
 
2516
 
 
2517
    def setUp(self):
 
2518
        super(TestConcurrentStoreUpdates, self).setUp()
 
2519
        self._content = 'one=1\ntwo=2\n'
 
2520
        self.stack = self.get_stack(self)
 
2521
        if not isinstance(self.stack, config._CompatibleStack):
 
2522
            raise tests.TestNotApplicable(
 
2523
                '%s is not meant to be compatible with the old config design'
 
2524
                % (self.stack,))
 
2525
        self.stack.store._load_from_string(self._content)
 
2526
        # Flush the store
 
2527
        self.stack.store.save()
 
2528
 
 
2529
    def test_simple_read_access(self):
 
2530
        self.assertEquals('1', self.stack.get('one'))
 
2531
 
 
2532
    def test_simple_write_access(self):
 
2533
        self.stack.set('one', 'one')
 
2534
        self.assertEquals('one', self.stack.get('one'))
 
2535
 
 
2536
    def test_listen_to_the_last_speaker(self):
 
2537
        c1 = self.stack
 
2538
        c2 = self.get_stack(self)
 
2539
        c1.set('one', 'ONE')
 
2540
        c2.set('two', 'TWO')
 
2541
        self.assertEquals('ONE', c1.get('one'))
 
2542
        self.assertEquals('TWO', c2.get('two'))
 
2543
        # The second update respect the first one
 
2544
        self.assertEquals('ONE', c2.get('one'))
 
2545
 
 
2546
    def test_last_speaker_wins(self):
 
2547
        # If the same config is not shared, the same variable modified twice
 
2548
        # can only see a single result.
 
2549
        c1 = self.stack
 
2550
        c2 = self.get_stack(self)
 
2551
        c1.set('one', 'c1')
 
2552
        c2.set('one', 'c2')
 
2553
        self.assertEquals('c2', c2.get('one'))
 
2554
        # The first modification is still available until another refresh
 
2555
        # occur
 
2556
        self.assertEquals('c1', c1.get('one'))
 
2557
        c1.set('two', 'done')
 
2558
        self.assertEquals('c2', c1.get('one'))
 
2559
 
 
2560
    def test_writes_are_serialized(self):
 
2561
        c1 = self.stack
 
2562
        c2 = self.get_stack(self)
 
2563
 
 
2564
        # We spawn a thread that will pause *during* the config saving.
 
2565
        before_writing = threading.Event()
 
2566
        after_writing = threading.Event()
 
2567
        writing_done = threading.Event()
 
2568
        c1_save_without_locking_orig = c1.store.save_without_locking
 
2569
        def c1_save_without_locking():
 
2570
            before_writing.set()
 
2571
            c1_save_without_locking_orig()
 
2572
            # The lock is held. We wait for the main thread to decide when to
 
2573
            # continue
 
2574
            after_writing.wait()
 
2575
        c1.store.save_without_locking = c1_save_without_locking
 
2576
        def c1_set():
 
2577
            c1.set('one', 'c1')
 
2578
            writing_done.set()
 
2579
        t1 = threading.Thread(target=c1_set)
 
2580
        # Collect the thread after the test
 
2581
        self.addCleanup(t1.join)
 
2582
        # Be ready to unblock the thread if the test goes wrong
 
2583
        self.addCleanup(after_writing.set)
 
2584
        t1.start()
 
2585
        before_writing.wait()
 
2586
        self.assertRaises(errors.LockContention,
 
2587
                          c2.set, 'one', 'c2')
 
2588
        self.assertEquals('c1', c1.get('one'))
 
2589
        # Let the lock be released
 
2590
        after_writing.set()
 
2591
        writing_done.wait()
 
2592
        c2.set('one', 'c2')
 
2593
        self.assertEquals('c2', c2.get('one'))
 
2594
 
 
2595
    def test_read_while_writing(self):
 
2596
       c1 = self.stack
 
2597
       # We spawn a thread that will pause *during* the write
 
2598
       ready_to_write = threading.Event()
 
2599
       do_writing = threading.Event()
 
2600
       writing_done = threading.Event()
 
2601
       # We override the _save implementation so we know the store is locked
 
2602
       c1_save_without_locking_orig = c1.store.save_without_locking
 
2603
       def c1_save_without_locking():
 
2604
           ready_to_write.set()
 
2605
           # The lock is held. We wait for the main thread to decide when to
 
2606
           # continue
 
2607
           do_writing.wait()
 
2608
           c1_save_without_locking_orig()
 
2609
           writing_done.set()
 
2610
       c1.store.save_without_locking = c1_save_without_locking
 
2611
       def c1_set():
 
2612
           c1.set('one', 'c1')
 
2613
       t1 = threading.Thread(target=c1_set)
 
2614
       # Collect the thread after the test
 
2615
       self.addCleanup(t1.join)
 
2616
       # Be ready to unblock the thread if the test goes wrong
 
2617
       self.addCleanup(do_writing.set)
 
2618
       t1.start()
 
2619
       # Ensure the thread is ready to write
 
2620
       ready_to_write.wait()
 
2621
       self.assertEquals('c1', c1.get('one'))
 
2622
       # If we read during the write, we get the old value
 
2623
       c2 = self.get_stack(self)
 
2624
       self.assertEquals('1', c2.get('one'))
 
2625
       # Let the writing occur and ensure it occurred
 
2626
       do_writing.set()
 
2627
       writing_done.wait()
 
2628
       # Now we get the updated value
 
2629
       c3 = self.get_stack(self)
 
2630
       self.assertEquals('c1', c3.get('one'))
 
2631
 
 
2632
    # FIXME: It may be worth looking into removing the lock dir when it's not
 
2633
    # needed anymore and look at possible fallouts for concurrent lockers. This
 
2634
    # will matter if/when we use config files outside of bazaar directories
 
2635
    # (.bazaar or .bzr) -- vila 20110-04-11
 
2636
 
 
2637
 
 
2638
class TestSectionMatcher(TestStore):
 
2639
 
 
2640
    scenarios = [('location', {'matcher': config.LocationMatcher})]
 
2641
 
 
2642
    def get_store(self, file_name):
 
2643
        return config.IniFileStore(self.get_readonly_transport(), file_name)
 
2644
 
 
2645
    def test_no_matches_for_empty_stores(self):
 
2646
        store = self.get_store('foo.conf')
 
2647
        store._load_from_string('')
 
2648
        matcher = self.matcher(store, '/bar')
 
2649
        self.assertEquals([], list(matcher.get_sections()))
 
2650
 
 
2651
    def test_build_doesnt_load_store(self):
 
2652
        store = self.get_store('foo.conf')
 
2653
        matcher = self.matcher(store, '/bar')
 
2654
        self.assertFalse(store.is_loaded())
 
2655
 
 
2656
 
 
2657
class TestLocationSection(tests.TestCase):
 
2658
 
 
2659
    def get_section(self, options, extra_path):
 
2660
        section = config.Section('foo', options)
 
2661
        # We don't care about the length so we use '0'
 
2662
        return config.LocationSection(section, 0, extra_path)
 
2663
 
 
2664
    def test_simple_option(self):
 
2665
        section = self.get_section({'foo': 'bar'}, '')
 
2666
        self.assertEquals('bar', section.get('foo'))
 
2667
 
 
2668
    def test_option_with_extra_path(self):
 
2669
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
 
2670
                                   'baz')
 
2671
        self.assertEquals('bar/baz', section.get('foo'))
 
2672
 
 
2673
    def test_invalid_policy(self):
 
2674
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
 
2675
                                   'baz')
 
2676
        # invalid policies are ignored
 
2677
        self.assertEquals('bar', section.get('foo'))
 
2678
 
 
2679
 
 
2680
class TestLocationMatcher(TestStore):
 
2681
 
 
2682
    def get_store(self, file_name):
 
2683
        return config.IniFileStore(self.get_readonly_transport(), file_name)
 
2684
 
 
2685
    def test_more_specific_sections_first(self):
 
2686
        store = self.get_store('foo.conf')
 
2687
        store._load_from_string('''
 
2688
[/foo]
 
2689
section=/foo
 
2690
[/foo/bar]
 
2691
section=/foo/bar
 
2692
''')
 
2693
        self.assertEquals(['/foo', '/foo/bar'],
 
2694
                          [section.id for section in store.get_sections()])
 
2695
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
 
2696
        sections = list(matcher.get_sections())
 
2697
        self.assertEquals([3, 2],
 
2698
                          [section.length for section in sections])
 
2699
        self.assertEquals(['/foo/bar', '/foo'],
 
2700
                          [section.id for section in sections])
 
2701
        self.assertEquals(['baz', 'bar/baz'],
 
2702
                          [section.extra_path for section in sections])
 
2703
 
 
2704
    def test_appendpath_in_no_name_section(self):
 
2705
        # It's a bit weird to allow appendpath in a no-name section, but
 
2706
        # someone may found a use for it
 
2707
        store = self.get_store('foo.conf')
 
2708
        store._load_from_string('''
 
2709
foo=bar
 
2710
foo:policy = appendpath
 
2711
''')
 
2712
        matcher = config.LocationMatcher(store, 'dir/subdir')
 
2713
        sections = list(matcher.get_sections())
 
2714
        self.assertLength(1, sections)
 
2715
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
 
2716
 
 
2717
    def test_file_urls_are_normalized(self):
 
2718
        store = self.get_store('foo.conf')
 
2719
        if sys.platform == 'win32':
 
2720
            expected_url = 'file:///C:/dir/subdir'
 
2721
            expected_location = 'C:/dir/subdir'
 
2722
        else:
 
2723
            expected_url = 'file:///dir/subdir'
 
2724
            expected_location = '/dir/subdir'
 
2725
        matcher = config.LocationMatcher(store, expected_url)
 
2726
        self.assertEquals(expected_location, matcher.location)
 
2727
 
 
2728
 
 
2729
class TestStackGet(tests.TestCase):
 
2730
 
 
2731
    # FIXME: This should be parametrized for all known Stack or dedicated
 
2732
    # paramerized tests created to avoid bloating -- vila 2011-03-31
 
2733
 
 
2734
    def test_single_config_get(self):
 
2735
        conf = dict(foo='bar')
 
2736
        conf_stack = config.Stack([conf])
 
2737
        self.assertEquals('bar', conf_stack.get('foo'))
 
2738
 
 
2739
    def test_get_with_registered_default_value(self):
 
2740
        conf_stack = config.Stack([dict()])
 
2741
        opt = config.Option('foo', default='bar')
 
2742
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
2743
        config.option_registry.register('foo', opt)
 
2744
        self.assertEquals('bar', conf_stack.get('foo'))
 
2745
 
 
2746
    def test_get_without_registered_default_value(self):
 
2747
        conf_stack = config.Stack([dict()])
 
2748
        opt = config.Option('foo')
 
2749
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
2750
        config.option_registry.register('foo', opt)
 
2751
        self.assertEquals(None, conf_stack.get('foo'))
 
2752
 
 
2753
    def test_get_without_default_value_for_not_registered(self):
 
2754
        conf_stack = config.Stack([dict()])
 
2755
        opt = config.Option('foo')
 
2756
        self.overrideAttr(config, 'option_registry', registry.Registry())
 
2757
        self.assertEquals(None, conf_stack.get('foo'))
 
2758
 
 
2759
    def test_get_first_definition(self):
 
2760
        conf1 = dict(foo='bar')
 
2761
        conf2 = dict(foo='baz')
 
2762
        conf_stack = config.Stack([conf1, conf2])
 
2763
        self.assertEquals('bar', conf_stack.get('foo'))
 
2764
 
 
2765
    def test_get_embedded_definition(self):
 
2766
        conf1 = dict(yy='12')
 
2767
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
 
2768
        conf_stack = config.Stack([conf1, conf2])
 
2769
        self.assertEquals('baz', conf_stack.get('foo'))
 
2770
 
 
2771
    def test_get_for_empty_section_callable(self):
 
2772
        conf_stack = config.Stack([lambda : []])
 
2773
        self.assertEquals(None, conf_stack.get('foo'))
 
2774
 
 
2775
    def test_get_for_broken_callable(self):
 
2776
        # Trying to use and invalid callable raises an exception on first use
 
2777
        conf_stack = config.Stack([lambda : object()])
 
2778
        self.assertRaises(TypeError, conf_stack.get, 'foo')
 
2779
 
 
2780
 
 
2781
class TestStackWithTransport(tests.TestCaseWithTransport):
 
2782
 
 
2783
    scenarios = [(key, {'get_stack': builder}) for key, builder
 
2784
                 in config.test_stack_builder_registry.iteritems()]
 
2785
 
 
2786
 
 
2787
class TestConcreteStacks(TestStackWithTransport):
 
2788
 
 
2789
    def test_build_stack(self):
 
2790
        # Just a smoke test to help debug builders
 
2791
        stack = self.get_stack(self)
 
2792
 
 
2793
 
 
2794
class TestStackGet(TestStackWithTransport):
 
2795
 
 
2796
    def test_get_for_empty_stack(self):
 
2797
        conf = self.get_stack(self)
 
2798
        self.assertEquals(None, conf.get('foo'))
 
2799
 
 
2800
    def test_get_hook(self):
 
2801
        conf = self.get_stack(self)
 
2802
        conf.store._load_from_string('foo=bar')
 
2803
        calls = []
 
2804
        def hook(*args):
 
2805
            calls.append(args)
 
2806
        config.ConfigHooks.install_named_hook('get', hook, None)
 
2807
        self.assertLength(0, calls)
 
2808
        value = conf.get('foo')
 
2809
        self.assertEquals('bar', value)
 
2810
        self.assertLength(1, calls)
 
2811
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
 
2812
 
 
2813
 
 
2814
class TestStackSet(TestStackWithTransport):
 
2815
 
 
2816
    def test_simple_set(self):
 
2817
        conf = self.get_stack(self)
 
2818
        conf.store._load_from_string('foo=bar')
 
2819
        self.assertEquals('bar', conf.get('foo'))
 
2820
        conf.set('foo', 'baz')
 
2821
        # Did we get it back ?
 
2822
        self.assertEquals('baz', conf.get('foo'))
 
2823
 
 
2824
    def test_set_creates_a_new_section(self):
 
2825
        conf = self.get_stack(self)
 
2826
        conf.set('foo', 'baz')
 
2827
        self.assertEquals, 'baz', conf.get('foo')
 
2828
 
 
2829
    def test_set_hook(self):
 
2830
        calls = []
 
2831
        def hook(*args):
 
2832
            calls.append(args)
 
2833
        config.ConfigHooks.install_named_hook('set', hook, None)
 
2834
        self.assertLength(0, calls)
 
2835
        conf = self.get_stack(self)
 
2836
        conf.set('foo', 'bar')
 
2837
        self.assertLength(1, calls)
 
2838
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
 
2839
 
 
2840
 
 
2841
class TestStackRemove(TestStackWithTransport):
 
2842
 
 
2843
    def test_remove_existing(self):
 
2844
        conf = self.get_stack(self)
 
2845
        conf.store._load_from_string('foo=bar')
 
2846
        self.assertEquals('bar', conf.get('foo'))
 
2847
        conf.remove('foo')
 
2848
        # Did we get it back ?
 
2849
        self.assertEquals(None, conf.get('foo'))
 
2850
 
 
2851
    def test_remove_unknown(self):
 
2852
        conf = self.get_stack(self)
 
2853
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
 
2854
 
 
2855
    def test_remove_hook(self):
 
2856
        calls = []
 
2857
        def hook(*args):
 
2858
            calls.append(args)
 
2859
        config.ConfigHooks.install_named_hook('remove', hook, None)
 
2860
        self.assertLength(0, calls)
 
2861
        conf = self.get_stack(self)
 
2862
        conf.store._load_from_string('foo=bar')
 
2863
        conf.remove('foo')
 
2864
        self.assertLength(1, calls)
 
2865
        self.assertEquals((conf, 'foo'), calls[0])
 
2866
 
 
2867
 
 
2868
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
 
2869
 
 
2870
    def setUp(self):
 
2871
        super(TestConfigGetOptions, self).setUp()
 
2872
        create_configs(self)
 
2873
 
 
2874
    def test_no_variable(self):
 
2875
        # Using branch should query branch, locations and bazaar
 
2876
        self.assertOptions([], self.branch_config)
 
2877
 
 
2878
    def test_option_in_bazaar(self):
 
2879
        self.bazaar_config.set_user_option('file', 'bazaar')
 
2880
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
 
2881
                           self.bazaar_config)
 
2882
 
 
2883
    def test_option_in_locations(self):
 
2884
        self.locations_config.set_user_option('file', 'locations')
 
2885
        self.assertOptions(
 
2886
            [('file', 'locations', self.tree.basedir, 'locations')],
 
2887
            self.locations_config)
 
2888
 
 
2889
    def test_option_in_branch(self):
 
2890
        self.branch_config.set_user_option('file', 'branch')
 
2891
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
 
2892
                           self.branch_config)
 
2893
 
 
2894
    def test_option_in_bazaar_and_branch(self):
 
2895
        self.bazaar_config.set_user_option('file', 'bazaar')
 
2896
        self.branch_config.set_user_option('file', 'branch')
 
2897
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
 
2898
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2899
                           self.branch_config)
 
2900
 
 
2901
    def test_option_in_branch_and_locations(self):
 
2902
        # Hmm, locations override branch :-/
 
2903
        self.locations_config.set_user_option('file', 'locations')
 
2904
        self.branch_config.set_user_option('file', 'branch')
 
2905
        self.assertOptions(
 
2906
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2907
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
2908
            self.branch_config)
 
2909
 
 
2910
    def test_option_in_bazaar_locations_and_branch(self):
 
2911
        self.bazaar_config.set_user_option('file', 'bazaar')
 
2912
        self.locations_config.set_user_option('file', 'locations')
 
2913
        self.branch_config.set_user_option('file', 'branch')
 
2914
        self.assertOptions(
 
2915
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2916
             ('file', 'branch', 'DEFAULT', 'branch'),
 
2917
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2918
            self.branch_config)
 
2919
 
 
2920
 
 
2921
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
 
2922
 
 
2923
    def setUp(self):
 
2924
        super(TestConfigRemoveOption, self).setUp()
 
2925
        create_configs_with_file_option(self)
 
2926
 
 
2927
    def test_remove_in_locations(self):
 
2928
        self.locations_config.remove_user_option('file', self.tree.basedir)
 
2929
        self.assertOptions(
 
2930
            [('file', 'branch', 'DEFAULT', 'branch'),
 
2931
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2932
            self.branch_config)
 
2933
 
 
2934
    def test_remove_in_branch(self):
 
2935
        self.branch_config.remove_user_option('file')
 
2936
        self.assertOptions(
 
2937
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2938
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
2939
            self.branch_config)
 
2940
 
 
2941
    def test_remove_in_bazaar(self):
 
2942
        self.bazaar_config.remove_user_option('file')
 
2943
        self.assertOptions(
 
2944
            [('file', 'locations', self.tree.basedir, 'locations'),
 
2945
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
2946
            self.branch_config)
 
2947
 
 
2948
 
 
2949
class TestConfigGetSections(tests.TestCaseWithTransport):
 
2950
 
 
2951
    def setUp(self):
 
2952
        super(TestConfigGetSections, self).setUp()
 
2953
        create_configs(self)
 
2954
 
 
2955
    def assertSectionNames(self, expected, conf, name=None):
 
2956
        """Check which sections are returned for a given config.
 
2957
 
 
2958
        If fallback configurations exist their sections can be included.
 
2959
 
 
2960
        :param expected: A list of section names.
 
2961
 
 
2962
        :param conf: The configuration that will be queried.
 
2963
 
 
2964
        :param name: An optional section name that will be passed to
 
2965
            get_sections().
 
2966
        """
 
2967
        sections = list(conf._get_sections(name))
 
2968
        self.assertLength(len(expected), sections)
 
2969
        self.assertEqual(expected, [name for name, _, _ in sections])
 
2970
 
 
2971
    def test_bazaar_default_section(self):
 
2972
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
 
2973
 
 
2974
    def test_locations_default_section(self):
 
2975
        # No sections are defined in an empty file
 
2976
        self.assertSectionNames([], self.locations_config)
 
2977
 
 
2978
    def test_locations_named_section(self):
 
2979
        self.locations_config.set_user_option('file', 'locations')
 
2980
        self.assertSectionNames([self.tree.basedir], self.locations_config)
 
2981
 
 
2982
    def test_locations_matching_sections(self):
 
2983
        loc_config = self.locations_config
 
2984
        loc_config.set_user_option('file', 'locations')
 
2985
        # We need to cheat a bit here to create an option in sections above and
 
2986
        # below the 'location' one.
 
2987
        parser = loc_config._get_parser()
 
2988
        # locations.cong deals with '/' ignoring native os.sep
 
2989
        location_names = self.tree.basedir.split('/')
 
2990
        parent = '/'.join(location_names[:-1])
 
2991
        child = '/'.join(location_names + ['child'])
 
2992
        parser[parent] = {}
 
2993
        parser[parent]['file'] = 'parent'
 
2994
        parser[child] = {}
 
2995
        parser[child]['file'] = 'child'
 
2996
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
 
2997
 
 
2998
    def test_branch_data_default_section(self):
 
2999
        self.assertSectionNames([None],
 
3000
                                self.branch_config._get_branch_data_config())
 
3001
 
 
3002
    def test_branch_default_sections(self):
 
3003
        # No sections are defined in an empty locations file
 
3004
        self.assertSectionNames([None, 'DEFAULT'],
 
3005
                                self.branch_config)
 
3006
        # Unless we define an option
 
3007
        self.branch_config._get_location_config().set_user_option(
 
3008
            'file', 'locations')
 
3009
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
 
3010
                                self.branch_config)
 
3011
 
 
3012
    def test_bazaar_named_section(self):
 
3013
        # We need to cheat as the API doesn't give direct access to sections
 
3014
        # other than DEFAULT.
 
3015
        self.bazaar_config.set_alias('bazaar', 'bzr')
 
3016
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
 
3017
 
 
3018
 
1315
3019
class TestAuthenticationConfigFile(tests.TestCase):
1316
3020
    """Test the authentication.conf file matching"""
1317
3021
 
1595
3299
 
1596
3300
    def test_username_defaults_prompts(self):
1597
3301
        # HTTP prompts can't be tested here, see test_http.py
1598
 
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
1599
 
        self._check_default_username_prompt(
1600
 
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
1601
 
        self._check_default_username_prompt(
1602
 
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
 
3302
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
 
3303
        self._check_default_username_prompt(
 
3304
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
 
3305
        self._check_default_username_prompt(
 
3306
            u'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1603
3307
 
1604
3308
    def test_username_default_no_prompt(self):
1605
3309
        conf = config.AuthenticationConfig()
1611
3315
    def test_password_default_prompts(self):
1612
3316
        # HTTP prompts can't be tested here, see test_http.py
1613
3317
        self._check_default_password_prompt(
1614
 
            'FTP %(user)s@%(host)s password: ', 'ftp')
1615
 
        self._check_default_password_prompt(
1616
 
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
1617
 
        self._check_default_password_prompt(
1618
 
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
 
3318
            u'FTP %(user)s@%(host)s password: ', 'ftp')
 
3319
        self._check_default_password_prompt(
 
3320
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
 
3321
        self._check_default_password_prompt(
 
3322
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
1619
3323
        # SMTP port handling is a bit special (it's handled if embedded in the
1620
3324
        # host too)
1621
3325
        # FIXME: should we: forbid that, extend it to other schemes, leave
1622
3326
        # things as they are that's fine thank you ?
1623
 
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
1624
 
                                            'smtp')
1625
 
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
1626
 
                                            'smtp', host='bar.org:10025')
1627
 
        self._check_default_password_prompt(
1628
 
            'SMTP %(user)s@%(host)s:%(port)d password: ',
1629
 
            'smtp', port=10025)
 
3327
        self._check_default_password_prompt(
 
3328
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
 
3329
        self._check_default_password_prompt(
 
3330
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
 
3331
        self._check_default_password_prompt(
 
3332
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
1630
3333
 
1631
3334
    def test_ssh_password_emits_warning(self):
1632
3335
        conf = config.AuthenticationConfig(_file=StringIO(
1812
3515
# test_user_prompted ?
1813
3516
class TestAuthenticationRing(tests.TestCaseWithTransport):
1814
3517
    pass
 
3518
 
 
3519
 
 
3520
class TestAutoUserId(tests.TestCase):
 
3521
    """Test inferring an automatic user name."""
 
3522
 
 
3523
    def test_auto_user_id(self):
 
3524
        """Automatic inference of user name.
 
3525
        
 
3526
        This is a bit hard to test in an isolated way, because it depends on
 
3527
        system functions that go direct to /etc or perhaps somewhere else.
 
3528
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
 
3529
        to be able to choose a user name with no configuration.
 
3530
        """
 
3531
        if sys.platform == 'win32':
 
3532
            raise tests.TestSkipped(
 
3533
                "User name inference not implemented on win32")
 
3534
        realname, address = config._auto_user_id()
 
3535
        if os.path.exists('/etc/mailname'):
 
3536
            self.assertIsNot(None, realname)
 
3537
            self.assertIsNot(None, address)
 
3538
        else:
 
3539
            self.assertEquals((None, None), (realname, address))
 
3540