/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-05 17:31:43 UTC
  • mto: This revision was merged to the branch mainline in revision 6348.
  • Revision ID: jelmer@samba.org-20111205173143-jwj2xtdwpgpn4ic0
Fix test.

Show diffs side-by-side

added added

removed removed

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