/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: Jonathan Riddell
  • Date: 2011-09-07 11:46:16 UTC
  • mto: (6123.1.10 +trunk)
  • mto: This revision was merged to the branch mainline in revision 6124.
  • Revision ID: jriddell@canonical.com-20110907114616-korjsxz31zdhyuqi
pass in a name not a tuple

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