/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

Merge fix for bug #388269 into trunk, resolve conflicts and add release notes.

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_control_store(test):
 
120
    build_backing_branch(test, 'branch')
 
121
    b = bzrdir.BzrDir.open('branch')
 
122
    return config.ControlStore(b)
 
123
config.test_store_builder_registry.register('control', build_control_store)
 
124
 
 
125
 
 
126
def build_remote_branch_store(test):
 
127
    # There is only one permutation (but we won't be able to handle more with
 
128
    # this design anyway)
 
129
    (transport_class,
 
130
     server_class) = transport_remote.get_test_permutations()[0]
 
131
    build_backing_branch(test, 'branch', transport_class, server_class)
 
132
    b = branch.Branch.open(test.get_url('branch'))
 
133
    return config.BranchStore(b)
 
134
config.test_store_builder_registry.register('remote_branch',
 
135
                                            build_remote_branch_store)
 
136
 
 
137
 
 
138
config.test_stack_builder_registry.register(
 
139
    'bazaar', lambda test: config.GlobalStack())
 
140
config.test_stack_builder_registry.register(
 
141
    'location', lambda test: config.LocationStack('.'))
 
142
 
 
143
 
 
144
def build_branch_stack(test):
 
145
    build_backing_branch(test, 'branch')
 
146
    b = branch.Branch.open('branch')
 
147
    return config.BranchStack(b)
 
148
config.test_stack_builder_registry.register('branch', build_branch_stack)
 
149
 
 
150
 
 
151
def build_remote_branch_stack(test):
 
152
    # There is only one permutation (but we won't be able to handle more with
 
153
    # this design anyway)
 
154
    (transport_class,
 
155
     server_class) = transport_remote.get_test_permutations()[0]
 
156
    build_backing_branch(test, 'branch', transport_class, server_class)
 
157
    b = branch.Branch.open(test.get_url('branch'))
 
158
    return config.RemoteBranchStack(b)
 
159
config.test_stack_builder_registry.register('remote_branch',
 
160
                                            build_remote_branch_stack)
 
161
 
 
162
def build_remote_control_stack(test):
 
163
    # There is only one permutation (but we won't be able to handle more with
 
164
    # this design anyway)
 
165
    (transport_class,
 
166
     server_class) = transport_remote.get_test_permutations()[0]
 
167
    # We need only a bzrdir for this, not a full branch, but it's not worth
 
168
    # creating a dedicated helper to create only the bzrdir
 
169
    build_backing_branch(test, 'branch', transport_class, server_class)
 
170
    b = branch.Branch.open(test.get_url('branch'))
 
171
    return config.RemoteControlStack(b.bzrdir)
 
172
config.test_stack_builder_registry.register('remote_control',
 
173
                                            build_remote_control_stack)
 
174
 
 
175
 
41
176
sample_long_alias="log -r-15..-1 --line"
42
177
sample_config_text = u"""
43
178
[DEFAULT]
45
180
editor=vim
46
181
change_editor=vimdiff -of @new_path @old_path
47
182
gpg_signing_command=gnome-gpg
 
183
gpg_signing_key=DD4D5088
48
184
log_format=short
 
185
validate_signatures_in_log=true
 
186
acceptable_keys=amy
49
187
user_global_option=something
 
188
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
 
189
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
 
190
bzr.default_mergetool=sometool
50
191
[ALIASES]
51
192
h=help
52
193
ll=""" + sample_long_alias + "\n"
94
235
[/a/]
95
236
check_signatures=check-available
96
237
gpg_signing_command=false
 
238
gpg_signing_key=default
97
239
user_local_option=local
98
240
# test trailing / matching
99
241
[/a/*]
105
247
"""
106
248
 
107
249
 
 
250
def create_configs(test):
 
251
    """Create configuration files for a given test.
 
252
 
 
253
    This requires creating a tree (and populate the ``test.tree`` attribute)
 
254
    and its associated branch and will populate the following attributes:
 
255
 
 
256
    - branch_config: A BranchConfig for the associated branch.
 
257
 
 
258
    - locations_config : A LocationConfig for the associated branch
 
259
 
 
260
    - bazaar_config: A GlobalConfig.
 
261
 
 
262
    The tree and branch are created in a 'tree' subdirectory so the tests can
 
263
    still use the test directory to stay outside of the branch.
 
264
    """
 
265
    tree = test.make_branch_and_tree('tree')
 
266
    test.tree = tree
 
267
    test.branch_config = config.BranchConfig(tree.branch)
 
268
    test.locations_config = config.LocationConfig(tree.basedir)
 
269
    test.bazaar_config = config.GlobalConfig()
 
270
 
 
271
 
 
272
def create_configs_with_file_option(test):
 
273
    """Create configuration files with a ``file`` option set in each.
 
274
 
 
275
    This builds on ``create_configs`` and add one ``file`` option in each
 
276
    configuration with a value which allows identifying the configuration file.
 
277
    """
 
278
    create_configs(test)
 
279
    test.bazaar_config.set_user_option('file', 'bazaar')
 
280
    test.locations_config.set_user_option('file', 'locations')
 
281
    test.branch_config.set_user_option('file', 'branch')
 
282
 
 
283
 
 
284
class TestOptionsMixin:
 
285
 
 
286
    def assertOptions(self, expected, conf):
 
287
        # We don't care about the parser (as it will make tests hard to write
 
288
        # and error-prone anyway)
 
289
        self.assertThat([opt[:4] for opt in conf._get_options()],
 
290
                        matchers.Equals(expected))
 
291
 
 
292
 
108
293
class InstrumentedConfigObj(object):
109
294
    """A config obj look-enough-alike to record calls made to it."""
110
295
 
129
314
        self._calls.append(('keys',))
130
315
        return []
131
316
 
 
317
    def reload(self):
 
318
        self._calls.append(('reload',))
 
319
 
132
320
    def write(self, arg):
133
321
        self._calls.append(('write',))
134
322
 
240
428
        """
241
429
        co = config.ConfigObj()
242
430
        co['test'] = 'foo#bar'
243
 
        lines = co.write()
 
431
        outfile = StringIO()
 
432
        co.write(outfile=outfile)
 
433
        lines = outfile.getvalue().splitlines()
244
434
        self.assertEqual(lines, ['test = "foo#bar"'])
245
435
        co2 = config.ConfigObj(lines)
246
436
        self.assertEqual(co2['test'], 'foo#bar')
247
437
 
 
438
    def test_triple_quotes(self):
 
439
        # Bug #710410: if the value string has triple quotes
 
440
        # then ConfigObj versions up to 4.7.2 will quote them wrong
 
441
        # and won't able to read them back
 
442
        triple_quotes_value = '''spam
 
443
""" that's my spam """
 
444
eggs'''
 
445
        co = config.ConfigObj()
 
446
        co['test'] = triple_quotes_value
 
447
        # While writing this test another bug in ConfigObj has been found:
 
448
        # method co.write() without arguments produces list of lines
 
449
        # one option per line, and multiline values are not split
 
450
        # across multiple lines,
 
451
        # and that breaks the parsing these lines back by ConfigObj.
 
452
        # This issue only affects test, but it's better to avoid
 
453
        # `co.write()` construct at all.
 
454
        # [bialix 20110222] bug report sent to ConfigObj's author
 
455
        outfile = StringIO()
 
456
        co.write(outfile=outfile)
 
457
        output = outfile.getvalue()
 
458
        # now we're trying to read it back
 
459
        co2 = config.ConfigObj(StringIO(output))
 
460
        self.assertEquals(triple_quotes_value, co2['test'])
 
461
 
248
462
 
249
463
erroneous_config = """[section] # line 1
250
464
good=good # line 2
271
485
        config.Config()
272
486
 
273
487
    def test_no_default_editor(self):
274
 
        self.assertRaises(NotImplementedError, config.Config().get_editor)
 
488
        self.assertRaises(
 
489
            NotImplementedError,
 
490
            self.applyDeprecated, deprecated_in((2, 4, 0)),
 
491
            config.Config().get_editor)
275
492
 
276
493
    def test_user_email(self):
277
494
        my_config = InstrumentedConfig()
320
537
        my_config = config.Config()
321
538
        self.assertEqual('long', my_config.log_format())
322
539
 
 
540
    def test_acceptable_keys_default(self):
 
541
        my_config = config.Config()
 
542
        self.assertEqual(None, my_config.acceptable_keys())
 
543
 
 
544
    def test_validate_signatures_in_log_default(self):
 
545
        my_config = config.Config()
 
546
        self.assertEqual(False, my_config.validate_signatures_in_log())
 
547
 
323
548
    def test_get_change_editor(self):
324
549
        my_config = InstrumentedConfig()
325
550
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
333
558
 
334
559
    def setUp(self):
335
560
        super(TestConfigPath, self).setUp()
336
 
        os.environ['HOME'] = '/home/bogus'
337
 
        os.environ['XDG_CACHE_DIR'] = ''
 
561
        self.overrideEnv('HOME', '/home/bogus')
 
562
        self.overrideEnv('XDG_CACHE_DIR', '')
338
563
        if sys.platform == 'win32':
339
 
            os.environ['BZR_HOME'] = \
340
 
                r'C:\Documents and Settings\bogus\Application Data'
 
564
            self.overrideEnv(
 
565
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
341
566
            self.bzr_home = \
342
567
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
343
568
        else:
350
575
        self.assertEqual(config.config_filename(),
351
576
                         self.bzr_home + '/bazaar.conf')
352
577
 
353
 
    def test_branches_config_filename(self):
354
 
        self.assertEqual(config.branches_config_filename(),
355
 
                         self.bzr_home + '/branches.conf')
356
 
 
357
578
    def test_locations_config_filename(self):
358
579
        self.assertEqual(config.locations_config_filename(),
359
580
                         self.bzr_home + '/locations.conf')
367
588
            '/home/bogus/.cache')
368
589
 
369
590
 
370
 
class TestIniConfig(tests.TestCase):
 
591
class TestXDGConfigDir(tests.TestCaseInTempDir):
 
592
    # must be in temp dir because config tests for the existence of the bazaar
 
593
    # subdirectory of $XDG_CONFIG_HOME
 
594
 
 
595
    def setUp(self):
 
596
        if sys.platform in ('darwin', 'win32'):
 
597
            raise tests.TestNotApplicable(
 
598
                'XDG config dir not used on this platform')
 
599
        super(TestXDGConfigDir, self).setUp()
 
600
        self.overrideEnv('HOME', self.test_home_dir)
 
601
        # BZR_HOME overrides everything we want to test so unset it.
 
602
        self.overrideEnv('BZR_HOME', None)
 
603
 
 
604
    def test_xdg_config_dir_exists(self):
 
605
        """When ~/.config/bazaar exists, use it as the config dir."""
 
606
        newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
 
607
        os.makedirs(newdir)
 
608
        self.assertEqual(config.config_dir(), newdir)
 
609
 
 
610
    def test_xdg_config_home(self):
 
611
        """When XDG_CONFIG_HOME is set, use it."""
 
612
        xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
 
613
        self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
 
614
        newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
 
615
        os.makedirs(newdir)
 
616
        self.assertEqual(config.config_dir(), newdir)
 
617
 
 
618
 
 
619
class TestIniConfig(tests.TestCaseInTempDir):
371
620
 
372
621
    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
 
622
        conf = config.IniBasedConfig.from_string(s)
 
623
        return conf, conf._get_parser()
376
624
 
377
625
 
378
626
class TestIniConfigBuilding(TestIniConfig):
379
627
 
380
628
    def test_contructs(self):
381
 
        my_config = config.IniBasedConfig("nothing")
 
629
        my_config = config.IniBasedConfig()
382
630
 
383
631
    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))
 
632
        my_config = config.IniBasedConfig.from_string(sample_config_text)
 
633
        self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
389
634
 
390
635
    def test_cached(self):
 
636
        my_config = config.IniBasedConfig.from_string(sample_config_text)
 
637
        parser = my_config._get_parser()
 
638
        self.assertTrue(my_config._get_parser() is parser)
 
639
 
 
640
    def _dummy_chown(self, path, uid, gid):
 
641
        self.path, self.uid, self.gid = path, uid, gid
 
642
 
 
643
    def test_ini_config_ownership(self):
 
644
        """Ensure that chown is happening during _write_config_file"""
 
645
        self.requireFeature(features.chown_feature)
 
646
        self.overrideAttr(os, 'chown', self._dummy_chown)
 
647
        self.path = self.uid = self.gid = None
 
648
        conf = config.IniBasedConfig(file_name='./foo.conf')
 
649
        conf._write_config_file()
 
650
        self.assertEquals(self.path, './foo.conf')
 
651
        self.assertTrue(isinstance(self.uid, int))
 
652
        self.assertTrue(isinstance(self.gid, int))
 
653
 
 
654
    def test_get_filename_parameter_is_deprecated_(self):
 
655
        conf = self.callDeprecated([
 
656
            'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
 
657
            ' Use file_name instead.'],
 
658
            config.IniBasedConfig, lambda: 'ini.conf')
 
659
        self.assertEqual('ini.conf', conf.file_name)
 
660
 
 
661
    def test_get_parser_file_parameter_is_deprecated_(self):
391
662
        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)
 
663
        conf = config.IniBasedConfig.from_string(sample_config_text)
 
664
        conf = self.callDeprecated([
 
665
            'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
 
666
            ' Use IniBasedConfig(_content=xxx) instead.'],
 
667
            conf._get_parser, file=config_file)
 
668
 
 
669
 
 
670
class TestIniConfigSaving(tests.TestCaseInTempDir):
 
671
 
 
672
    def test_cant_save_without_a_file_name(self):
 
673
        conf = config.IniBasedConfig()
 
674
        self.assertRaises(AssertionError, conf._write_config_file)
 
675
 
 
676
    def test_saved_with_content(self):
 
677
        content = 'foo = bar\n'
 
678
        conf = config.IniBasedConfig.from_string(
 
679
            content, file_name='./test.conf', save=True)
 
680
        self.assertFileEqual(content, 'test.conf')
 
681
 
 
682
 
 
683
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
 
684
    """What is the default value of expand for config options.
 
685
 
 
686
    This is an opt-in beta feature used to evaluate whether or not option
 
687
    references can appear in dangerous place raising exceptions, disapearing
 
688
    (and as such corrupting data) or if it's safe to activate the option by
 
689
    default.
 
690
 
 
691
    Note that these tests relies on config._expand_default_value being already
 
692
    overwritten in the parent class setUp.
 
693
    """
 
694
 
 
695
    def setUp(self):
 
696
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
 
697
        self.config = None
 
698
        self.warnings = []
 
699
        def warning(*args):
 
700
            self.warnings.append(args[0] % args[1:])
 
701
        self.overrideAttr(trace, 'warning', warning)
 
702
 
 
703
    def get_config(self, expand):
 
704
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
 
705
                                            save=True)
 
706
        return c
 
707
 
 
708
    def assertExpandIs(self, expected):
 
709
        actual = config._get_expand_default_value()
 
710
        #self.config.get_user_option_as_bool('bzr.config.expand')
 
711
        self.assertEquals(expected, actual)
 
712
 
 
713
    def test_default_is_None(self):
 
714
        self.assertEquals(None, config._expand_default_value)
 
715
 
 
716
    def test_default_is_False_even_if_None(self):
 
717
        self.config = self.get_config(None)
 
718
        self.assertExpandIs(False)
 
719
 
 
720
    def test_default_is_False_even_if_invalid(self):
 
721
        self.config = self.get_config('<your choice>')
 
722
        self.assertExpandIs(False)
 
723
        # ...
 
724
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
 
725
        # Wait, you've been warned !
 
726
        self.assertLength(1, self.warnings)
 
727
        self.assertEquals(
 
728
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
 
729
            self.warnings[0])
 
730
 
 
731
    def test_default_is_True(self):
 
732
        self.config = self.get_config(True)
 
733
        self.assertExpandIs(True)
 
734
 
 
735
    def test_default_is_False(self):
 
736
        self.config = self.get_config(False)
 
737
        self.assertExpandIs(False)
 
738
 
 
739
 
 
740
class TestIniConfigOptionExpansion(tests.TestCase):
 
741
    """Test option expansion from the IniConfig level.
 
742
 
 
743
    What we really want here is to test the Config level, but the class being
 
744
    abstract as far as storing values is concerned, this can't be done
 
745
    properly (yet).
 
746
    """
 
747
    # FIXME: This should be rewritten when all configs share a storage
 
748
    # implementation -- vila 2011-02-18
 
749
 
 
750
    def get_config(self, string=None):
 
751
        if string is None:
 
752
            string = ''
 
753
        c = config.IniBasedConfig.from_string(string)
 
754
        return c
 
755
 
 
756
    def assertExpansion(self, expected, conf, string, env=None):
 
757
        self.assertEquals(expected, conf.expand_options(string, env))
 
758
 
 
759
    def test_no_expansion(self):
 
760
        c = self.get_config('')
 
761
        self.assertExpansion('foo', c, 'foo')
 
762
 
 
763
    def test_env_adding_options(self):
 
764
        c = self.get_config('')
 
765
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
766
 
 
767
    def test_env_overriding_options(self):
 
768
        c = self.get_config('foo=baz')
 
769
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
770
 
 
771
    def test_simple_ref(self):
 
772
        c = self.get_config('foo=xxx')
 
773
        self.assertExpansion('xxx', c, '{foo}')
 
774
 
 
775
    def test_unknown_ref(self):
 
776
        c = self.get_config('')
 
777
        self.assertRaises(errors.ExpandingUnknownOption,
 
778
                          c.expand_options, '{foo}')
 
779
 
 
780
    def test_indirect_ref(self):
 
781
        c = self.get_config('''
 
782
foo=xxx
 
783
bar={foo}
 
784
''')
 
785
        self.assertExpansion('xxx', c, '{bar}')
 
786
 
 
787
    def test_embedded_ref(self):
 
788
        c = self.get_config('''
 
789
foo=xxx
 
790
bar=foo
 
791
''')
 
792
        self.assertExpansion('xxx', c, '{{bar}}')
 
793
 
 
794
    def test_simple_loop(self):
 
795
        c = self.get_config('foo={foo}')
 
796
        self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
 
797
 
 
798
    def test_indirect_loop(self):
 
799
        c = self.get_config('''
 
800
foo={bar}
 
801
bar={baz}
 
802
baz={foo}''')
 
803
        e = self.assertRaises(errors.OptionExpansionLoop,
 
804
                              c.expand_options, '{foo}')
 
805
        self.assertEquals('foo->bar->baz', e.refs)
 
806
        self.assertEquals('{foo}', e.string)
 
807
 
 
808
    def test_list(self):
 
809
        conf = self.get_config('''
 
810
foo=start
 
811
bar=middle
 
812
baz=end
 
813
list={foo},{bar},{baz}
 
814
''')
 
815
        self.assertEquals(['start', 'middle', 'end'],
 
816
                           conf.get_user_option('list', expand=True))
 
817
 
 
818
    def test_cascading_list(self):
 
819
        conf = self.get_config('''
 
820
foo=start,{bar}
 
821
bar=middle,{baz}
 
822
baz=end
 
823
list={foo}
 
824
''')
 
825
        self.assertEquals(['start', 'middle', 'end'],
 
826
                           conf.get_user_option('list', expand=True))
 
827
 
 
828
    def test_pathological_hidden_list(self):
 
829
        conf = self.get_config('''
 
830
foo=bin
 
831
bar=go
 
832
start={foo
 
833
middle=},{
 
834
end=bar}
 
835
hidden={start}{middle}{end}
 
836
''')
 
837
        # Nope, it's either a string or a list, and the list wins as soon as a
 
838
        # ',' appears, so the string concatenation never occur.
 
839
        self.assertEquals(['{foo', '}', '{', 'bar}'],
 
840
                          conf.get_user_option('hidden', expand=True))
 
841
 
 
842
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
 
843
 
 
844
    def get_config(self, location, string=None):
 
845
        if string is None:
 
846
            string = ''
 
847
        # Since we don't save the config we won't strictly require to inherit
 
848
        # from TestCaseInTempDir, but an error occurs so quickly...
 
849
        c = config.LocationConfig.from_string(string, location)
 
850
        return c
 
851
 
 
852
    def test_dont_cross_unrelated_section(self):
 
853
        c = self.get_config('/another/branch/path','''
 
854
[/one/branch/path]
 
855
foo = hello
 
856
bar = {foo}/2
 
857
 
 
858
[/another/branch/path]
 
859
bar = {foo}/2
 
860
''')
 
861
        self.assertRaises(errors.ExpandingUnknownOption,
 
862
                          c.get_user_option, 'bar', expand=True)
 
863
 
 
864
    def test_cross_related_sections(self):
 
865
        c = self.get_config('/project/branch/path','''
 
866
[/project]
 
867
foo = qu
 
868
 
 
869
[/project/branch/path]
 
870
bar = {foo}ux
 
871
''')
 
872
        self.assertEquals('quux', c.get_user_option('bar', expand=True))
 
873
 
 
874
 
 
875
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
 
876
 
 
877
    def test_cannot_reload_without_name(self):
 
878
        conf = config.IniBasedConfig.from_string(sample_config_text)
 
879
        self.assertRaises(AssertionError, conf.reload)
 
880
 
 
881
    def test_reload_see_new_value(self):
 
882
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
 
883
                                               file_name='./test/conf')
 
884
        c1._write_config_file()
 
885
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
 
886
                                               file_name='./test/conf')
 
887
        c2._write_config_file()
 
888
        self.assertEqual('vim', c1.get_user_option('editor'))
 
889
        self.assertEqual('emacs', c2.get_user_option('editor'))
 
890
        # Make sure we get the Right value
 
891
        c1.reload()
 
892
        self.assertEqual('emacs', c1.get_user_option('editor'))
 
893
 
 
894
 
 
895
class TestLockableConfig(tests.TestCaseInTempDir):
 
896
 
 
897
    scenarios = lockable_config_scenarios()
 
898
 
 
899
    # Set by load_tests
 
900
    config_class = None
 
901
    config_args = None
 
902
    config_section = None
 
903
 
 
904
    def setUp(self):
 
905
        super(TestLockableConfig, self).setUp()
 
906
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
 
907
        self.config = self.create_config(self._content)
 
908
 
 
909
    def get_existing_config(self):
 
910
        return self.config_class(*self.config_args)
 
911
 
 
912
    def create_config(self, content):
 
913
        kwargs = dict(save=True)
 
914
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
 
915
        return c
 
916
 
 
917
    def test_simple_read_access(self):
 
918
        self.assertEquals('1', self.config.get_user_option('one'))
 
919
 
 
920
    def test_simple_write_access(self):
 
921
        self.config.set_user_option('one', 'one')
 
922
        self.assertEquals('one', self.config.get_user_option('one'))
 
923
 
 
924
    def test_listen_to_the_last_speaker(self):
 
925
        c1 = self.config
 
926
        c2 = self.get_existing_config()
 
927
        c1.set_user_option('one', 'ONE')
 
928
        c2.set_user_option('two', 'TWO')
 
929
        self.assertEquals('ONE', c1.get_user_option('one'))
 
930
        self.assertEquals('TWO', c2.get_user_option('two'))
 
931
        # The second update respect the first one
 
932
        self.assertEquals('ONE', c2.get_user_option('one'))
 
933
 
 
934
    def test_last_speaker_wins(self):
 
935
        # If the same config is not shared, the same variable modified twice
 
936
        # can only see a single result.
 
937
        c1 = self.config
 
938
        c2 = self.get_existing_config()
 
939
        c1.set_user_option('one', 'c1')
 
940
        c2.set_user_option('one', 'c2')
 
941
        self.assertEquals('c2', c2._get_user_option('one'))
 
942
        # The first modification is still available until another refresh
 
943
        # occur
 
944
        self.assertEquals('c1', c1._get_user_option('one'))
 
945
        c1.set_user_option('two', 'done')
 
946
        self.assertEquals('c2', c1._get_user_option('one'))
 
947
 
 
948
    def test_writes_are_serialized(self):
 
949
        c1 = self.config
 
950
        c2 = self.get_existing_config()
 
951
 
 
952
        # We spawn a thread that will pause *during* the write
 
953
        before_writing = threading.Event()
 
954
        after_writing = threading.Event()
 
955
        writing_done = threading.Event()
 
956
        c1_orig = c1._write_config_file
 
957
        def c1_write_config_file():
 
958
            before_writing.set()
 
959
            c1_orig()
 
960
            # The lock is held. We wait for the main thread to decide when to
 
961
            # continue
 
962
            after_writing.wait()
 
963
        c1._write_config_file = c1_write_config_file
 
964
        def c1_set_option():
 
965
            c1.set_user_option('one', 'c1')
 
966
            writing_done.set()
 
967
        t1 = threading.Thread(target=c1_set_option)
 
968
        # Collect the thread after the test
 
969
        self.addCleanup(t1.join)
 
970
        # Be ready to unblock the thread if the test goes wrong
 
971
        self.addCleanup(after_writing.set)
 
972
        t1.start()
 
973
        before_writing.wait()
 
974
        self.assertTrue(c1._lock.is_held)
 
975
        self.assertRaises(errors.LockContention,
 
976
                          c2.set_user_option, 'one', 'c2')
 
977
        self.assertEquals('c1', c1.get_user_option('one'))
 
978
        # Let the lock be released
 
979
        after_writing.set()
 
980
        writing_done.wait()
 
981
        c2.set_user_option('one', 'c2')
 
982
        self.assertEquals('c2', c2.get_user_option('one'))
 
983
 
 
984
    def test_read_while_writing(self):
 
985
       c1 = self.config
 
986
       # We spawn a thread that will pause *during* the write
 
987
       ready_to_write = threading.Event()
 
988
       do_writing = threading.Event()
 
989
       writing_done = threading.Event()
 
990
       c1_orig = c1._write_config_file
 
991
       def c1_write_config_file():
 
992
           ready_to_write.set()
 
993
           # The lock is held. We wait for the main thread to decide when to
 
994
           # continue
 
995
           do_writing.wait()
 
996
           c1_orig()
 
997
           writing_done.set()
 
998
       c1._write_config_file = c1_write_config_file
 
999
       def c1_set_option():
 
1000
           c1.set_user_option('one', 'c1')
 
1001
       t1 = threading.Thread(target=c1_set_option)
 
1002
       # Collect the thread after the test
 
1003
       self.addCleanup(t1.join)
 
1004
       # Be ready to unblock the thread if the test goes wrong
 
1005
       self.addCleanup(do_writing.set)
 
1006
       t1.start()
 
1007
       # Ensure the thread is ready to write
 
1008
       ready_to_write.wait()
 
1009
       self.assertTrue(c1._lock.is_held)
 
1010
       self.assertEquals('c1', c1.get_user_option('one'))
 
1011
       # If we read during the write, we get the old value
 
1012
       c2 = self.get_existing_config()
 
1013
       self.assertEquals('1', c2.get_user_option('one'))
 
1014
       # Let the writing occur and ensure it occurred
 
1015
       do_writing.set()
 
1016
       writing_done.wait()
 
1017
       # Now we get the updated value
 
1018
       c3 = self.get_existing_config()
 
1019
       self.assertEquals('c1', c3.get_user_option('one'))
395
1020
 
396
1021
 
397
1022
class TestGetUserOptionAs(TestIniConfig):
430
1055
        # automatically cast to list
431
1056
        self.assertEqual(['x'], get_list('one_item'))
432
1057
 
 
1058
    def test_get_user_option_as_int_from_SI(self):
 
1059
        conf, parser = self.make_config_parser("""
 
1060
plain = 100
 
1061
si_k = 5k,
 
1062
si_kb = 5kb,
 
1063
si_m = 5M,
 
1064
si_mb = 5MB,
 
1065
si_g = 5g,
 
1066
si_gb = 5gB,
 
1067
""")
 
1068
        get_si = conf.get_user_option_as_int_from_SI
 
1069
        self.assertEqual(100, get_si('plain'))
 
1070
        self.assertEqual(5000, get_si('si_k'))
 
1071
        self.assertEqual(5000, get_si('si_kb'))
 
1072
        self.assertEqual(5000000, get_si('si_m'))
 
1073
        self.assertEqual(5000000, get_si('si_mb'))
 
1074
        self.assertEqual(5000000000, get_si('si_g'))
 
1075
        self.assertEqual(5000000000, get_si('si_gb'))
 
1076
        self.assertEqual(None, get_si('non-exist'))
 
1077
        self.assertEqual(42, get_si('non-exist-with-default',  42))
433
1078
 
434
1079
class TestSupressWarning(TestIniConfig):
435
1080
 
462
1107
            parser = my_config._get_parser()
463
1108
        finally:
464
1109
            config.ConfigObj = oldparserclass
465
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
1110
        self.assertIsInstance(parser, InstrumentedConfigObj)
466
1111
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
467
1112
                                          'utf-8')])
468
1113
 
479
1124
        my_config = config.BranchConfig(branch)
480
1125
        location_config = my_config._get_location_config()
481
1126
        self.assertEqual(branch.base, location_config.location)
482
 
        self.failUnless(location_config is my_config._get_location_config())
 
1127
        self.assertIs(location_config, my_config._get_location_config())
483
1128
 
484
1129
    def test_get_config(self):
485
1130
        """The Branch.get_config method works properly"""
505
1150
        branch = self.make_branch('branch')
506
1151
        self.assertEqual('branch', branch.nick)
507
1152
 
508
 
        locations = config.locations_config_filename()
509
 
        config.ensure_config_dir_exists()
510
1153
        local_url = urlutils.local_path_to_url('branch')
511
 
        open(locations, 'wb').write('[%s]\nnickname = foobar'
512
 
                                    % (local_url,))
 
1154
        conf = config.LocationConfig.from_string(
 
1155
            '[%s]\nnickname = foobar' % (local_url,),
 
1156
            local_url, save=True)
513
1157
        self.assertEqual('foobar', branch.nick)
514
1158
 
515
1159
    def test_config_local_path(self):
517
1161
        branch = self.make_branch('branch')
518
1162
        self.assertEqual('branch', branch.nick)
519
1163
 
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'),))
 
1164
        local_path = osutils.getcwd().encode('utf8')
 
1165
        conf = config.LocationConfig.from_string(
 
1166
            '[%s/branch]\nnickname = barry' % (local_path,),
 
1167
            'branch',  save=True)
524
1168
        self.assertEqual('barry', branch.nick)
525
1169
 
526
1170
    def test_config_creates_local(self):
527
1171
        """Creating a new entry in config uses a local path."""
528
1172
        branch = self.make_branch('branch', format='knit')
529
1173
        branch.set_push_location('http://foobar')
530
 
        locations = config.locations_config_filename()
531
1174
        local_path = osutils.getcwd().encode('utf8')
532
1175
        # Surprisingly ConfigObj doesn't create a trailing newline
533
 
        self.check_file_contents(locations,
 
1176
        self.check_file_contents(config.locations_config_filename(),
534
1177
                                 '[%s/branch]\n'
535
1178
                                 'push_location = http://foobar\n'
536
1179
                                 'push_location:policy = norecurse\n'
541
1184
        self.assertEqual('!repo', b.get_config().get_nickname())
542
1185
 
543
1186
    def test_warn_if_masked(self):
544
 
        _warning = trace.warning
545
1187
        warnings = []
546
1188
        def warning(*args):
547
1189
            warnings.append(args[0] % args[1:])
 
1190
        self.overrideAttr(trace, 'warning', warning)
548
1191
 
549
1192
        def set_option(store, warn_masked=True):
550
1193
            warnings[:] = []
556
1199
            else:
557
1200
                self.assertEqual(1, len(warnings))
558
1201
                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):
 
1202
        branch = self.make_branch('.')
 
1203
        conf = branch.get_config()
 
1204
        set_option(config.STORE_GLOBAL)
 
1205
        assertWarning(None)
 
1206
        set_option(config.STORE_BRANCH)
 
1207
        assertWarning(None)
 
1208
        set_option(config.STORE_GLOBAL)
 
1209
        assertWarning('Value "4" is masked by "3" from branch.conf')
 
1210
        set_option(config.STORE_GLOBAL, warn_masked=False)
 
1211
        assertWarning(None)
 
1212
        set_option(config.STORE_LOCATION)
 
1213
        assertWarning(None)
 
1214
        set_option(config.STORE_BRANCH)
 
1215
        assertWarning('Value "3" is masked by "0" from locations.conf')
 
1216
        set_option(config.STORE_BRANCH, warn_masked=False)
 
1217
        assertWarning(None)
 
1218
 
 
1219
 
 
1220
class TestGlobalConfigItems(tests.TestCaseInTempDir):
582
1221
 
583
1222
    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)
 
1223
        my_config = config.GlobalConfig.from_string(sample_config_text)
587
1224
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
588
1225
                         my_config._get_user_id())
589
1226
 
590
1227
    def test_absent_user_id(self):
591
 
        config_file = StringIO("")
592
1228
        my_config = config.GlobalConfig()
593
 
        my_config._parser = my_config._get_parser(file=config_file)
594
1229
        self.assertEqual(None, my_config._get_user_id())
595
1230
 
596
1231
    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())
 
1232
        my_config = config.GlobalConfig.from_string(sample_config_text)
 
1233
        editor = self.applyDeprecated(
 
1234
            deprecated_in((2, 4, 0)), my_config.get_editor)
 
1235
        self.assertEqual('vim', editor)
601
1236
 
602
1237
    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)
 
1238
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
606
1239
        self.assertEqual(config.CHECK_NEVER,
607
1240
                         my_config.signature_checking())
608
1241
        self.assertEqual(config.SIGN_ALWAYS,
610
1243
        self.assertEqual(True, my_config.signature_needed())
611
1244
 
612
1245
    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)
 
1246
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
616
1247
        self.assertEqual(config.CHECK_NEVER,
617
1248
                         my_config.signature_checking())
618
1249
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
620
1251
        self.assertEqual(False, my_config.signature_needed())
621
1252
 
622
1253
    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)
 
1254
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
626
1255
        self.assertEqual(config.CHECK_ALWAYS,
627
1256
                         my_config.signature_checking())
628
1257
        self.assertEqual(config.SIGN_NEVER,
630
1259
        self.assertEqual(False, my_config.signature_needed())
631
1260
 
632
1261
    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)
 
1262
        my_config = config.GlobalConfig.from_string(sample_config_text)
636
1263
        return my_config
637
1264
 
638
1265
    def test_gpg_signing_command(self):
640
1267
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
641
1268
        self.assertEqual(False, my_config.signature_needed())
642
1269
 
 
1270
    def test_gpg_signing_key(self):
 
1271
        my_config = self._get_sample_config()
 
1272
        self.assertEqual("DD4D5088", my_config.gpg_signing_key())
 
1273
 
643
1274
    def _get_empty_config(self):
644
 
        config_file = StringIO("")
645
1275
        my_config = config.GlobalConfig()
646
 
        my_config._parser = my_config._get_parser(file=config_file)
647
1276
        return my_config
648
1277
 
649
1278
    def test_gpg_signing_command_unset(self):
667
1296
        my_config = self._get_sample_config()
668
1297
        self.assertEqual("short", my_config.log_format())
669
1298
 
 
1299
    def test_configured_acceptable_keys(self):
 
1300
        my_config = self._get_sample_config()
 
1301
        self.assertEqual("amy", my_config.acceptable_keys())
 
1302
 
 
1303
    def test_configured_validate_signatures_in_log(self):
 
1304
        my_config = self._get_sample_config()
 
1305
        self.assertEqual(True, my_config.validate_signatures_in_log())
 
1306
 
670
1307
    def test_get_alias(self):
671
1308
        my_config = self._get_sample_config()
672
1309
        self.assertEqual('help', my_config.get_alias('h'))
699
1336
        change_editor = my_config.get_change_editor('old', 'new')
700
1337
        self.assertIs(None, change_editor)
701
1338
 
 
1339
    def test_get_merge_tools(self):
 
1340
        conf = self._get_sample_config()
 
1341
        tools = conf.get_merge_tools()
 
1342
        self.log(repr(tools))
 
1343
        self.assertEqual(
 
1344
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
 
1345
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
 
1346
            tools)
 
1347
 
 
1348
    def test_get_merge_tools_empty(self):
 
1349
        conf = self._get_empty_config()
 
1350
        tools = conf.get_merge_tools()
 
1351
        self.assertEqual({}, tools)
 
1352
 
 
1353
    def test_find_merge_tool(self):
 
1354
        conf = self._get_sample_config()
 
1355
        cmdline = conf.find_merge_tool('sometool')
 
1356
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
 
1357
 
 
1358
    def test_find_merge_tool_not_found(self):
 
1359
        conf = self._get_sample_config()
 
1360
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
 
1361
        self.assertIs(cmdline, None)
 
1362
 
 
1363
    def test_find_merge_tool_known(self):
 
1364
        conf = self._get_empty_config()
 
1365
        cmdline = conf.find_merge_tool('kdiff3')
 
1366
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
 
1367
 
 
1368
    def test_find_merge_tool_override_known(self):
 
1369
        conf = self._get_empty_config()
 
1370
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
 
1371
        cmdline = conf.find_merge_tool('kdiff3')
 
1372
        self.assertEqual('kdiff3 blah', cmdline)
 
1373
 
702
1374
 
703
1375
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
704
1376
 
722
1394
        self.assertIs(None, new_config.get_alias('commit'))
723
1395
 
724
1396
 
725
 
class TestLocationConfig(tests.TestCaseInTempDir):
 
1397
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
726
1398
 
727
1399
    def test_constructs(self):
728
1400
        my_config = config.LocationConfig('http://example.com')
740
1412
            parser = my_config._get_parser()
741
1413
        finally:
742
1414
            config.ConfigObj = oldparserclass
743
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
1415
        self.assertIsInstance(parser, InstrumentedConfigObj)
744
1416
        self.assertEqual(parser._calls,
745
1417
                         [('__init__', config.locations_config_filename(),
746
1418
                           '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
1419
 
760
1420
    def test_get_global_config(self):
761
1421
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
762
1422
        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())
 
1423
        self.assertIsInstance(global_config, config.GlobalConfig)
 
1424
        self.assertIs(global_config, my_config._get_global_config())
 
1425
 
 
1426
    def assertLocationMatching(self, expected):
 
1427
        self.assertEqual(expected,
 
1428
                         list(self.my_location_config._get_matching_sections()))
765
1429
 
766
1430
    def test__get_matching_sections_no_match(self):
767
1431
        self.get_branch_config('/')
768
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1432
        self.assertLocationMatching([])
769
1433
 
770
1434
    def test__get_matching_sections_exact(self):
771
1435
        self.get_branch_config('http://www.example.com')
772
 
        self.assertEqual([('http://www.example.com', '')],
773
 
                         self.my_location_config._get_matching_sections())
 
1436
        self.assertLocationMatching([('http://www.example.com', '')])
774
1437
 
775
1438
    def test__get_matching_sections_suffix_does_not(self):
776
1439
        self.get_branch_config('http://www.example.com-com')
777
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1440
        self.assertLocationMatching([])
778
1441
 
779
1442
    def test__get_matching_sections_subdir_recursive(self):
780
1443
        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())
 
1444
        self.assertLocationMatching([('http://www.example.com', 'com')])
783
1445
 
784
1446
    def test__get_matching_sections_ignoreparent(self):
785
1447
        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())
 
1448
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1449
                                      '')])
788
1450
 
789
1451
    def test__get_matching_sections_ignoreparent_subdir(self):
790
1452
        self.get_branch_config(
791
1453
            'http://www.example.com/ignoreparent/childbranch')
792
 
        self.assertEqual([('http://www.example.com/ignoreparent',
793
 
                           'childbranch')],
794
 
                         self.my_location_config._get_matching_sections())
 
1454
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1455
                                      'childbranch')])
795
1456
 
796
1457
    def test__get_matching_sections_subdir_trailing_slash(self):
797
1458
        self.get_branch_config('/b')
798
 
        self.assertEqual([('/b/', '')],
799
 
                         self.my_location_config._get_matching_sections())
 
1459
        self.assertLocationMatching([('/b/', '')])
800
1460
 
801
1461
    def test__get_matching_sections_subdir_child(self):
802
1462
        self.get_branch_config('/a/foo')
803
 
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
804
 
                         self.my_location_config._get_matching_sections())
 
1463
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
805
1464
 
806
1465
    def test__get_matching_sections_subdir_child_child(self):
807
1466
        self.get_branch_config('/a/foo/bar')
808
 
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
809
 
                         self.my_location_config._get_matching_sections())
 
1467
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
810
1468
 
811
1469
    def test__get_matching_sections_trailing_slash_with_children(self):
812
1470
        self.get_branch_config('/a/')
813
 
        self.assertEqual([('/a/', '')],
814
 
                         self.my_location_config._get_matching_sections())
 
1471
        self.assertLocationMatching([('/a/', '')])
815
1472
 
816
1473
    def test__get_matching_sections_explicit_over_glob(self):
817
1474
        # XXX: 2006-09-08 jamesh
819
1476
        # was a config section for '/a/?', it would get precedence
820
1477
        # over '/a/c'.
821
1478
        self.get_branch_config('/a/c')
822
 
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
823
 
                         self.my_location_config._get_matching_sections())
 
1479
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
824
1480
 
825
1481
    def test__get_option_policy_normal(self):
826
1482
        self.get_branch_config('http://www.example.com')
848
1504
            'http://www.example.com', 'appendpath_option'),
849
1505
            config.POLICY_APPENDPATH)
850
1506
 
 
1507
    def test__get_options_with_policy(self):
 
1508
        self.get_branch_config('/dir/subdir',
 
1509
                               location_config="""\
 
1510
[/dir]
 
1511
other_url = /other-dir
 
1512
other_url:policy = appendpath
 
1513
[/dir/subdir]
 
1514
other_url = /other-subdir
 
1515
""")
 
1516
        self.assertOptions(
 
1517
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
 
1518
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
 
1519
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
 
1520
            self.my_location_config)
 
1521
 
851
1522
    def test_location_without_username(self):
852
1523
        self.get_branch_config('http://www.example.com/ignoreparent')
853
1524
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
895
1566
        self.get_branch_config('/a')
896
1567
        self.assertEqual("false", self.my_config.gpg_signing_command())
897
1568
 
 
1569
    def test_gpg_signing_key(self):
 
1570
        self.get_branch_config('/b')
 
1571
        self.assertEqual("DD4D5088", self.my_config.gpg_signing_key())
 
1572
 
 
1573
    def test_gpg_signing_key_default(self):
 
1574
        self.get_branch_config('/a')
 
1575
        self.assertEqual("erik@bagfors.nu", self.my_config.gpg_signing_key())
 
1576
 
898
1577
    def test_get_user_option_global(self):
899
1578
        self.get_branch_config('/a')
900
1579
        self.assertEqual('something',
989
1668
        self.assertEqual('bzrlib.tests.test_config.post_commit',
990
1669
                         self.my_config.post_commit())
991
1670
 
992
 
    def get_branch_config(self, location, global_config=None):
 
1671
    def get_branch_config(self, location, global_config=None,
 
1672
                          location_config=None):
 
1673
        my_branch = FakeBranch(location)
993
1674
        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)
 
1675
            global_config = sample_config_text
 
1676
        if location_config is None:
 
1677
            location_config = sample_branches_text
 
1678
 
 
1679
        my_global_config = config.GlobalConfig.from_string(global_config,
 
1680
                                                           save=True)
 
1681
        my_location_config = config.LocationConfig.from_string(
 
1682
            location_config, my_branch.base, save=True)
 
1683
        my_config = config.BranchConfig(my_branch)
 
1684
        self.my_config = my_config
 
1685
        self.my_location_config = my_config._get_location_config()
1004
1686
 
1005
1687
    def test_set_user_setting_sets_and_saves(self):
1006
1688
        self.get_branch_config('/a/c')
1007
1689
        record = InstrumentedConfigObj("foo")
1008
1690
        self.my_location_config._parser = record
1009
1691
 
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'),
 
1692
        self.callDeprecated(['The recurse option is deprecated as of '
 
1693
                             '0.14.  The section "/a/c" has been '
 
1694
                             'converted to use policies.'],
 
1695
                            self.my_config.set_user_option,
 
1696
                            'foo', 'bar', store=config.STORE_LOCATION)
 
1697
        self.assertEqual([('reload',),
 
1698
                          ('__contains__', '/a/c'),
1029
1699
                          ('__contains__', '/a/c/'),
1030
1700
                          ('__setitem__', '/a/c', {}),
1031
1701
                          ('__getitem__', '/a/c'),
1060
1730
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1061
1731
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1062
1732
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1063
 
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
1733
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1064
1734
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1065
1735
 
1066
1736
 
1074
1744
option = exact
1075
1745
"""
1076
1746
 
1077
 
 
1078
1747
class TestBranchConfigItems(tests.TestCaseInTempDir):
1079
1748
 
1080
1749
    def get_branch_config(self, global_config=None, location=None,
1081
1750
                          location_config=None, branch_data_config=None):
1082
 
        my_config = config.BranchConfig(FakeBranch(location))
 
1751
        my_branch = FakeBranch(location)
1083
1752
        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()
 
1753
            my_global_config = config.GlobalConfig.from_string(global_config,
 
1754
                                                               save=True)
1087
1755
        if location_config is not None:
1088
 
            location_file = StringIO(location_config.encode('utf-8'))
1089
 
            self.my_location_config._get_parser(location_file)
 
1756
            my_location_config = config.LocationConfig.from_string(
 
1757
                location_config, my_branch.base, save=True)
 
1758
        my_config = config.BranchConfig(my_branch)
1090
1759
        if branch_data_config is not None:
1091
1760
            my_config.branch.control_files.files['branch.conf'] = \
1092
1761
                branch_data_config
1106
1775
                         my_config.username())
1107
1776
 
1108
1777
    def test_not_set_in_branch(self):
1109
 
        my_config = self.get_branch_config(sample_config_text)
 
1778
        my_config = self.get_branch_config(global_config=sample_config_text)
1110
1779
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1111
1780
                         my_config._get_user_id())
1112
1781
        my_config.branch.control_files.files['email'] = "John"
1113
1782
        self.assertEqual("John", my_config._get_user_id())
1114
1783
 
1115
1784
    def test_BZR_EMAIL_OVERRIDES(self):
1116
 
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
 
1785
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1117
1786
        branch = FakeBranch()
1118
1787
        my_config = config.BranchConfig(branch)
1119
1788
        self.assertEqual("Robert Collins <robertc@example.org>",
1136
1805
 
1137
1806
    def test_gpg_signing_command(self):
1138
1807
        my_config = self.get_branch_config(
 
1808
            global_config=sample_config_text,
1139
1809
            # branch data cannot set gpg_signing_command
1140
1810
            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
1811
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1144
1812
 
1145
1813
    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))
 
1814
        my_config = self.get_branch_config(global_config=sample_config_text)
1150
1815
        self.assertEqual('something',
1151
1816
                         my_config.get_user_option('user_global_option'))
1152
1817
 
1153
1818
    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)
 
1819
        my_config = self.get_branch_config(global_config=sample_config_text,
 
1820
                                      location='/a/c',
 
1821
                                      location_config=sample_branches_text)
1157
1822
        self.assertEqual(my_config.branch.base, '/a/c')
1158
1823
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1159
1824
                         my_config.post_commit())
1160
1825
        my_config.set_user_option('post_commit', 'rmtree_root')
1161
 
        # post-commit is ignored when bresent in branch data
 
1826
        # post-commit is ignored when present in branch data
1162
1827
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1163
1828
                         my_config.post_commit())
1164
1829
        my_config.set_user_option('post_commit', 'rmtree_root',
1166
1831
        self.assertEqual('rmtree_root', my_config.post_commit())
1167
1832
 
1168
1833
    def test_config_precedence(self):
 
1834
        # FIXME: eager test, luckily no persitent config file makes it fail
 
1835
        # -- vila 20100716
1169
1836
        my_config = self.get_branch_config(global_config=precedence_global)
1170
1837
        self.assertEqual(my_config.get_user_option('option'), 'global')
1171
1838
        my_config = self.get_branch_config(global_config=precedence_global,
1172
 
                                      branch_data_config=precedence_branch)
 
1839
                                           branch_data_config=precedence_branch)
1173
1840
        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)
 
1841
        my_config = self.get_branch_config(
 
1842
            global_config=precedence_global,
 
1843
            branch_data_config=precedence_branch,
 
1844
            location_config=precedence_location)
1177
1845
        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')
 
1846
        my_config = self.get_branch_config(
 
1847
            global_config=precedence_global,
 
1848
            branch_data_config=precedence_branch,
 
1849
            location_config=precedence_location,
 
1850
            location='http://example.com/specific')
1182
1851
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1183
1852
 
1184
1853
    def test_get_mail_client(self):
1274
1943
 
1275
1944
class TestTransportConfig(tests.TestCaseWithTransport):
1276
1945
 
 
1946
    def test_load_utf8(self):
 
1947
        """Ensure we can load an utf8-encoded file."""
 
1948
        t = self.get_transport()
 
1949
        unicode_user = u'b\N{Euro Sign}ar'
 
1950
        unicode_content = u'user=%s' % (unicode_user,)
 
1951
        utf8_content = unicode_content.encode('utf8')
 
1952
        # Store the raw content in the config file
 
1953
        t.put_bytes('foo.conf', utf8_content)
 
1954
        conf = config.TransportConfig(t, 'foo.conf')
 
1955
        self.assertEquals(unicode_user, conf.get_option('user'))
 
1956
 
 
1957
    def test_load_non_ascii(self):
 
1958
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
 
1959
        t = self.get_transport()
 
1960
        t.put_bytes('foo.conf', 'user=foo\n#\xff\n')
 
1961
        conf = config.TransportConfig(t, 'foo.conf')
 
1962
        self.assertRaises(errors.ConfigContentError, conf._get_configobj)
 
1963
 
 
1964
    def test_load_erroneous_content(self):
 
1965
        """Ensure we display a proper error on content that can't be parsed."""
 
1966
        t = self.get_transport()
 
1967
        t.put_bytes('foo.conf', '[open_section\n')
 
1968
        conf = config.TransportConfig(t, 'foo.conf')
 
1969
        self.assertRaises(errors.ParseConfigError, conf._get_configobj)
 
1970
 
1277
1971
    def test_get_value(self):
1278
1972
        """Test that retreiving a value from a section is possible"""
1279
 
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
 
1973
        bzrdir_config = config.TransportConfig(self.get_transport('.'),
1280
1974
                                               'control.conf')
1281
1975
        bzrdir_config.set_option('value', 'key', 'SECTION')
1282
1976
        bzrdir_config.set_option('value2', 'key2')
1312
2006
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1313
2007
 
1314
2008
 
 
2009
class TestOldConfigHooks(tests.TestCaseWithTransport):
 
2010
 
 
2011
    def setUp(self):
 
2012
        super(TestOldConfigHooks, self).setUp()
 
2013
        create_configs_with_file_option(self)
 
2014
 
 
2015
    def assertGetHook(self, conf, name, value):
 
2016
        calls = []
 
2017
        def hook(*args):
 
2018
            calls.append(args)
 
2019
        config.OldConfigHooks.install_named_hook('get', hook, None)
 
2020
        self.addCleanup(
 
2021
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
 
2022
        self.assertLength(0, calls)
 
2023
        actual_value = conf.get_user_option(name)
 
2024
        self.assertEquals(value, actual_value)
 
2025
        self.assertLength(1, calls)
 
2026
        self.assertEquals((conf, name, value), calls[0])
 
2027
 
 
2028
    def test_get_hook_bazaar(self):
 
2029
        self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
 
2030
 
 
2031
    def test_get_hook_locations(self):
 
2032
        self.assertGetHook(self.locations_config, 'file', 'locations')
 
2033
 
 
2034
    def test_get_hook_branch(self):
 
2035
        # Since locations masks branch, we define a different option
 
2036
        self.branch_config.set_user_option('file2', 'branch')
 
2037
        self.assertGetHook(self.branch_config, 'file2', 'branch')
 
2038
 
 
2039
    def assertSetHook(self, conf, name, value):
 
2040
        calls = []
 
2041
        def hook(*args):
 
2042
            calls.append(args)
 
2043
        config.OldConfigHooks.install_named_hook('set', hook, None)
 
2044
        self.addCleanup(
 
2045
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
 
2046
        self.assertLength(0, calls)
 
2047
        conf.set_user_option(name, value)
 
2048
        self.assertLength(1, calls)
 
2049
        # We can't assert the conf object below as different configs use
 
2050
        # different means to implement set_user_option and we care only about
 
2051
        # coverage here.
 
2052
        self.assertEquals((name, value), calls[0][1:])
 
2053
 
 
2054
    def test_set_hook_bazaar(self):
 
2055
        self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
 
2056
 
 
2057
    def test_set_hook_locations(self):
 
2058
        self.assertSetHook(self.locations_config, 'foo', 'locations')
 
2059
 
 
2060
    def test_set_hook_branch(self):
 
2061
        self.assertSetHook(self.branch_config, 'foo', 'branch')
 
2062
 
 
2063
    def assertRemoveHook(self, conf, name, section_name=None):
 
2064
        calls = []
 
2065
        def hook(*args):
 
2066
            calls.append(args)
 
2067
        config.OldConfigHooks.install_named_hook('remove', hook, None)
 
2068
        self.addCleanup(
 
2069
            config.OldConfigHooks.uninstall_named_hook, 'remove', None)
 
2070
        self.assertLength(0, calls)
 
2071
        conf.remove_user_option(name, section_name)
 
2072
        self.assertLength(1, calls)
 
2073
        # We can't assert the conf object below as different configs use
 
2074
        # different means to implement remove_user_option and we care only about
 
2075
        # coverage here.
 
2076
        self.assertEquals((name,), calls[0][1:])
 
2077
 
 
2078
    def test_remove_hook_bazaar(self):
 
2079
        self.assertRemoveHook(self.bazaar_config, 'file')
 
2080
 
 
2081
    def test_remove_hook_locations(self):
 
2082
        self.assertRemoveHook(self.locations_config, 'file',
 
2083
                              self.locations_config.location)
 
2084
 
 
2085
    def test_remove_hook_branch(self):
 
2086
        self.assertRemoveHook(self.branch_config, 'file')
 
2087
 
 
2088
    def assertLoadHook(self, name, conf_class, *conf_args):
 
2089
        calls = []
 
2090
        def hook(*args):
 
2091
            calls.append(args)
 
2092
        config.OldConfigHooks.install_named_hook('load', hook, None)
 
2093
        self.addCleanup(
 
2094
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
 
2095
        self.assertLength(0, calls)
 
2096
        # Build a config
 
2097
        conf = conf_class(*conf_args)
 
2098
        # Access an option to trigger a load
 
2099
        conf.get_user_option(name)
 
2100
        self.assertLength(1, calls)
 
2101
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2102
 
 
2103
    def test_load_hook_bazaar(self):
 
2104
        self.assertLoadHook('file', config.GlobalConfig)
 
2105
 
 
2106
    def test_load_hook_locations(self):
 
2107
        self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
 
2108
 
 
2109
    def test_load_hook_branch(self):
 
2110
        self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
 
2111
 
 
2112
    def assertSaveHook(self, conf):
 
2113
        calls = []
 
2114
        def hook(*args):
 
2115
            calls.append(args)
 
2116
        config.OldConfigHooks.install_named_hook('save', hook, None)
 
2117
        self.addCleanup(
 
2118
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
 
2119
        self.assertLength(0, calls)
 
2120
        # Setting an option triggers a save
 
2121
        conf.set_user_option('foo', 'bar')
 
2122
        self.assertLength(1, calls)
 
2123
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2124
 
 
2125
    def test_save_hook_bazaar(self):
 
2126
        self.assertSaveHook(self.bazaar_config)
 
2127
 
 
2128
    def test_save_hook_locations(self):
 
2129
        self.assertSaveHook(self.locations_config)
 
2130
 
 
2131
    def test_save_hook_branch(self):
 
2132
        self.assertSaveHook(self.branch_config)
 
2133
 
 
2134
 
 
2135
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
 
2136
    """Tests config hooks for remote configs.
 
2137
 
 
2138
    No tests for the remove hook as this is not implemented there.
 
2139
    """
 
2140
 
 
2141
    def setUp(self):
 
2142
        super(TestOldConfigHooksForRemote, self).setUp()
 
2143
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2144
        create_configs_with_file_option(self)
 
2145
 
 
2146
    def assertGetHook(self, conf, name, value):
 
2147
        calls = []
 
2148
        def hook(*args):
 
2149
            calls.append(args)
 
2150
        config.OldConfigHooks.install_named_hook('get', hook, None)
 
2151
        self.addCleanup(
 
2152
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
 
2153
        self.assertLength(0, calls)
 
2154
        actual_value = conf.get_option(name)
 
2155
        self.assertEquals(value, actual_value)
 
2156
        self.assertLength(1, calls)
 
2157
        self.assertEquals((conf, name, value), calls[0])
 
2158
 
 
2159
    def test_get_hook_remote_branch(self):
 
2160
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2161
        self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
 
2162
 
 
2163
    def test_get_hook_remote_bzrdir(self):
 
2164
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2165
        conf = remote_bzrdir._get_config()
 
2166
        conf.set_option('remotedir', 'file')
 
2167
        self.assertGetHook(conf, 'file', 'remotedir')
 
2168
 
 
2169
    def assertSetHook(self, conf, name, value):
 
2170
        calls = []
 
2171
        def hook(*args):
 
2172
            calls.append(args)
 
2173
        config.OldConfigHooks.install_named_hook('set', hook, None)
 
2174
        self.addCleanup(
 
2175
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
 
2176
        self.assertLength(0, calls)
 
2177
        conf.set_option(value, name)
 
2178
        self.assertLength(1, calls)
 
2179
        # We can't assert the conf object below as different configs use
 
2180
        # different means to implement set_user_option and we care only about
 
2181
        # coverage here.
 
2182
        self.assertEquals((name, value), calls[0][1:])
 
2183
 
 
2184
    def test_set_hook_remote_branch(self):
 
2185
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2186
        self.addCleanup(remote_branch.lock_write().unlock)
 
2187
        self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
 
2188
 
 
2189
    def test_set_hook_remote_bzrdir(self):
 
2190
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2191
        self.addCleanup(remote_branch.lock_write().unlock)
 
2192
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2193
        self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
 
2194
 
 
2195
    def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
 
2196
        calls = []
 
2197
        def hook(*args):
 
2198
            calls.append(args)
 
2199
        config.OldConfigHooks.install_named_hook('load', hook, None)
 
2200
        self.addCleanup(
 
2201
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
 
2202
        self.assertLength(0, calls)
 
2203
        # Build a config
 
2204
        conf = conf_class(*conf_args)
 
2205
        # Access an option to trigger a load
 
2206
        conf.get_option(name)
 
2207
        self.assertLength(expected_nb_calls, calls)
 
2208
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2209
 
 
2210
    def test_load_hook_remote_branch(self):
 
2211
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2212
        self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
 
2213
 
 
2214
    def test_load_hook_remote_bzrdir(self):
 
2215
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2216
        # The config file doesn't exist, set an option to force its creation
 
2217
        conf = remote_bzrdir._get_config()
 
2218
        conf.set_option('remotedir', 'file')
 
2219
        # We get one call for the server and one call for the client, this is
 
2220
        # caused by the differences in implementations betwen
 
2221
        # SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
 
2222
        # SmartServerBranchGetConfigFile (in smart/branch.py)
 
2223
        self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
 
2224
 
 
2225
    def assertSaveHook(self, conf):
 
2226
        calls = []
 
2227
        def hook(*args):
 
2228
            calls.append(args)
 
2229
        config.OldConfigHooks.install_named_hook('save', hook, None)
 
2230
        self.addCleanup(
 
2231
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
 
2232
        self.assertLength(0, calls)
 
2233
        # Setting an option triggers a save
 
2234
        conf.set_option('foo', 'bar')
 
2235
        self.assertLength(1, calls)
 
2236
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2237
 
 
2238
    def test_save_hook_remote_branch(self):
 
2239
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2240
        self.addCleanup(remote_branch.lock_write().unlock)
 
2241
        self.assertSaveHook(remote_branch._get_config())
 
2242
 
 
2243
    def test_save_hook_remote_bzrdir(self):
 
2244
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2245
        self.addCleanup(remote_branch.lock_write().unlock)
 
2246
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2247
        self.assertSaveHook(remote_bzrdir._get_config())
 
2248
 
 
2249
 
 
2250
class TestOption(tests.TestCase):
 
2251
 
 
2252
    def test_default_value(self):
 
2253
        opt = config.Option('foo', default='bar')
 
2254
        self.assertEquals('bar', opt.get_default())
 
2255
 
 
2256
    def test_default_value_from_env(self):
 
2257
        opt = config.Option('foo', default='bar', default_from_env=['FOO'])
 
2258
        self.overrideEnv('FOO', 'quux')
 
2259
        # Env variable provides a default taking over the option one
 
2260
        self.assertEquals('quux', opt.get_default())
 
2261
        
 
2262
    def test_first_default_value_from_env_wins(self):
 
2263
        opt = config.Option('foo', default='bar',
 
2264
                            default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
 
2265
        self.overrideEnv('FOO', 'foo')
 
2266
        self.overrideEnv('BAZ', 'baz')
 
2267
        # The first env var set wins
 
2268
        self.assertEquals('foo', opt.get_default())
 
2269
 
 
2270
 
 
2271
class TestOptionRegistry(tests.TestCase):
 
2272
 
 
2273
    def setUp(self):
 
2274
        super(TestOptionRegistry, self).setUp()
 
2275
        # Always start with an empty registry
 
2276
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
2277
        self.registry = config.option_registry
 
2278
 
 
2279
    def test_register(self):
 
2280
        opt = config.Option('foo')
 
2281
        self.registry.register(opt)
 
2282
        self.assertIs(opt, self.registry.get('foo'))
 
2283
 
 
2284
    def test_registered_help(self):
 
2285
        opt = config.Option('foo', help='A simple option')
 
2286
        self.registry.register(opt)
 
2287
        self.assertEquals('A simple option', self.registry.get_help('foo'))
 
2288
 
 
2289
    lazy_option = config.Option('lazy_foo', help='Lazy help')
 
2290
 
 
2291
    def test_register_lazy(self):
 
2292
        self.registry.register_lazy('lazy_foo', self.__module__,
 
2293
                                    'TestOptionRegistry.lazy_option')
 
2294
        self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
 
2295
 
 
2296
    def test_registered_lazy_help(self):
 
2297
        self.registry.register_lazy('lazy_foo', self.__module__,
 
2298
                                    'TestOptionRegistry.lazy_option')
 
2299
        self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
 
2300
 
 
2301
 
 
2302
class TestRegisteredOptions(tests.TestCase):
 
2303
    """All registered options should verify some constraints."""
 
2304
 
 
2305
    scenarios = [(key, {'option_name': key, 'option': option}) for key, option
 
2306
                 in config.option_registry.iteritems()]
 
2307
 
 
2308
    def setUp(self):
 
2309
        super(TestRegisteredOptions, self).setUp()
 
2310
        self.registry = config.option_registry
 
2311
 
 
2312
    def test_proper_name(self):
 
2313
        # An option should be registered under its own name, this can't be
 
2314
        # checked at registration time for the lazy ones.
 
2315
        self.assertEquals(self.option_name, self.option.name)
 
2316
 
 
2317
    def test_help_is_set(self):
 
2318
        option_help = self.registry.get_help(self.option_name)
 
2319
        self.assertNotEquals(None, option_help)
 
2320
        # Come on, think about the user, he really wants to know what the
 
2321
        # option is about
 
2322
        self.assertIsNot(None, option_help)
 
2323
        self.assertNotEquals('', option_help)
 
2324
 
 
2325
 
 
2326
class TestSection(tests.TestCase):
 
2327
 
 
2328
    # FIXME: Parametrize so that all sections produced by Stores run these
 
2329
    # tests -- vila 2011-04-01
 
2330
 
 
2331
    def test_get_a_value(self):
 
2332
        a_dict = dict(foo='bar')
 
2333
        section = config.Section('myID', a_dict)
 
2334
        self.assertEquals('bar', section.get('foo'))
 
2335
 
 
2336
    def test_get_unknown_option(self):
 
2337
        a_dict = dict()
 
2338
        section = config.Section(None, a_dict)
 
2339
        self.assertEquals('out of thin air',
 
2340
                          section.get('foo', 'out of thin air'))
 
2341
 
 
2342
    def test_options_is_shared(self):
 
2343
        a_dict = dict()
 
2344
        section = config.Section(None, a_dict)
 
2345
        self.assertIs(a_dict, section.options)
 
2346
 
 
2347
 
 
2348
class TestMutableSection(tests.TestCase):
 
2349
 
 
2350
    # FIXME: Parametrize so that all sections (including os.environ and the
 
2351
    # ones produced by Stores) run these tests -- vila 2011-04-01
 
2352
 
 
2353
    def test_set(self):
 
2354
        a_dict = dict(foo='bar')
 
2355
        section = config.MutableSection('myID', a_dict)
 
2356
        section.set('foo', 'new_value')
 
2357
        self.assertEquals('new_value', section.get('foo'))
 
2358
        # The change appears in the shared section
 
2359
        self.assertEquals('new_value', a_dict.get('foo'))
 
2360
        # We keep track of the change
 
2361
        self.assertTrue('foo' in section.orig)
 
2362
        self.assertEquals('bar', section.orig.get('foo'))
 
2363
 
 
2364
    def test_set_preserve_original_once(self):
 
2365
        a_dict = dict(foo='bar')
 
2366
        section = config.MutableSection('myID', a_dict)
 
2367
        section.set('foo', 'first_value')
 
2368
        section.set('foo', 'second_value')
 
2369
        # We keep track of the original value
 
2370
        self.assertTrue('foo' in section.orig)
 
2371
        self.assertEquals('bar', section.orig.get('foo'))
 
2372
 
 
2373
    def test_remove(self):
 
2374
        a_dict = dict(foo='bar')
 
2375
        section = config.MutableSection('myID', a_dict)
 
2376
        section.remove('foo')
 
2377
        # We get None for unknown options via the default value
 
2378
        self.assertEquals(None, section.get('foo'))
 
2379
        # Or we just get the default value
 
2380
        self.assertEquals('unknown', section.get('foo', 'unknown'))
 
2381
        self.assertFalse('foo' in section.options)
 
2382
        # We keep track of the deletion
 
2383
        self.assertTrue('foo' in section.orig)
 
2384
        self.assertEquals('bar', section.orig.get('foo'))
 
2385
 
 
2386
    def test_remove_new_option(self):
 
2387
        a_dict = dict()
 
2388
        section = config.MutableSection('myID', a_dict)
 
2389
        section.set('foo', 'bar')
 
2390
        section.remove('foo')
 
2391
        self.assertFalse('foo' in section.options)
 
2392
        # The option didn't exist initially so it we need to keep track of it
 
2393
        # with a special value
 
2394
        self.assertTrue('foo' in section.orig)
 
2395
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
 
2396
 
 
2397
 
 
2398
class TestStore(tests.TestCaseWithTransport):
 
2399
 
 
2400
    def assertSectionContent(self, expected, section):
 
2401
        """Assert that some options have the proper values in a section."""
 
2402
        expected_name, expected_options = expected
 
2403
        self.assertEquals(expected_name, section.id)
 
2404
        self.assertEquals(
 
2405
            expected_options,
 
2406
            dict([(k, section.get(k)) for k in expected_options.keys()]))
 
2407
 
 
2408
 
 
2409
class TestReadonlyStore(TestStore):
 
2410
 
 
2411
    scenarios = [(key, {'get_store': builder}) for key, builder
 
2412
                 in config.test_store_builder_registry.iteritems()]
 
2413
 
 
2414
    def setUp(self):
 
2415
        super(TestReadonlyStore, self).setUp()
 
2416
 
 
2417
    def test_building_delays_load(self):
 
2418
        store = self.get_store(self)
 
2419
        self.assertEquals(False, store.is_loaded())
 
2420
        store._load_from_string('')
 
2421
        self.assertEquals(True, store.is_loaded())
 
2422
 
 
2423
    def test_get_no_sections_for_empty(self):
 
2424
        store = self.get_store(self)
 
2425
        store._load_from_string('')
 
2426
        self.assertEquals([], list(store.get_sections()))
 
2427
 
 
2428
    def test_get_default_section(self):
 
2429
        store = self.get_store(self)
 
2430
        store._load_from_string('foo=bar')
 
2431
        sections = list(store.get_sections())
 
2432
        self.assertLength(1, sections)
 
2433
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2434
 
 
2435
    def test_get_named_section(self):
 
2436
        store = self.get_store(self)
 
2437
        store._load_from_string('[baz]\nfoo=bar')
 
2438
        sections = list(store.get_sections())
 
2439
        self.assertLength(1, sections)
 
2440
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
2441
 
 
2442
    def test_load_from_string_fails_for_non_empty_store(self):
 
2443
        store = self.get_store(self)
 
2444
        store._load_from_string('foo=bar')
 
2445
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
 
2446
 
 
2447
 
 
2448
class TestIniFileStoreContent(tests.TestCaseWithTransport):
 
2449
    """Simulate loading a config store without content of various encodings.
 
2450
 
 
2451
    All files produced by bzr are in utf8 content.
 
2452
 
 
2453
    Users may modify them manually and end up with a file that can't be
 
2454
    loaded. We need to issue proper error messages in this case.
 
2455
    """
 
2456
 
 
2457
    invalid_utf8_char = '\xff'
 
2458
 
 
2459
    def test_load_utf8(self):
 
2460
        """Ensure we can load an utf8-encoded file."""
 
2461
        t = self.get_transport()
 
2462
        # From http://pad.lv/799212
 
2463
        unicode_user = u'b\N{Euro Sign}ar'
 
2464
        unicode_content = u'user=%s' % (unicode_user,)
 
2465
        utf8_content = unicode_content.encode('utf8')
 
2466
        # Store the raw content in the config file
 
2467
        t.put_bytes('foo.conf', utf8_content)
 
2468
        store = config.IniFileStore(t, 'foo.conf')
 
2469
        store.load()
 
2470
        stack = config.Stack([store.get_sections], store)
 
2471
        self.assertEquals(unicode_user, stack.get('user'))
 
2472
 
 
2473
    def test_load_non_ascii(self):
 
2474
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
 
2475
        t = self.get_transport()
 
2476
        t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
 
2477
        store = config.IniFileStore(t, 'foo.conf')
 
2478
        self.assertRaises(errors.ConfigContentError, store.load)
 
2479
 
 
2480
    def test_load_erroneous_content(self):
 
2481
        """Ensure we display a proper error on content that can't be parsed."""
 
2482
        t = self.get_transport()
 
2483
        t.put_bytes('foo.conf', '[open_section\n')
 
2484
        store = config.IniFileStore(t, 'foo.conf')
 
2485
        self.assertRaises(errors.ParseConfigError, store.load)
 
2486
 
 
2487
 
 
2488
class TestIniConfigContent(tests.TestCaseWithTransport):
 
2489
    """Simulate loading a IniBasedConfig without content of various encodings.
 
2490
 
 
2491
    All files produced by bzr are in utf8 content.
 
2492
 
 
2493
    Users may modify them manually and end up with a file that can't be
 
2494
    loaded. We need to issue proper error messages in this case.
 
2495
    """
 
2496
 
 
2497
    invalid_utf8_char = '\xff'
 
2498
 
 
2499
    def test_load_utf8(self):
 
2500
        """Ensure we can load an utf8-encoded file."""
 
2501
        # From http://pad.lv/799212
 
2502
        unicode_user = u'b\N{Euro Sign}ar'
 
2503
        unicode_content = u'user=%s' % (unicode_user,)
 
2504
        utf8_content = unicode_content.encode('utf8')
 
2505
        # Store the raw content in the config file
 
2506
        with open('foo.conf', 'wb') as f:
 
2507
            f.write(utf8_content)
 
2508
        conf = config.IniBasedConfig(file_name='foo.conf')
 
2509
        self.assertEquals(unicode_user, conf.get_user_option('user'))
 
2510
 
 
2511
    def test_load_badly_encoded_content(self):
 
2512
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
 
2513
        with open('foo.conf', 'wb') as f:
 
2514
            f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
 
2515
        conf = config.IniBasedConfig(file_name='foo.conf')
 
2516
        self.assertRaises(errors.ConfigContentError, conf._get_parser)
 
2517
 
 
2518
    def test_load_erroneous_content(self):
 
2519
        """Ensure we display a proper error on content that can't be parsed."""
 
2520
        with open('foo.conf', 'wb') as f:
 
2521
            f.write('[open_section\n')
 
2522
        conf = config.IniBasedConfig(file_name='foo.conf')
 
2523
        self.assertRaises(errors.ParseConfigError, conf._get_parser)
 
2524
 
 
2525
 
 
2526
class TestMutableStore(TestStore):
 
2527
 
 
2528
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
 
2529
                 in config.test_store_builder_registry.iteritems()]
 
2530
 
 
2531
    def setUp(self):
 
2532
        super(TestMutableStore, self).setUp()
 
2533
        self.transport = self.get_transport()
 
2534
 
 
2535
    def has_store(self, store):
 
2536
        store_basename = urlutils.relative_url(self.transport.external_url(),
 
2537
                                               store.external_url())
 
2538
        return self.transport.has(store_basename)
 
2539
 
 
2540
    def test_save_empty_creates_no_file(self):
 
2541
        # FIXME: There should be a better way than relying on the test
 
2542
        # parametrization to identify branch.conf -- vila 2011-0526
 
2543
        if self.store_id in ('branch', 'remote_branch'):
 
2544
            raise tests.TestNotApplicable(
 
2545
                'branch.conf is *always* created when a branch is initialized')
 
2546
        store = self.get_store(self)
 
2547
        store.save()
 
2548
        self.assertEquals(False, self.has_store(store))
 
2549
 
 
2550
    def test_save_emptied_succeeds(self):
 
2551
        store = self.get_store(self)
 
2552
        store._load_from_string('foo=bar\n')
 
2553
        section = store.get_mutable_section(None)
 
2554
        section.remove('foo')
 
2555
        store.save()
 
2556
        self.assertEquals(True, self.has_store(store))
 
2557
        modified_store = self.get_store(self)
 
2558
        sections = list(modified_store.get_sections())
 
2559
        self.assertLength(0, sections)
 
2560
 
 
2561
    def test_save_with_content_succeeds(self):
 
2562
        # FIXME: There should be a better way than relying on the test
 
2563
        # parametrization to identify branch.conf -- vila 2011-0526
 
2564
        if self.store_id in ('branch', 'remote_branch'):
 
2565
            raise tests.TestNotApplicable(
 
2566
                'branch.conf is *always* created when a branch is initialized')
 
2567
        store = self.get_store(self)
 
2568
        store._load_from_string('foo=bar\n')
 
2569
        self.assertEquals(False, self.has_store(store))
 
2570
        store.save()
 
2571
        self.assertEquals(True, self.has_store(store))
 
2572
        modified_store = self.get_store(self)
 
2573
        sections = list(modified_store.get_sections())
 
2574
        self.assertLength(1, sections)
 
2575
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2576
 
 
2577
    def test_set_option_in_empty_store(self):
 
2578
        store = self.get_store(self)
 
2579
        section = store.get_mutable_section(None)
 
2580
        section.set('foo', 'bar')
 
2581
        store.save()
 
2582
        modified_store = self.get_store(self)
 
2583
        sections = list(modified_store.get_sections())
 
2584
        self.assertLength(1, sections)
 
2585
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2586
 
 
2587
    def test_set_option_in_default_section(self):
 
2588
        store = self.get_store(self)
 
2589
        store._load_from_string('')
 
2590
        section = store.get_mutable_section(None)
 
2591
        section.set('foo', 'bar')
 
2592
        store.save()
 
2593
        modified_store = self.get_store(self)
 
2594
        sections = list(modified_store.get_sections())
 
2595
        self.assertLength(1, sections)
 
2596
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2597
 
 
2598
    def test_set_option_in_named_section(self):
 
2599
        store = self.get_store(self)
 
2600
        store._load_from_string('')
 
2601
        section = store.get_mutable_section('baz')
 
2602
        section.set('foo', 'bar')
 
2603
        store.save()
 
2604
        modified_store = self.get_store(self)
 
2605
        sections = list(modified_store.get_sections())
 
2606
        self.assertLength(1, sections)
 
2607
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
2608
 
 
2609
    def test_load_hook(self):
 
2610
        # We first needs to ensure that the store exists
 
2611
        store = self.get_store(self)
 
2612
        section = store.get_mutable_section('baz')
 
2613
        section.set('foo', 'bar')
 
2614
        store.save()
 
2615
        # Now we can try to load it
 
2616
        store = self.get_store(self)
 
2617
        calls = []
 
2618
        def hook(*args):
 
2619
            calls.append(args)
 
2620
        config.ConfigHooks.install_named_hook('load', hook, None)
 
2621
        self.assertLength(0, calls)
 
2622
        store.load()
 
2623
        self.assertLength(1, calls)
 
2624
        self.assertEquals((store,), calls[0])
 
2625
 
 
2626
    def test_save_hook(self):
 
2627
        calls = []
 
2628
        def hook(*args):
 
2629
            calls.append(args)
 
2630
        config.ConfigHooks.install_named_hook('save', hook, None)
 
2631
        self.assertLength(0, calls)
 
2632
        store = self.get_store(self)
 
2633
        section = store.get_mutable_section('baz')
 
2634
        section.set('foo', 'bar')
 
2635
        store.save()
 
2636
        self.assertLength(1, calls)
 
2637
        self.assertEquals((store,), calls[0])
 
2638
 
 
2639
 
 
2640
class TestIniFileStore(TestStore):
 
2641
 
 
2642
    def test_loading_unknown_file_fails(self):
 
2643
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
 
2644
        self.assertRaises(errors.NoSuchFile, store.load)
 
2645
 
 
2646
    def test_invalid_content(self):
 
2647
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
2648
        self.assertEquals(False, store.is_loaded())
 
2649
        exc = self.assertRaises(
 
2650
            errors.ParseConfigError, store._load_from_string,
 
2651
            'this is invalid !')
 
2652
        self.assertEndsWith(exc.filename, 'foo.conf')
 
2653
        # And the load failed
 
2654
        self.assertEquals(False, store.is_loaded())
 
2655
 
 
2656
    def test_get_embedded_sections(self):
 
2657
        # A more complicated example (which also shows that section names and
 
2658
        # option names share the same name space...)
 
2659
        # FIXME: This should be fixed by forbidding dicts as values ?
 
2660
        # -- vila 2011-04-05
 
2661
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
 
2662
        store._load_from_string('''
 
2663
foo=bar
 
2664
l=1,2
 
2665
[DEFAULT]
 
2666
foo_in_DEFAULT=foo_DEFAULT
 
2667
[bar]
 
2668
foo_in_bar=barbar
 
2669
[baz]
 
2670
foo_in_baz=barbaz
 
2671
[[qux]]
 
2672
foo_in_qux=quux
 
2673
''')
 
2674
        sections = list(store.get_sections())
 
2675
        self.assertLength(4, sections)
 
2676
        # The default section has no name.
 
2677
        # List values are provided as lists
 
2678
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
 
2679
                                  sections[0])
 
2680
        self.assertSectionContent(
 
2681
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
 
2682
        self.assertSectionContent(
 
2683
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
 
2684
        # sub sections are provided as embedded dicts.
 
2685
        self.assertSectionContent(
 
2686
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
 
2687
            sections[3])
 
2688
 
 
2689
 
 
2690
class TestLockableIniFileStore(TestStore):
 
2691
 
 
2692
    def test_create_store_in_created_dir(self):
 
2693
        self.assertPathDoesNotExist('dir')
 
2694
        t = self.get_transport('dir/subdir')
 
2695
        store = config.LockableIniFileStore(t, 'foo.conf')
 
2696
        store.get_mutable_section(None).set('foo', 'bar')
 
2697
        store.save()
 
2698
        self.assertPathExists('dir/subdir')
 
2699
 
 
2700
 
 
2701
class TestConcurrentStoreUpdates(TestStore):
 
2702
    """Test that Stores properly handle conccurent updates.
 
2703
 
 
2704
    New Store implementation may fail some of these tests but until such
 
2705
    implementations exist it's hard to properly filter them from the scenarios
 
2706
    applied here. If you encounter such a case, contact the bzr devs.
 
2707
    """
 
2708
 
 
2709
    scenarios = [(key, {'get_stack': builder}) for key, builder
 
2710
                 in config.test_stack_builder_registry.iteritems()]
 
2711
 
 
2712
    def setUp(self):
 
2713
        super(TestConcurrentStoreUpdates, self).setUp()
 
2714
        self._content = 'one=1\ntwo=2\n'
 
2715
        self.stack = self.get_stack(self)
 
2716
        if not isinstance(self.stack, config._CompatibleStack):
 
2717
            raise tests.TestNotApplicable(
 
2718
                '%s is not meant to be compatible with the old config design'
 
2719
                % (self.stack,))
 
2720
        self.stack.store._load_from_string(self._content)
 
2721
        # Flush the store
 
2722
        self.stack.store.save()
 
2723
 
 
2724
    def test_simple_read_access(self):
 
2725
        self.assertEquals('1', self.stack.get('one'))
 
2726
 
 
2727
    def test_simple_write_access(self):
 
2728
        self.stack.set('one', 'one')
 
2729
        self.assertEquals('one', self.stack.get('one'))
 
2730
 
 
2731
    def test_listen_to_the_last_speaker(self):
 
2732
        c1 = self.stack
 
2733
        c2 = self.get_stack(self)
 
2734
        c1.set('one', 'ONE')
 
2735
        c2.set('two', 'TWO')
 
2736
        self.assertEquals('ONE', c1.get('one'))
 
2737
        self.assertEquals('TWO', c2.get('two'))
 
2738
        # The second update respect the first one
 
2739
        self.assertEquals('ONE', c2.get('one'))
 
2740
 
 
2741
    def test_last_speaker_wins(self):
 
2742
        # If the same config is not shared, the same variable modified twice
 
2743
        # can only see a single result.
 
2744
        c1 = self.stack
 
2745
        c2 = self.get_stack(self)
 
2746
        c1.set('one', 'c1')
 
2747
        c2.set('one', 'c2')
 
2748
        self.assertEquals('c2', c2.get('one'))
 
2749
        # The first modification is still available until another refresh
 
2750
        # occur
 
2751
        self.assertEquals('c1', c1.get('one'))
 
2752
        c1.set('two', 'done')
 
2753
        self.assertEquals('c2', c1.get('one'))
 
2754
 
 
2755
    def test_writes_are_serialized(self):
 
2756
        c1 = self.stack
 
2757
        c2 = self.get_stack(self)
 
2758
 
 
2759
        # We spawn a thread that will pause *during* the config saving.
 
2760
        before_writing = threading.Event()
 
2761
        after_writing = threading.Event()
 
2762
        writing_done = threading.Event()
 
2763
        c1_save_without_locking_orig = c1.store.save_without_locking
 
2764
        def c1_save_without_locking():
 
2765
            before_writing.set()
 
2766
            c1_save_without_locking_orig()
 
2767
            # The lock is held. We wait for the main thread to decide when to
 
2768
            # continue
 
2769
            after_writing.wait()
 
2770
        c1.store.save_without_locking = c1_save_without_locking
 
2771
        def c1_set():
 
2772
            c1.set('one', 'c1')
 
2773
            writing_done.set()
 
2774
        t1 = threading.Thread(target=c1_set)
 
2775
        # Collect the thread after the test
 
2776
        self.addCleanup(t1.join)
 
2777
        # Be ready to unblock the thread if the test goes wrong
 
2778
        self.addCleanup(after_writing.set)
 
2779
        t1.start()
 
2780
        before_writing.wait()
 
2781
        self.assertRaises(errors.LockContention,
 
2782
                          c2.set, 'one', 'c2')
 
2783
        self.assertEquals('c1', c1.get('one'))
 
2784
        # Let the lock be released
 
2785
        after_writing.set()
 
2786
        writing_done.wait()
 
2787
        c2.set('one', 'c2')
 
2788
        self.assertEquals('c2', c2.get('one'))
 
2789
 
 
2790
    def test_read_while_writing(self):
 
2791
       c1 = self.stack
 
2792
       # We spawn a thread that will pause *during* the write
 
2793
       ready_to_write = threading.Event()
 
2794
       do_writing = threading.Event()
 
2795
       writing_done = threading.Event()
 
2796
       # We override the _save implementation so we know the store is locked
 
2797
       c1_save_without_locking_orig = c1.store.save_without_locking
 
2798
       def c1_save_without_locking():
 
2799
           ready_to_write.set()
 
2800
           # The lock is held. We wait for the main thread to decide when to
 
2801
           # continue
 
2802
           do_writing.wait()
 
2803
           c1_save_without_locking_orig()
 
2804
           writing_done.set()
 
2805
       c1.store.save_without_locking = c1_save_without_locking
 
2806
       def c1_set():
 
2807
           c1.set('one', 'c1')
 
2808
       t1 = threading.Thread(target=c1_set)
 
2809
       # Collect the thread after the test
 
2810
       self.addCleanup(t1.join)
 
2811
       # Be ready to unblock the thread if the test goes wrong
 
2812
       self.addCleanup(do_writing.set)
 
2813
       t1.start()
 
2814
       # Ensure the thread is ready to write
 
2815
       ready_to_write.wait()
 
2816
       self.assertEquals('c1', c1.get('one'))
 
2817
       # If we read during the write, we get the old value
 
2818
       c2 = self.get_stack(self)
 
2819
       self.assertEquals('1', c2.get('one'))
 
2820
       # Let the writing occur and ensure it occurred
 
2821
       do_writing.set()
 
2822
       writing_done.wait()
 
2823
       # Now we get the updated value
 
2824
       c3 = self.get_stack(self)
 
2825
       self.assertEquals('c1', c3.get('one'))
 
2826
 
 
2827
    # FIXME: It may be worth looking into removing the lock dir when it's not
 
2828
    # needed anymore and look at possible fallouts for concurrent lockers. This
 
2829
    # will matter if/when we use config files outside of bazaar directories
 
2830
    # (.bazaar or .bzr) -- vila 20110-04-11
 
2831
 
 
2832
 
 
2833
class TestSectionMatcher(TestStore):
 
2834
 
 
2835
    scenarios = [('location', {'matcher': config.LocationMatcher})]
 
2836
 
 
2837
    def get_store(self, file_name):
 
2838
        return config.IniFileStore(self.get_readonly_transport(), file_name)
 
2839
 
 
2840
    def test_no_matches_for_empty_stores(self):
 
2841
        store = self.get_store('foo.conf')
 
2842
        store._load_from_string('')
 
2843
        matcher = self.matcher(store, '/bar')
 
2844
        self.assertEquals([], list(matcher.get_sections()))
 
2845
 
 
2846
    def test_build_doesnt_load_store(self):
 
2847
        store = self.get_store('foo.conf')
 
2848
        matcher = self.matcher(store, '/bar')
 
2849
        self.assertFalse(store.is_loaded())
 
2850
 
 
2851
 
 
2852
class TestLocationSection(tests.TestCase):
 
2853
 
 
2854
    def get_section(self, options, extra_path):
 
2855
        section = config.Section('foo', options)
 
2856
        # We don't care about the length so we use '0'
 
2857
        return config.LocationSection(section, 0, extra_path)
 
2858
 
 
2859
    def test_simple_option(self):
 
2860
        section = self.get_section({'foo': 'bar'}, '')
 
2861
        self.assertEquals('bar', section.get('foo'))
 
2862
 
 
2863
    def test_option_with_extra_path(self):
 
2864
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
 
2865
                                   'baz')
 
2866
        self.assertEquals('bar/baz', section.get('foo'))
 
2867
 
 
2868
    def test_invalid_policy(self):
 
2869
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
 
2870
                                   'baz')
 
2871
        # invalid policies are ignored
 
2872
        self.assertEquals('bar', section.get('foo'))
 
2873
 
 
2874
 
 
2875
class TestLocationMatcher(TestStore):
 
2876
 
 
2877
    def get_store(self, file_name):
 
2878
        return config.IniFileStore(self.get_readonly_transport(), file_name)
 
2879
 
 
2880
    def test_unrelated_section_excluded(self):
 
2881
        store = self.get_store('foo.conf')
 
2882
        store._load_from_string('''
 
2883
[/foo]
 
2884
section=/foo
 
2885
[/foo/baz]
 
2886
section=/foo/baz
 
2887
[/foo/bar]
 
2888
section=/foo/bar
 
2889
[/foo/bar/baz]
 
2890
section=/foo/bar/baz
 
2891
[/quux/quux]
 
2892
section=/quux/quux
 
2893
''')
 
2894
        self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
 
2895
                           '/quux/quux'],
 
2896
                          [section.id for section in store.get_sections()])
 
2897
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
 
2898
        sections = list(matcher.get_sections())
 
2899
        self.assertEquals([3, 2],
 
2900
                          [section.length for section in sections])
 
2901
        self.assertEquals(['/foo/bar', '/foo'],
 
2902
                          [section.id for section in sections])
 
2903
        self.assertEquals(['quux', 'bar/quux'],
 
2904
                          [section.extra_path for section in sections])
 
2905
 
 
2906
    def test_more_specific_sections_first(self):
 
2907
        store = self.get_store('foo.conf')
 
2908
        store._load_from_string('''
 
2909
[/foo]
 
2910
section=/foo
 
2911
[/foo/bar]
 
2912
section=/foo/bar
 
2913
''')
 
2914
        self.assertEquals(['/foo', '/foo/bar'],
 
2915
                          [section.id for section in store.get_sections()])
 
2916
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
 
2917
        sections = list(matcher.get_sections())
 
2918
        self.assertEquals([3, 2],
 
2919
                          [section.length for section in sections])
 
2920
        self.assertEquals(['/foo/bar', '/foo'],
 
2921
                          [section.id for section in sections])
 
2922
        self.assertEquals(['baz', 'bar/baz'],
 
2923
                          [section.extra_path for section in sections])
 
2924
 
 
2925
    def test_appendpath_in_no_name_section(self):
 
2926
        # It's a bit weird to allow appendpath in a no-name section, but
 
2927
        # someone may found a use for it
 
2928
        store = self.get_store('foo.conf')
 
2929
        store._load_from_string('''
 
2930
foo=bar
 
2931
foo:policy = appendpath
 
2932
''')
 
2933
        matcher = config.LocationMatcher(store, 'dir/subdir')
 
2934
        sections = list(matcher.get_sections())
 
2935
        self.assertLength(1, sections)
 
2936
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
 
2937
 
 
2938
    def test_file_urls_are_normalized(self):
 
2939
        store = self.get_store('foo.conf')
 
2940
        if sys.platform == 'win32':
 
2941
            expected_url = 'file:///C:/dir/subdir'
 
2942
            expected_location = 'C:/dir/subdir'
 
2943
        else:
 
2944
            expected_url = 'file:///dir/subdir'
 
2945
            expected_location = '/dir/subdir'
 
2946
        matcher = config.LocationMatcher(store, expected_url)
 
2947
        self.assertEquals(expected_location, matcher.location)
 
2948
 
 
2949
 
 
2950
class TestStackGet(tests.TestCase):
 
2951
 
 
2952
    # FIXME: This should be parametrized for all known Stack or dedicated
 
2953
    # paramerized tests created to avoid bloating -- vila 2011-03-31
 
2954
 
 
2955
    def overrideOptionRegistry(self):
 
2956
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
2957
 
 
2958
    def test_single_config_get(self):
 
2959
        conf = dict(foo='bar')
 
2960
        conf_stack = config.Stack([conf])
 
2961
        self.assertEquals('bar', conf_stack.get('foo'))
 
2962
 
 
2963
    def test_get_with_registered_default_value(self):
 
2964
        conf_stack = config.Stack([dict()])
 
2965
        opt = config.Option('foo', default='bar')
 
2966
        self.overrideOptionRegistry()
 
2967
        config.option_registry.register('foo', opt)
 
2968
        self.assertEquals('bar', conf_stack.get('foo'))
 
2969
 
 
2970
    def test_get_without_registered_default_value(self):
 
2971
        conf_stack = config.Stack([dict()])
 
2972
        opt = config.Option('foo')
 
2973
        self.overrideOptionRegistry()
 
2974
        config.option_registry.register('foo', opt)
 
2975
        self.assertEquals(None, conf_stack.get('foo'))
 
2976
 
 
2977
    def test_get_without_default_value_for_not_registered(self):
 
2978
        conf_stack = config.Stack([dict()])
 
2979
        opt = config.Option('foo')
 
2980
        self.overrideOptionRegistry()
 
2981
        self.assertEquals(None, conf_stack.get('foo'))
 
2982
 
 
2983
    def test_get_first_definition(self):
 
2984
        conf1 = dict(foo='bar')
 
2985
        conf2 = dict(foo='baz')
 
2986
        conf_stack = config.Stack([conf1, conf2])
 
2987
        self.assertEquals('bar', conf_stack.get('foo'))
 
2988
 
 
2989
    def test_get_embedded_definition(self):
 
2990
        conf1 = dict(yy='12')
 
2991
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
 
2992
        conf_stack = config.Stack([conf1, conf2])
 
2993
        self.assertEquals('baz', conf_stack.get('foo'))
 
2994
 
 
2995
    def test_get_for_empty_section_callable(self):
 
2996
        conf_stack = config.Stack([lambda : []])
 
2997
        self.assertEquals(None, conf_stack.get('foo'))
 
2998
 
 
2999
    def test_get_for_broken_callable(self):
 
3000
        # Trying to use and invalid callable raises an exception on first use
 
3001
        conf_stack = config.Stack([lambda : object()])
 
3002
        self.assertRaises(TypeError, conf_stack.get, 'foo')
 
3003
 
 
3004
 
 
3005
class TestStackWithTransport(tests.TestCaseWithTransport):
 
3006
 
 
3007
    scenarios = [(key, {'get_stack': builder}) for key, builder
 
3008
                 in config.test_stack_builder_registry.iteritems()]
 
3009
 
 
3010
 
 
3011
class TestConcreteStacks(TestStackWithTransport):
 
3012
 
 
3013
    def test_build_stack(self):
 
3014
        # Just a smoke test to help debug builders
 
3015
        stack = self.get_stack(self)
 
3016
 
 
3017
 
 
3018
class TestStackGet(TestStackWithTransport):
 
3019
 
 
3020
    def setUp(self):
 
3021
        super(TestStackGet, self).setUp()
 
3022
        self.conf = self.get_stack(self)
 
3023
 
 
3024
    def test_get_for_empty_stack(self):
 
3025
        self.assertEquals(None, self.conf.get('foo'))
 
3026
 
 
3027
    def test_get_hook(self):
 
3028
        self.conf.store._load_from_string('foo=bar')
 
3029
        calls = []
 
3030
        def hook(*args):
 
3031
            calls.append(args)
 
3032
        config.ConfigHooks.install_named_hook('get', hook, None)
 
3033
        self.assertLength(0, calls)
 
3034
        value = self.conf.get('foo')
 
3035
        self.assertEquals('bar', value)
 
3036
        self.assertLength(1, calls)
 
3037
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
 
3038
 
 
3039
 
 
3040
class TestStackGetWithConverter(TestStackGet):
 
3041
 
 
3042
    def setUp(self):
 
3043
        super(TestStackGetWithConverter, self).setUp()
 
3044
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3045
        self.registry = config.option_registry
 
3046
 
 
3047
    def register_bool_option(self, name, default, invalid=None):
 
3048
        b = config.Option(name, default=default, help='A boolean.',
 
3049
                          from_unicode=config.bool_from_store,
 
3050
                          invalid=invalid)
 
3051
        self.registry.register(b)
 
3052
 
 
3053
    def test_get_with_bool_not_defined_default_true(self):
 
3054
        self.register_bool_option('foo', True)
 
3055
        self.assertEquals(True, self.conf.get('foo'))
 
3056
 
 
3057
    def test_get_with_bool_not_defined_default_false(self):
 
3058
        self.register_bool_option('foo', False)
 
3059
        self.assertEquals(False, self.conf.get('foo'))
 
3060
 
 
3061
    def test_get_with_bool_converter_not_default(self):
 
3062
        self.register_bool_option('foo', False)
 
3063
        self.conf.store._load_from_string('foo=yes')
 
3064
        self.assertEquals(True, self.conf.get('foo'))
 
3065
 
 
3066
    def test_get_with_bool_converter_invalid_string(self):
 
3067
        self.register_bool_option('foo', False)
 
3068
        self.conf.store._load_from_string('foo=not-a-boolean')
 
3069
        self.assertEquals(False, self.conf.get('foo'))
 
3070
 
 
3071
    def test_get_with_bool_converter_invalid_list(self):
 
3072
        self.register_bool_option('foo', False)
 
3073
        self.conf.store._load_from_string('foo=not,a,boolean')
 
3074
        self.assertEquals(False, self.conf.get('foo'))
 
3075
 
 
3076
    def test_get_invalid_warns(self):
 
3077
        self.register_bool_option('foo', False, invalid='warning')
 
3078
        self.conf.store._load_from_string('foo=not-a-boolean')
 
3079
        warnings = []
 
3080
        def warning(*args):
 
3081
            warnings.append(args[0] % args[1:])
 
3082
        self.overrideAttr(trace, 'warning', warning)
 
3083
        self.assertEquals(False, self.conf.get('foo'))
 
3084
        self.assertLength(1, warnings)
 
3085
        self.assertEquals('Value "not-a-boolean" is not valid for "foo"',
 
3086
                          warnings[0])
 
3087
 
 
3088
    def test_get_invalid_errors(self):
 
3089
        self.register_bool_option('foo', False, invalid='error')
 
3090
        self.conf.store._load_from_string('foo=not-a-boolean')
 
3091
        self.assertRaises(errors.ConfigOptionValueError, self.conf.get, 'foo')
 
3092
 
 
3093
    def register_integer_option(self, name, default):
 
3094
        i = config.Option(name, default=default, help='An integer.',
 
3095
                          from_unicode=config.int_from_store)
 
3096
        self.registry.register(i)
 
3097
 
 
3098
    def test_get_with_integer_not_defined_returns_default(self):
 
3099
        self.register_integer_option('foo', 42)
 
3100
        self.assertEquals(42, self.conf.get('foo'))
 
3101
 
 
3102
    def test_get_with_integer_converter_not_default(self):
 
3103
        self.register_integer_option('foo', 42)
 
3104
        self.conf.store._load_from_string('foo=16')
 
3105
        self.assertEquals(16, self.conf.get('foo'))
 
3106
 
 
3107
    def test_get_with_integer_converter_invalid_string(self):
 
3108
        # We don't set a default value
 
3109
        self.register_integer_option('foo', None)
 
3110
        self.conf.store._load_from_string('foo=forty-two')
 
3111
        # No default value, so we should get None
 
3112
        self.assertEquals(None, self.conf.get('foo'))
 
3113
 
 
3114
    def test_get_with_integer_converter_invalid_list(self):
 
3115
        # We don't set a default value
 
3116
        self.register_integer_option('foo', None)
 
3117
        self.conf.store._load_from_string('foo=a,list')
 
3118
        # No default value, so we should get None
 
3119
        self.assertEquals(None, self.conf.get('foo'))
 
3120
 
 
3121
    def register_list_option(self, name, default):
 
3122
        l = config.Option(name, default=default, help='A list.',
 
3123
                          from_unicode=config.list_from_store)
 
3124
        self.registry.register(l)
 
3125
 
 
3126
    def test_get_with_list_not_defined_returns_default(self):
 
3127
        self.register_list_option('foo', [])
 
3128
        self.assertEquals([], self.conf.get('foo'))
 
3129
 
 
3130
    def test_get_with_list_converter_nothing(self):
 
3131
        self.register_list_option('foo', [1])
 
3132
        self.conf.store._load_from_string('foo=')
 
3133
        self.assertEquals([], self.conf.get('foo'))
 
3134
 
 
3135
    def test_get_with_list_converter_no_item(self):
 
3136
        self.register_list_option('foo', [1])
 
3137
        self.conf.store._load_from_string('foo=,')
 
3138
        self.assertEquals([], self.conf.get('foo'))
 
3139
 
 
3140
    def test_get_with_list_converter_one_boolean(self):
 
3141
        self.register_list_option('foo', [1])
 
3142
        self.conf.store._load_from_string('foo=True')
 
3143
        # We get a list of one string
 
3144
        self.assertEquals(['True'], self.conf.get('foo'))
 
3145
 
 
3146
    def test_get_with_list_converter_one_integer(self):
 
3147
        self.register_list_option('foo', [1])
 
3148
        self.conf.store._load_from_string('foo=2')
 
3149
        # We get a list of one string
 
3150
        self.assertEquals(['2'], self.conf.get('foo'))
 
3151
 
 
3152
    def test_get_with_list_converter_one_string(self):
 
3153
        self.register_list_option('foo', ['foo'])
 
3154
        self.conf.store._load_from_string('foo=bar')
 
3155
        # We get a list of one string
 
3156
        self.assertEquals(['bar'], self.conf.get('foo'))
 
3157
 
 
3158
    def test_get_with_list_converter_many_items(self):
 
3159
        self.register_list_option('foo', [1])
 
3160
        self.conf.store._load_from_string('foo=m,o,r,e')
 
3161
        self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
 
3162
 
 
3163
 
 
3164
class TestStackSet(TestStackWithTransport):
 
3165
 
 
3166
    def test_simple_set(self):
 
3167
        conf = self.get_stack(self)
 
3168
        conf.store._load_from_string('foo=bar')
 
3169
        self.assertEquals('bar', conf.get('foo'))
 
3170
        conf.set('foo', 'baz')
 
3171
        # Did we get it back ?
 
3172
        self.assertEquals('baz', conf.get('foo'))
 
3173
 
 
3174
    def test_set_creates_a_new_section(self):
 
3175
        conf = self.get_stack(self)
 
3176
        conf.set('foo', 'baz')
 
3177
        self.assertEquals, 'baz', conf.get('foo')
 
3178
 
 
3179
    def test_set_hook(self):
 
3180
        calls = []
 
3181
        def hook(*args):
 
3182
            calls.append(args)
 
3183
        config.ConfigHooks.install_named_hook('set', hook, None)
 
3184
        self.assertLength(0, calls)
 
3185
        conf = self.get_stack(self)
 
3186
        conf.set('foo', 'bar')
 
3187
        self.assertLength(1, calls)
 
3188
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
 
3189
 
 
3190
 
 
3191
class TestStackRemove(TestStackWithTransport):
 
3192
 
 
3193
    def test_remove_existing(self):
 
3194
        conf = self.get_stack(self)
 
3195
        conf.store._load_from_string('foo=bar')
 
3196
        self.assertEquals('bar', conf.get('foo'))
 
3197
        conf.remove('foo')
 
3198
        # Did we get it back ?
 
3199
        self.assertEquals(None, conf.get('foo'))
 
3200
 
 
3201
    def test_remove_unknown(self):
 
3202
        conf = self.get_stack(self)
 
3203
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
 
3204
 
 
3205
    def test_remove_hook(self):
 
3206
        calls = []
 
3207
        def hook(*args):
 
3208
            calls.append(args)
 
3209
        config.ConfigHooks.install_named_hook('remove', hook, None)
 
3210
        self.assertLength(0, calls)
 
3211
        conf = self.get_stack(self)
 
3212
        conf.store._load_from_string('foo=bar')
 
3213
        conf.remove('foo')
 
3214
        self.assertLength(1, calls)
 
3215
        self.assertEquals((conf, 'foo'), calls[0])
 
3216
 
 
3217
 
 
3218
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
 
3219
 
 
3220
    def setUp(self):
 
3221
        super(TestConfigGetOptions, self).setUp()
 
3222
        create_configs(self)
 
3223
 
 
3224
    def test_no_variable(self):
 
3225
        # Using branch should query branch, locations and bazaar
 
3226
        self.assertOptions([], self.branch_config)
 
3227
 
 
3228
    def test_option_in_bazaar(self):
 
3229
        self.bazaar_config.set_user_option('file', 'bazaar')
 
3230
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
 
3231
                           self.bazaar_config)
 
3232
 
 
3233
    def test_option_in_locations(self):
 
3234
        self.locations_config.set_user_option('file', 'locations')
 
3235
        self.assertOptions(
 
3236
            [('file', 'locations', self.tree.basedir, 'locations')],
 
3237
            self.locations_config)
 
3238
 
 
3239
    def test_option_in_branch(self):
 
3240
        self.branch_config.set_user_option('file', 'branch')
 
3241
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
 
3242
                           self.branch_config)
 
3243
 
 
3244
    def test_option_in_bazaar_and_branch(self):
 
3245
        self.bazaar_config.set_user_option('file', 'bazaar')
 
3246
        self.branch_config.set_user_option('file', 'branch')
 
3247
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
 
3248
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
3249
                           self.branch_config)
 
3250
 
 
3251
    def test_option_in_branch_and_locations(self):
 
3252
        # Hmm, locations override branch :-/
 
3253
        self.locations_config.set_user_option('file', 'locations')
 
3254
        self.branch_config.set_user_option('file', 'branch')
 
3255
        self.assertOptions(
 
3256
            [('file', 'locations', self.tree.basedir, 'locations'),
 
3257
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
3258
            self.branch_config)
 
3259
 
 
3260
    def test_option_in_bazaar_locations_and_branch(self):
 
3261
        self.bazaar_config.set_user_option('file', 'bazaar')
 
3262
        self.locations_config.set_user_option('file', 'locations')
 
3263
        self.branch_config.set_user_option('file', 'branch')
 
3264
        self.assertOptions(
 
3265
            [('file', 'locations', self.tree.basedir, 'locations'),
 
3266
             ('file', 'branch', 'DEFAULT', 'branch'),
 
3267
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
3268
            self.branch_config)
 
3269
 
 
3270
 
 
3271
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
 
3272
 
 
3273
    def setUp(self):
 
3274
        super(TestConfigRemoveOption, self).setUp()
 
3275
        create_configs_with_file_option(self)
 
3276
 
 
3277
    def test_remove_in_locations(self):
 
3278
        self.locations_config.remove_user_option('file', self.tree.basedir)
 
3279
        self.assertOptions(
 
3280
            [('file', 'branch', 'DEFAULT', 'branch'),
 
3281
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
3282
            self.branch_config)
 
3283
 
 
3284
    def test_remove_in_branch(self):
 
3285
        self.branch_config.remove_user_option('file')
 
3286
        self.assertOptions(
 
3287
            [('file', 'locations', self.tree.basedir, 'locations'),
 
3288
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
3289
            self.branch_config)
 
3290
 
 
3291
    def test_remove_in_bazaar(self):
 
3292
        self.bazaar_config.remove_user_option('file')
 
3293
        self.assertOptions(
 
3294
            [('file', 'locations', self.tree.basedir, 'locations'),
 
3295
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
3296
            self.branch_config)
 
3297
 
 
3298
 
 
3299
class TestConfigGetSections(tests.TestCaseWithTransport):
 
3300
 
 
3301
    def setUp(self):
 
3302
        super(TestConfigGetSections, self).setUp()
 
3303
        create_configs(self)
 
3304
 
 
3305
    def assertSectionNames(self, expected, conf, name=None):
 
3306
        """Check which sections are returned for a given config.
 
3307
 
 
3308
        If fallback configurations exist their sections can be included.
 
3309
 
 
3310
        :param expected: A list of section names.
 
3311
 
 
3312
        :param conf: The configuration that will be queried.
 
3313
 
 
3314
        :param name: An optional section name that will be passed to
 
3315
            get_sections().
 
3316
        """
 
3317
        sections = list(conf._get_sections(name))
 
3318
        self.assertLength(len(expected), sections)
 
3319
        self.assertEqual(expected, [name for name, _, _ in sections])
 
3320
 
 
3321
    def test_bazaar_default_section(self):
 
3322
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
 
3323
 
 
3324
    def test_locations_default_section(self):
 
3325
        # No sections are defined in an empty file
 
3326
        self.assertSectionNames([], self.locations_config)
 
3327
 
 
3328
    def test_locations_named_section(self):
 
3329
        self.locations_config.set_user_option('file', 'locations')
 
3330
        self.assertSectionNames([self.tree.basedir], self.locations_config)
 
3331
 
 
3332
    def test_locations_matching_sections(self):
 
3333
        loc_config = self.locations_config
 
3334
        loc_config.set_user_option('file', 'locations')
 
3335
        # We need to cheat a bit here to create an option in sections above and
 
3336
        # below the 'location' one.
 
3337
        parser = loc_config._get_parser()
 
3338
        # locations.cong deals with '/' ignoring native os.sep
 
3339
        location_names = self.tree.basedir.split('/')
 
3340
        parent = '/'.join(location_names[:-1])
 
3341
        child = '/'.join(location_names + ['child'])
 
3342
        parser[parent] = {}
 
3343
        parser[parent]['file'] = 'parent'
 
3344
        parser[child] = {}
 
3345
        parser[child]['file'] = 'child'
 
3346
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
 
3347
 
 
3348
    def test_branch_data_default_section(self):
 
3349
        self.assertSectionNames([None],
 
3350
                                self.branch_config._get_branch_data_config())
 
3351
 
 
3352
    def test_branch_default_sections(self):
 
3353
        # No sections are defined in an empty locations file
 
3354
        self.assertSectionNames([None, 'DEFAULT'],
 
3355
                                self.branch_config)
 
3356
        # Unless we define an option
 
3357
        self.branch_config._get_location_config().set_user_option(
 
3358
            'file', 'locations')
 
3359
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
 
3360
                                self.branch_config)
 
3361
 
 
3362
    def test_bazaar_named_section(self):
 
3363
        # We need to cheat as the API doesn't give direct access to sections
 
3364
        # other than DEFAULT.
 
3365
        self.bazaar_config.set_alias('bazaar', 'bzr')
 
3366
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
 
3367
 
 
3368
 
1315
3369
class TestAuthenticationConfigFile(tests.TestCase):
1316
3370
    """Test the authentication.conf file matching"""
1317
3371
 
1332
3386
        self.assertEquals({}, conf._get_config())
1333
3387
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1334
3388
 
 
3389
    def test_non_utf8_config(self):
 
3390
        conf = config.AuthenticationConfig(_file=StringIO(
 
3391
                'foo = bar\xff'))
 
3392
        self.assertRaises(errors.ConfigContentError, conf._get_config)
 
3393
 
1335
3394
    def test_missing_auth_section_header(self):
1336
3395
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1337
3396
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1595
3654
 
1596
3655
    def test_username_defaults_prompts(self):
1597
3656
        # 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)
 
3657
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
 
3658
        self._check_default_username_prompt(
 
3659
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
 
3660
        self._check_default_username_prompt(
 
3661
            u'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1603
3662
 
1604
3663
    def test_username_default_no_prompt(self):
1605
3664
        conf = config.AuthenticationConfig()
1611
3670
    def test_password_default_prompts(self):
1612
3671
        # HTTP prompts can't be tested here, see test_http.py
1613
3672
        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)
 
3673
            u'FTP %(user)s@%(host)s password: ', 'ftp')
 
3674
        self._check_default_password_prompt(
 
3675
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
 
3676
        self._check_default_password_prompt(
 
3677
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
1619
3678
        # SMTP port handling is a bit special (it's handled if embedded in the
1620
3679
        # host too)
1621
3680
        # FIXME: should we: forbid that, extend it to other schemes, leave
1622
3681
        # 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)
 
3682
        self._check_default_password_prompt(
 
3683
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
 
3684
        self._check_default_password_prompt(
 
3685
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
 
3686
        self._check_default_password_prompt(
 
3687
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
1630
3688
 
1631
3689
    def test_ssh_password_emits_warning(self):
1632
3690
        conf = config.AuthenticationConfig(_file=StringIO(
1812
3870
# test_user_prompted ?
1813
3871
class TestAuthenticationRing(tests.TestCaseWithTransport):
1814
3872
    pass
 
3873
 
 
3874
 
 
3875
class TestAutoUserId(tests.TestCase):
 
3876
    """Test inferring an automatic user name."""
 
3877
 
 
3878
    def test_auto_user_id(self):
 
3879
        """Automatic inference of user name.
 
3880
        
 
3881
        This is a bit hard to test in an isolated way, because it depends on
 
3882
        system functions that go direct to /etc or perhaps somewhere else.
 
3883
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
 
3884
        to be able to choose a user name with no configuration.
 
3885
        """
 
3886
        if sys.platform == 'win32':
 
3887
            raise tests.TestSkipped(
 
3888
                "User name inference not implemented on win32")
 
3889
        realname, address = config._auto_user_id()
 
3890
        if os.path.exists('/etc/mailname'):
 
3891
            self.assertIsNot(None, realname)
 
3892
            self.assertIsNot(None, address)
 
3893
        else:
 
3894
            self.assertEquals((None, None), (realname, address))
 
3895