~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Vincent Ladeuil
  • Date: 2008-09-11 19:36:38 UTC
  • mfrom: (3703 +trunk)
  • mto: (3705.1.1 trunk2)
  • mto: This revision was merged to the branch mainline in revision 3708.
  • Revision ID: v.ladeuil+lp@free.fr-20080911193638-wtjyc1kcmacc6t1f
merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
#   Authors: Robert Collins <robert.collins@canonical.com>
2
3
#
3
4
# This program is free software; you can redistribute it and/or modify
4
5
# it under the terms of the GNU General Public License as published by
12
13
#
13
14
# You should have received a copy of the GNU General Public License
14
15
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
 
17
18
"""Tests for finding and reading the bzr config file[s]."""
18
19
# import system imports here
19
20
from cStringIO import StringIO
20
21
import os
21
22
import sys
22
 
import threading
23
 
 
24
 
 
25
 
from testtools import matchers
26
23
 
27
24
#import bzrlib specific imports here
28
25
from bzrlib import (
29
26
    branch,
30
27
    bzrdir,
31
28
    config,
32
 
    diff,
33
29
    errors,
34
30
    osutils,
35
31
    mail_client,
36
 
    mergetools,
37
32
    ui,
38
33
    urlutils,
39
 
    registry,
40
 
    remote,
41
34
    tests,
42
35
    trace,
43
36
    transport,
44
37
    )
45
 
from bzrlib.symbol_versioning import (
46
 
    deprecated_in,
47
 
    deprecated_method,
48
 
    )
49
 
from bzrlib.transport import remote as transport_remote
50
 
from bzrlib.tests import (
51
 
    features,
52
 
    scenarios,
53
 
    test_server,
54
 
    )
55
38
from bzrlib.util.configobj import configobj
56
39
 
57
40
 
58
 
def lockable_config_scenarios():
59
 
    return [
60
 
        ('global',
61
 
         {'config_class': config.GlobalConfig,
62
 
          'config_args': [],
63
 
          'config_section': 'DEFAULT'}),
64
 
        ('locations',
65
 
         {'config_class': config.LocationConfig,
66
 
          'config_args': ['.'],
67
 
          'config_section': '.'}),]
68
 
 
69
 
 
70
 
load_tests = scenarios.load_tests_apply_scenarios
71
 
 
72
 
# Register helpers to build stores
73
 
config.test_store_builder_registry.register(
74
 
    'configobj', lambda test: config.IniFileStore(test.get_transport(),
75
 
                                                  'configobj.conf'))
76
 
config.test_store_builder_registry.register(
77
 
    'bazaar', lambda test: config.GlobalStore())
78
 
config.test_store_builder_registry.register(
79
 
    'location', lambda test: config.LocationStore())
80
 
 
81
 
 
82
 
def build_backing_branch(test, relpath,
83
 
                         transport_class=None, server_class=None):
84
 
    """Test helper to create a backing branch only once.
85
 
 
86
 
    Some tests needs multiple stores/stacks to check concurrent update
87
 
    behaviours. As such, they need to build different branch *objects* even if
88
 
    they share the branch on disk.
89
 
 
90
 
    :param relpath: The relative path to the branch. (Note that the helper
91
 
        should always specify the same relpath).
92
 
 
93
 
    :param transport_class: The Transport class the test needs to use.
94
 
 
95
 
    :param server_class: The server associated with the ``transport_class``
96
 
        above.
97
 
 
98
 
    Either both or neither of ``transport_class`` and ``server_class`` should
99
 
    be specified.
100
 
    """
101
 
    if transport_class is not None and server_class is not None:
102
 
        test.transport_class = transport_class
103
 
        test.transport_server = server_class
104
 
    elif not (transport_class is None and server_class is None):
105
 
        raise AssertionError('Specify both ``transport_class`` and '
106
 
                             '``server_class`` or neither of them')
107
 
    if getattr(test, 'backing_branch', None) is None:
108
 
        # First call, let's build the branch on disk
109
 
        test.backing_branch = test.make_branch(relpath)
110
 
 
111
 
 
112
 
def build_branch_store(test):
113
 
    build_backing_branch(test, 'branch')
114
 
    b = branch.Branch.open('branch')
115
 
    return config.BranchStore(b)
116
 
config.test_store_builder_registry.register('branch', build_branch_store)
117
 
 
118
 
 
119
 
def build_remote_branch_store(test):
120
 
    # There is only one permutation (but we won't be able to handle more with
121
 
    # this design anyway)
122
 
    (transport_class,
123
 
     server_class) = transport_remote.get_test_permutations()[0]
124
 
    build_backing_branch(test, 'branch', transport_class, server_class)
125
 
    b = branch.Branch.open(test.get_url('branch'))
126
 
    return config.BranchStore(b)
127
 
config.test_store_builder_registry.register('remote_branch',
128
 
                                            build_remote_branch_store)
129
 
 
130
 
 
131
 
config.test_stack_builder_registry.register(
132
 
    'bazaar', lambda test: config.GlobalStack())
133
 
config.test_stack_builder_registry.register(
134
 
    'location', lambda test: config.LocationStack('.'))
135
 
 
136
 
 
137
 
def build_branch_stack(test):
138
 
    build_backing_branch(test, 'branch')
139
 
    b = branch.Branch.open('branch')
140
 
    return config.BranchStack(b)
141
 
config.test_stack_builder_registry.register('branch', build_branch_stack)
142
 
 
143
 
 
144
 
def build_remote_branch_stack(test):
145
 
    # There is only one permutation (but we won't be able to handle more with
146
 
    # this design anyway)
147
 
    (transport_class,
148
 
     server_class) = transport_remote.get_test_permutations()[0]
149
 
    build_backing_branch(test, 'branch', transport_class, server_class)
150
 
    b = branch.Branch.open(test.get_url('branch'))
151
 
    return config.BranchStack(b)
152
 
config.test_stack_builder_registry.register('remote_branch',
153
 
                                            build_remote_branch_stack)
154
 
 
155
 
 
156
41
sample_long_alias="log -r-15..-1 --line"
157
42
sample_config_text = u"""
158
43
[DEFAULT]
159
44
email=Erik B\u00e5gfors <erik@bagfors.nu>
160
45
editor=vim
161
 
change_editor=vimdiff -of @new_path @old_path
162
46
gpg_signing_command=gnome-gpg
163
 
gpg_signing_key=DD4D5088
164
47
log_format=short
165
 
validate_signatures_in_log=true
166
 
acceptable_keys=amy
167
48
user_global_option=something
168
 
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
169
 
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
170
 
bzr.default_mergetool=sometool
171
49
[ALIASES]
172
50
h=help
173
51
ll=""" + sample_long_alias + "\n"
215
93
[/a/]
216
94
check_signatures=check-available
217
95
gpg_signing_command=false
218
 
gpg_signing_key=default
219
96
user_local_option=local
220
97
# test trailing / matching
221
98
[/a/*]
227
104
"""
228
105
 
229
106
 
230
 
def create_configs(test):
231
 
    """Create configuration files for a given test.
232
 
 
233
 
    This requires creating a tree (and populate the ``test.tree`` attribute)
234
 
    and its associated branch and will populate the following attributes:
235
 
 
236
 
    - branch_config: A BranchConfig for the associated branch.
237
 
 
238
 
    - locations_config : A LocationConfig for the associated branch
239
 
 
240
 
    - bazaar_config: A GlobalConfig.
241
 
 
242
 
    The tree and branch are created in a 'tree' subdirectory so the tests can
243
 
    still use the test directory to stay outside of the branch.
244
 
    """
245
 
    tree = test.make_branch_and_tree('tree')
246
 
    test.tree = tree
247
 
    test.branch_config = config.BranchConfig(tree.branch)
248
 
    test.locations_config = config.LocationConfig(tree.basedir)
249
 
    test.bazaar_config = config.GlobalConfig()
250
 
 
251
 
 
252
 
def create_configs_with_file_option(test):
253
 
    """Create configuration files with a ``file`` option set in each.
254
 
 
255
 
    This builds on ``create_configs`` and add one ``file`` option in each
256
 
    configuration with a value which allows identifying the configuration file.
257
 
    """
258
 
    create_configs(test)
259
 
    test.bazaar_config.set_user_option('file', 'bazaar')
260
 
    test.locations_config.set_user_option('file', 'locations')
261
 
    test.branch_config.set_user_option('file', 'branch')
262
 
 
263
 
 
264
 
class TestOptionsMixin:
265
 
 
266
 
    def assertOptions(self, expected, conf):
267
 
        # We don't care about the parser (as it will make tests hard to write
268
 
        # and error-prone anyway)
269
 
        self.assertThat([opt[:4] for opt in conf._get_options()],
270
 
                        matchers.Equals(expected))
271
 
 
272
 
 
273
107
class InstrumentedConfigObj(object):
274
108
    """A config obj look-enough-alike to record calls made to it."""
275
109
 
294
128
        self._calls.append(('keys',))
295
129
        return []
296
130
 
297
 
    def reload(self):
298
 
        self._calls.append(('reload',))
299
 
 
300
131
    def write(self, arg):
301
132
        self._calls.append(('write',))
302
133
 
319
150
        self._transport = self.control_files = \
320
151
            FakeControlFilesAndTransport(user_id=user_id)
321
152
 
322
 
    def _get_config(self):
323
 
        return config.TransportConfig(self._transport, 'branch.conf')
324
 
 
325
153
    def lock_write(self):
326
154
        pass
327
155
 
378
206
        self._calls.append('_get_signature_checking')
379
207
        return self._signatures
380
208
 
381
 
    def _get_change_editor(self):
382
 
        self._calls.append('_get_change_editor')
383
 
        return 'vimdiff -fo @new_path @old_path'
384
 
 
385
209
 
386
210
bool_config = """[DEFAULT]
387
211
active = true
408
232
        """
409
233
        co = config.ConfigObj()
410
234
        co['test'] = 'foo#bar'
411
 
        outfile = StringIO()
412
 
        co.write(outfile=outfile)
413
 
        lines = outfile.getvalue().splitlines()
 
235
        lines = co.write()
414
236
        self.assertEqual(lines, ['test = "foo#bar"'])
415
237
        co2 = config.ConfigObj(lines)
416
238
        self.assertEqual(co2['test'], 'foo#bar')
417
239
 
418
 
    def test_triple_quotes(self):
419
 
        # Bug #710410: if the value string has triple quotes
420
 
        # then ConfigObj versions up to 4.7.2 will quote them wrong
421
 
        # and won't able to read them back
422
 
        triple_quotes_value = '''spam
423
 
""" that's my spam """
424
 
eggs'''
425
 
        co = config.ConfigObj()
426
 
        co['test'] = triple_quotes_value
427
 
        # While writing this test another bug in ConfigObj has been found:
428
 
        # method co.write() without arguments produces list of lines
429
 
        # one option per line, and multiline values are not split
430
 
        # across multiple lines,
431
 
        # and that breaks the parsing these lines back by ConfigObj.
432
 
        # This issue only affects test, but it's better to avoid
433
 
        # `co.write()` construct at all.
434
 
        # [bialix 20110222] bug report sent to ConfigObj's author
435
 
        outfile = StringIO()
436
 
        co.write(outfile=outfile)
437
 
        output = outfile.getvalue()
438
 
        # now we're trying to read it back
439
 
        co2 = config.ConfigObj(StringIO(output))
440
 
        self.assertEquals(triple_quotes_value, co2['test'])
441
 
 
442
240
 
443
241
erroneous_config = """[section] # line 1
444
242
good=good # line 2
465
263
        config.Config()
466
264
 
467
265
    def test_no_default_editor(self):
468
 
        self.assertRaises(
469
 
            NotImplementedError,
470
 
            self.applyDeprecated, deprecated_in((2, 4, 0)),
471
 
            config.Config().get_editor)
 
266
        self.assertRaises(NotImplementedError, config.Config().get_editor)
472
267
 
473
268
    def test_user_email(self):
474
269
        my_config = InstrumentedConfig()
517
312
        my_config = config.Config()
518
313
        self.assertEqual('long', my_config.log_format())
519
314
 
520
 
    def test_acceptable_keys_default(self):
521
 
        my_config = config.Config()
522
 
        self.assertEqual(None, my_config.acceptable_keys())
523
 
 
524
 
    def test_validate_signatures_in_log_default(self):
525
 
        my_config = config.Config()
526
 
        self.assertEqual(False, my_config.validate_signatures_in_log())
527
 
 
528
 
    def test_get_change_editor(self):
529
 
        my_config = InstrumentedConfig()
530
 
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
531
 
        self.assertEqual(['_get_change_editor'], my_config._calls)
532
 
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
533
 
        self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
534
 
                         change_editor.command_template)
535
 
 
536
315
 
537
316
class TestConfigPath(tests.TestCase):
538
317
 
539
318
    def setUp(self):
540
319
        super(TestConfigPath, self).setUp()
541
 
        self.overrideEnv('HOME', '/home/bogus')
542
 
        self.overrideEnv('XDG_CACHE_DIR', '')
 
320
        os.environ['HOME'] = '/home/bogus'
543
321
        if sys.platform == 'win32':
544
 
            self.overrideEnv(
545
 
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
 
322
            os.environ['BZR_HOME'] = \
 
323
                r'C:\Documents and Settings\bogus\Application Data'
546
324
            self.bzr_home = \
547
325
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
548
326
        else:
555
333
        self.assertEqual(config.config_filename(),
556
334
                         self.bzr_home + '/bazaar.conf')
557
335
 
 
336
    def test_branches_config_filename(self):
 
337
        self.assertEqual(config.branches_config_filename(),
 
338
                         self.bzr_home + '/branches.conf')
 
339
 
558
340
    def test_locations_config_filename(self):
559
341
        self.assertEqual(config.locations_config_filename(),
560
342
                         self.bzr_home + '/locations.conf')
563
345
        self.assertEqual(config.authentication_config_filename(),
564
346
                         self.bzr_home + '/authentication.conf')
565
347
 
566
 
    def test_xdg_cache_dir(self):
567
 
        self.assertEqual(config.xdg_cache_dir(),
568
 
            '/home/bogus/.cache')
569
 
 
570
 
 
571
 
class TestXDGConfigDir(tests.TestCaseInTempDir):
572
 
    # must be in temp dir because config tests for the existence of the bazaar
573
 
    # subdirectory of $XDG_CONFIG_HOME
574
 
 
575
 
    def setUp(self):
576
 
        if sys.platform in ('darwin', 'win32'):
577
 
            raise tests.TestNotApplicable(
578
 
                'XDG config dir not used on this platform')
579
 
        super(TestXDGConfigDir, self).setUp()
580
 
        self.overrideEnv('HOME', self.test_home_dir)
581
 
        # BZR_HOME overrides everything we want to test so unset it.
582
 
        self.overrideEnv('BZR_HOME', None)
583
 
 
584
 
    def test_xdg_config_dir_exists(self):
585
 
        """When ~/.config/bazaar exists, use it as the config dir."""
586
 
        newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
587
 
        os.makedirs(newdir)
588
 
        self.assertEqual(config.config_dir(), newdir)
589
 
 
590
 
    def test_xdg_config_home(self):
591
 
        """When XDG_CONFIG_HOME is set, use it."""
592
 
        xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
593
 
        self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
594
 
        newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
595
 
        os.makedirs(newdir)
596
 
        self.assertEqual(config.config_dir(), newdir)
597
 
 
598
 
 
599
 
class TestIniConfig(tests.TestCaseInTempDir):
600
 
 
601
 
    def make_config_parser(self, s):
602
 
        conf = config.IniBasedConfig.from_string(s)
603
 
        return conf, conf._get_parser()
604
 
 
605
 
 
606
 
class TestIniConfigBuilding(TestIniConfig):
 
348
 
 
349
class TestIniConfig(tests.TestCase):
607
350
 
608
351
    def test_contructs(self):
609
 
        my_config = config.IniBasedConfig()
 
352
        my_config = config.IniBasedConfig("nothing")
610
353
 
611
354
    def test_from_fp(self):
612
 
        my_config = config.IniBasedConfig.from_string(sample_config_text)
613
 
        self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
 
355
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
356
        my_config = config.IniBasedConfig(None)
 
357
        self.failUnless(
 
358
            isinstance(my_config._get_parser(file=config_file),
 
359
                        configobj.ConfigObj))
614
360
 
615
361
    def test_cached(self):
616
 
        my_config = config.IniBasedConfig.from_string(sample_config_text)
617
 
        parser = my_config._get_parser()
618
 
        self.assertTrue(my_config._get_parser() is parser)
619
 
 
620
 
    def _dummy_chown(self, path, uid, gid):
621
 
        self.path, self.uid, self.gid = path, uid, gid
622
 
 
623
 
    def test_ini_config_ownership(self):
624
 
        """Ensure that chown is happening during _write_config_file"""
625
 
        self.requireFeature(features.chown_feature)
626
 
        self.overrideAttr(os, 'chown', self._dummy_chown)
627
 
        self.path = self.uid = self.gid = None
628
 
        conf = config.IniBasedConfig(file_name='./foo.conf')
629
 
        conf._write_config_file()
630
 
        self.assertEquals(self.path, './foo.conf')
631
 
        self.assertTrue(isinstance(self.uid, int))
632
 
        self.assertTrue(isinstance(self.gid, int))
633
 
 
634
 
    def test_get_filename_parameter_is_deprecated_(self):
635
 
        conf = self.callDeprecated([
636
 
            'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
637
 
            ' Use file_name instead.'],
638
 
            config.IniBasedConfig, lambda: 'ini.conf')
639
 
        self.assertEqual('ini.conf', conf.file_name)
640
 
 
641
 
    def test_get_parser_file_parameter_is_deprecated_(self):
642
362
        config_file = StringIO(sample_config_text.encode('utf-8'))
643
 
        conf = config.IniBasedConfig.from_string(sample_config_text)
644
 
        conf = self.callDeprecated([
645
 
            'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
646
 
            ' Use IniBasedConfig(_content=xxx) instead.'],
647
 
            conf._get_parser, file=config_file)
648
 
 
649
 
 
650
 
class TestIniConfigSaving(tests.TestCaseInTempDir):
651
 
 
652
 
    def test_cant_save_without_a_file_name(self):
653
 
        conf = config.IniBasedConfig()
654
 
        self.assertRaises(AssertionError, conf._write_config_file)
655
 
 
656
 
    def test_saved_with_content(self):
657
 
        content = 'foo = bar\n'
658
 
        conf = config.IniBasedConfig.from_string(
659
 
            content, file_name='./test.conf', save=True)
660
 
        self.assertFileEqual(content, 'test.conf')
661
 
 
662
 
 
663
 
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
664
 
    """What is the default value of expand for config options.
665
 
 
666
 
    This is an opt-in beta feature used to evaluate whether or not option
667
 
    references can appear in dangerous place raising exceptions, disapearing
668
 
    (and as such corrupting data) or if it's safe to activate the option by
669
 
    default.
670
 
 
671
 
    Note that these tests relies on config._expand_default_value being already
672
 
    overwritten in the parent class setUp.
673
 
    """
674
 
 
675
 
    def setUp(self):
676
 
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
677
 
        self.config = None
678
 
        self.warnings = []
679
 
        def warning(*args):
680
 
            self.warnings.append(args[0] % args[1:])
681
 
        self.overrideAttr(trace, 'warning', warning)
682
 
 
683
 
    def get_config(self, expand):
684
 
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
685
 
                                            save=True)
686
 
        return c
687
 
 
688
 
    def assertExpandIs(self, expected):
689
 
        actual = config._get_expand_default_value()
690
 
        #self.config.get_user_option_as_bool('bzr.config.expand')
691
 
        self.assertEquals(expected, actual)
692
 
 
693
 
    def test_default_is_None(self):
694
 
        self.assertEquals(None, config._expand_default_value)
695
 
 
696
 
    def test_default_is_False_even_if_None(self):
697
 
        self.config = self.get_config(None)
698
 
        self.assertExpandIs(False)
699
 
 
700
 
    def test_default_is_False_even_if_invalid(self):
701
 
        self.config = self.get_config('<your choice>')
702
 
        self.assertExpandIs(False)
703
 
        # ...
704
 
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
705
 
        # Wait, you've been warned !
706
 
        self.assertLength(1, self.warnings)
707
 
        self.assertEquals(
708
 
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
709
 
            self.warnings[0])
710
 
 
711
 
    def test_default_is_True(self):
712
 
        self.config = self.get_config(True)
713
 
        self.assertExpandIs(True)
714
 
 
715
 
    def test_default_is_False(self):
716
 
        self.config = self.get_config(False)
717
 
        self.assertExpandIs(False)
718
 
 
719
 
 
720
 
class TestIniConfigOptionExpansion(tests.TestCase):
721
 
    """Test option expansion from the IniConfig level.
722
 
 
723
 
    What we really want here is to test the Config level, but the class being
724
 
    abstract as far as storing values is concerned, this can't be done
725
 
    properly (yet).
726
 
    """
727
 
    # FIXME: This should be rewritten when all configs share a storage
728
 
    # implementation -- vila 2011-02-18
729
 
 
730
 
    def get_config(self, string=None):
731
 
        if string is None:
732
 
            string = ''
733
 
        c = config.IniBasedConfig.from_string(string)
734
 
        return c
735
 
 
736
 
    def assertExpansion(self, expected, conf, string, env=None):
737
 
        self.assertEquals(expected, conf.expand_options(string, env))
738
 
 
739
 
    def test_no_expansion(self):
740
 
        c = self.get_config('')
741
 
        self.assertExpansion('foo', c, 'foo')
742
 
 
743
 
    def test_env_adding_options(self):
744
 
        c = self.get_config('')
745
 
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
746
 
 
747
 
    def test_env_overriding_options(self):
748
 
        c = self.get_config('foo=baz')
749
 
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
750
 
 
751
 
    def test_simple_ref(self):
752
 
        c = self.get_config('foo=xxx')
753
 
        self.assertExpansion('xxx', c, '{foo}')
754
 
 
755
 
    def test_unknown_ref(self):
756
 
        c = self.get_config('')
757
 
        self.assertRaises(errors.ExpandingUnknownOption,
758
 
                          c.expand_options, '{foo}')
759
 
 
760
 
    def test_indirect_ref(self):
761
 
        c = self.get_config('''
762
 
foo=xxx
763
 
bar={foo}
764
 
''')
765
 
        self.assertExpansion('xxx', c, '{bar}')
766
 
 
767
 
    def test_embedded_ref(self):
768
 
        c = self.get_config('''
769
 
foo=xxx
770
 
bar=foo
771
 
''')
772
 
        self.assertExpansion('xxx', c, '{{bar}}')
773
 
 
774
 
    def test_simple_loop(self):
775
 
        c = self.get_config('foo={foo}')
776
 
        self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
777
 
 
778
 
    def test_indirect_loop(self):
779
 
        c = self.get_config('''
780
 
foo={bar}
781
 
bar={baz}
782
 
baz={foo}''')
783
 
        e = self.assertRaises(errors.OptionExpansionLoop,
784
 
                              c.expand_options, '{foo}')
785
 
        self.assertEquals('foo->bar->baz', e.refs)
786
 
        self.assertEquals('{foo}', e.string)
787
 
 
788
 
    def test_list(self):
789
 
        conf = self.get_config('''
790
 
foo=start
791
 
bar=middle
792
 
baz=end
793
 
list={foo},{bar},{baz}
794
 
''')
795
 
        self.assertEquals(['start', 'middle', 'end'],
796
 
                           conf.get_user_option('list', expand=True))
797
 
 
798
 
    def test_cascading_list(self):
799
 
        conf = self.get_config('''
800
 
foo=start,{bar}
801
 
bar=middle,{baz}
802
 
baz=end
803
 
list={foo}
804
 
''')
805
 
        self.assertEquals(['start', 'middle', 'end'],
806
 
                           conf.get_user_option('list', expand=True))
807
 
 
808
 
    def test_pathological_hidden_list(self):
809
 
        conf = self.get_config('''
810
 
foo=bin
811
 
bar=go
812
 
start={foo
813
 
middle=},{
814
 
end=bar}
815
 
hidden={start}{middle}{end}
816
 
''')
817
 
        # Nope, it's either a string or a list, and the list wins as soon as a
818
 
        # ',' appears, so the string concatenation never occur.
819
 
        self.assertEquals(['{foo', '}', '{', 'bar}'],
820
 
                          conf.get_user_option('hidden', expand=True))
821
 
 
822
 
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
823
 
 
824
 
    def get_config(self, location, string=None):
825
 
        if string is None:
826
 
            string = ''
827
 
        # Since we don't save the config we won't strictly require to inherit
828
 
        # from TestCaseInTempDir, but an error occurs so quickly...
829
 
        c = config.LocationConfig.from_string(string, location)
830
 
        return c
831
 
 
832
 
    def test_dont_cross_unrelated_section(self):
833
 
        c = self.get_config('/another/branch/path','''
834
 
[/one/branch/path]
835
 
foo = hello
836
 
bar = {foo}/2
837
 
 
838
 
[/another/branch/path]
839
 
bar = {foo}/2
840
 
''')
841
 
        self.assertRaises(errors.ExpandingUnknownOption,
842
 
                          c.get_user_option, 'bar', expand=True)
843
 
 
844
 
    def test_cross_related_sections(self):
845
 
        c = self.get_config('/project/branch/path','''
846
 
[/project]
847
 
foo = qu
848
 
 
849
 
[/project/branch/path]
850
 
bar = {foo}ux
851
 
''')
852
 
        self.assertEquals('quux', c.get_user_option('bar', expand=True))
853
 
 
854
 
 
855
 
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
856
 
 
857
 
    def test_cannot_reload_without_name(self):
858
 
        conf = config.IniBasedConfig.from_string(sample_config_text)
859
 
        self.assertRaises(AssertionError, conf.reload)
860
 
 
861
 
    def test_reload_see_new_value(self):
862
 
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
863
 
                                               file_name='./test/conf')
864
 
        c1._write_config_file()
865
 
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
866
 
                                               file_name='./test/conf')
867
 
        c2._write_config_file()
868
 
        self.assertEqual('vim', c1.get_user_option('editor'))
869
 
        self.assertEqual('emacs', c2.get_user_option('editor'))
870
 
        # Make sure we get the Right value
871
 
        c1.reload()
872
 
        self.assertEqual('emacs', c1.get_user_option('editor'))
873
 
 
874
 
 
875
 
class TestLockableConfig(tests.TestCaseInTempDir):
876
 
 
877
 
    scenarios = lockable_config_scenarios()
878
 
 
879
 
    # Set by load_tests
880
 
    config_class = None
881
 
    config_args = None
882
 
    config_section = None
883
 
 
884
 
    def setUp(self):
885
 
        super(TestLockableConfig, self).setUp()
886
 
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
887
 
        self.config = self.create_config(self._content)
888
 
 
889
 
    def get_existing_config(self):
890
 
        return self.config_class(*self.config_args)
891
 
 
892
 
    def create_config(self, content):
893
 
        kwargs = dict(save=True)
894
 
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
895
 
        return c
896
 
 
897
 
    def test_simple_read_access(self):
898
 
        self.assertEquals('1', self.config.get_user_option('one'))
899
 
 
900
 
    def test_simple_write_access(self):
901
 
        self.config.set_user_option('one', 'one')
902
 
        self.assertEquals('one', self.config.get_user_option('one'))
903
 
 
904
 
    def test_listen_to_the_last_speaker(self):
905
 
        c1 = self.config
906
 
        c2 = self.get_existing_config()
907
 
        c1.set_user_option('one', 'ONE')
908
 
        c2.set_user_option('two', 'TWO')
909
 
        self.assertEquals('ONE', c1.get_user_option('one'))
910
 
        self.assertEquals('TWO', c2.get_user_option('two'))
911
 
        # The second update respect the first one
912
 
        self.assertEquals('ONE', c2.get_user_option('one'))
913
 
 
914
 
    def test_last_speaker_wins(self):
915
 
        # If the same config is not shared, the same variable modified twice
916
 
        # can only see a single result.
917
 
        c1 = self.config
918
 
        c2 = self.get_existing_config()
919
 
        c1.set_user_option('one', 'c1')
920
 
        c2.set_user_option('one', 'c2')
921
 
        self.assertEquals('c2', c2._get_user_option('one'))
922
 
        # The first modification is still available until another refresh
923
 
        # occur
924
 
        self.assertEquals('c1', c1._get_user_option('one'))
925
 
        c1.set_user_option('two', 'done')
926
 
        self.assertEquals('c2', c1._get_user_option('one'))
927
 
 
928
 
    def test_writes_are_serialized(self):
929
 
        c1 = self.config
930
 
        c2 = self.get_existing_config()
931
 
 
932
 
        # We spawn a thread that will pause *during* the write
933
 
        before_writing = threading.Event()
934
 
        after_writing = threading.Event()
935
 
        writing_done = threading.Event()
936
 
        c1_orig = c1._write_config_file
937
 
        def c1_write_config_file():
938
 
            before_writing.set()
939
 
            c1_orig()
940
 
            # The lock is held. We wait for the main thread to decide when to
941
 
            # continue
942
 
            after_writing.wait()
943
 
        c1._write_config_file = c1_write_config_file
944
 
        def c1_set_option():
945
 
            c1.set_user_option('one', 'c1')
946
 
            writing_done.set()
947
 
        t1 = threading.Thread(target=c1_set_option)
948
 
        # Collect the thread after the test
949
 
        self.addCleanup(t1.join)
950
 
        # Be ready to unblock the thread if the test goes wrong
951
 
        self.addCleanup(after_writing.set)
952
 
        t1.start()
953
 
        before_writing.wait()
954
 
        self.assertTrue(c1._lock.is_held)
955
 
        self.assertRaises(errors.LockContention,
956
 
                          c2.set_user_option, 'one', 'c2')
957
 
        self.assertEquals('c1', c1.get_user_option('one'))
958
 
        # Let the lock be released
959
 
        after_writing.set()
960
 
        writing_done.wait()
961
 
        c2.set_user_option('one', 'c2')
962
 
        self.assertEquals('c2', c2.get_user_option('one'))
963
 
 
964
 
    def test_read_while_writing(self):
965
 
       c1 = self.config
966
 
       # We spawn a thread that will pause *during* the write
967
 
       ready_to_write = threading.Event()
968
 
       do_writing = threading.Event()
969
 
       writing_done = threading.Event()
970
 
       c1_orig = c1._write_config_file
971
 
       def c1_write_config_file():
972
 
           ready_to_write.set()
973
 
           # The lock is held. We wait for the main thread to decide when to
974
 
           # continue
975
 
           do_writing.wait()
976
 
           c1_orig()
977
 
           writing_done.set()
978
 
       c1._write_config_file = c1_write_config_file
979
 
       def c1_set_option():
980
 
           c1.set_user_option('one', 'c1')
981
 
       t1 = threading.Thread(target=c1_set_option)
982
 
       # Collect the thread after the test
983
 
       self.addCleanup(t1.join)
984
 
       # Be ready to unblock the thread if the test goes wrong
985
 
       self.addCleanup(do_writing.set)
986
 
       t1.start()
987
 
       # Ensure the thread is ready to write
988
 
       ready_to_write.wait()
989
 
       self.assertTrue(c1._lock.is_held)
990
 
       self.assertEquals('c1', c1.get_user_option('one'))
991
 
       # If we read during the write, we get the old value
992
 
       c2 = self.get_existing_config()
993
 
       self.assertEquals('1', c2.get_user_option('one'))
994
 
       # Let the writing occur and ensure it occurred
995
 
       do_writing.set()
996
 
       writing_done.wait()
997
 
       # Now we get the updated value
998
 
       c3 = self.get_existing_config()
999
 
       self.assertEquals('c1', c3.get_user_option('one'))
1000
 
 
1001
 
 
1002
 
class TestGetUserOptionAs(TestIniConfig):
1003
 
 
1004
 
    def test_get_user_option_as_bool(self):
1005
 
        conf, parser = self.make_config_parser("""
1006
 
a_true_bool = true
1007
 
a_false_bool = 0
1008
 
an_invalid_bool = maybe
1009
 
a_list = hmm, who knows ? # This is interpreted as a list !
1010
 
""")
1011
 
        get_bool = conf.get_user_option_as_bool
1012
 
        self.assertEqual(True, get_bool('a_true_bool'))
1013
 
        self.assertEqual(False, get_bool('a_false_bool'))
1014
 
        warnings = []
1015
 
        def warning(*args):
1016
 
            warnings.append(args[0] % args[1:])
1017
 
        self.overrideAttr(trace, 'warning', warning)
1018
 
        msg = 'Value "%s" is not a boolean for "%s"'
1019
 
        self.assertIs(None, get_bool('an_invalid_bool'))
1020
 
        self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
1021
 
        warnings = []
1022
 
        self.assertIs(None, get_bool('not_defined_in_this_config'))
1023
 
        self.assertEquals([], warnings)
1024
 
 
1025
 
    def test_get_user_option_as_list(self):
1026
 
        conf, parser = self.make_config_parser("""
1027
 
a_list = a,b,c
1028
 
length_1 = 1,
1029
 
one_item = x
1030
 
""")
1031
 
        get_list = conf.get_user_option_as_list
1032
 
        self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
1033
 
        self.assertEqual(['1'], get_list('length_1'))
1034
 
        self.assertEqual('x', conf.get_user_option('one_item'))
1035
 
        # automatically cast to list
1036
 
        self.assertEqual(['x'], get_list('one_item'))
1037
 
 
1038
 
 
1039
 
class TestSupressWarning(TestIniConfig):
1040
 
 
1041
 
    def make_warnings_config(self, s):
1042
 
        conf, parser = self.make_config_parser(s)
1043
 
        return conf.suppress_warning
1044
 
 
1045
 
    def test_suppress_warning_unknown(self):
1046
 
        suppress_warning = self.make_warnings_config('')
1047
 
        self.assertEqual(False, suppress_warning('unknown_warning'))
1048
 
 
1049
 
    def test_suppress_warning_known(self):
1050
 
        suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
1051
 
        self.assertEqual(False, suppress_warning('c'))
1052
 
        self.assertEqual(True, suppress_warning('a'))
1053
 
        self.assertEqual(True, suppress_warning('b'))
 
363
        my_config = config.IniBasedConfig(None)
 
364
        parser = my_config._get_parser(file=config_file)
 
365
        self.failUnless(my_config._get_parser() is parser)
1054
366
 
1055
367
 
1056
368
class TestGetConfig(tests.TestCase):
1067
379
            parser = my_config._get_parser()
1068
380
        finally:
1069
381
            config.ConfigObj = oldparserclass
1070
 
        self.assertIsInstance(parser, InstrumentedConfigObj)
 
382
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1071
383
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
1072
384
                                          'utf-8')])
1073
385
 
1084
396
        my_config = config.BranchConfig(branch)
1085
397
        location_config = my_config._get_location_config()
1086
398
        self.assertEqual(branch.base, location_config.location)
1087
 
        self.assertIs(location_config, my_config._get_location_config())
 
399
        self.failUnless(location_config is my_config._get_location_config())
1088
400
 
1089
401
    def test_get_config(self):
1090
402
        """The Branch.get_config method works properly"""
1110
422
        branch = self.make_branch('branch')
1111
423
        self.assertEqual('branch', branch.nick)
1112
424
 
 
425
        locations = config.locations_config_filename()
 
426
        config.ensure_config_dir_exists()
1113
427
        local_url = urlutils.local_path_to_url('branch')
1114
 
        conf = config.LocationConfig.from_string(
1115
 
            '[%s]\nnickname = foobar' % (local_url,),
1116
 
            local_url, save=True)
 
428
        open(locations, 'wb').write('[%s]\nnickname = foobar' 
 
429
                                    % (local_url,))
1117
430
        self.assertEqual('foobar', branch.nick)
1118
431
 
1119
432
    def test_config_local_path(self):
1121
434
        branch = self.make_branch('branch')
1122
435
        self.assertEqual('branch', branch.nick)
1123
436
 
1124
 
        local_path = osutils.getcwd().encode('utf8')
1125
 
        conf = config.LocationConfig.from_string(
1126
 
            '[%s/branch]\nnickname = barry' % (local_path,),
1127
 
            'branch',  save=True)
 
437
        locations = config.locations_config_filename()
 
438
        config.ensure_config_dir_exists()
 
439
        open(locations, 'wb').write('[%s/branch]\nnickname = barry' 
 
440
                                    % (osutils.getcwd().encode('utf8'),))
1128
441
        self.assertEqual('barry', branch.nick)
1129
442
 
1130
443
    def test_config_creates_local(self):
1131
444
        """Creating a new entry in config uses a local path."""
1132
445
        branch = self.make_branch('branch', format='knit')
1133
446
        branch.set_push_location('http://foobar')
 
447
        locations = config.locations_config_filename()
1134
448
        local_path = osutils.getcwd().encode('utf8')
1135
449
        # Surprisingly ConfigObj doesn't create a trailing newline
1136
 
        self.check_file_contents(config.locations_config_filename(),
 
450
        self.check_file_contents(locations,
1137
451
                                 '[%s/branch]\n'
1138
452
                                 'push_location = http://foobar\n'
1139
453
                                 'push_location:policy = norecurse\n'
1144
458
        self.assertEqual('!repo', b.get_config().get_nickname())
1145
459
 
1146
460
    def test_warn_if_masked(self):
 
461
        _warning = trace.warning
1147
462
        warnings = []
1148
463
        def warning(*args):
1149
464
            warnings.append(args[0] % args[1:])
1150
 
        self.overrideAttr(trace, 'warning', warning)
1151
465
 
1152
466
        def set_option(store, warn_masked=True):
1153
467
            warnings[:] = []
1159
473
            else:
1160
474
                self.assertEqual(1, len(warnings))
1161
475
                self.assertEqual(warning, warnings[0])
1162
 
        branch = self.make_branch('.')
1163
 
        conf = branch.get_config()
1164
 
        set_option(config.STORE_GLOBAL)
1165
 
        assertWarning(None)
1166
 
        set_option(config.STORE_BRANCH)
1167
 
        assertWarning(None)
1168
 
        set_option(config.STORE_GLOBAL)
1169
 
        assertWarning('Value "4" is masked by "3" from branch.conf')
1170
 
        set_option(config.STORE_GLOBAL, warn_masked=False)
1171
 
        assertWarning(None)
1172
 
        set_option(config.STORE_LOCATION)
1173
 
        assertWarning(None)
1174
 
        set_option(config.STORE_BRANCH)
1175
 
        assertWarning('Value "3" is masked by "0" from locations.conf')
1176
 
        set_option(config.STORE_BRANCH, warn_masked=False)
1177
 
        assertWarning(None)
1178
 
 
1179
 
 
1180
 
class TestGlobalConfigItems(tests.TestCaseInTempDir):
 
476
        trace.warning = warning
 
477
        try:
 
478
            branch = self.make_branch('.')
 
479
            conf = branch.get_config()
 
480
            set_option(config.STORE_GLOBAL)
 
481
            assertWarning(None)
 
482
            set_option(config.STORE_BRANCH)
 
483
            assertWarning(None)
 
484
            set_option(config.STORE_GLOBAL)
 
485
            assertWarning('Value "4" is masked by "3" from branch.conf')
 
486
            set_option(config.STORE_GLOBAL, warn_masked=False)
 
487
            assertWarning(None)
 
488
            set_option(config.STORE_LOCATION)
 
489
            assertWarning(None)
 
490
            set_option(config.STORE_BRANCH)
 
491
            assertWarning('Value "3" is masked by "0" from locations.conf')
 
492
            set_option(config.STORE_BRANCH, warn_masked=False)
 
493
            assertWarning(None)
 
494
        finally:
 
495
            trace.warning = _warning
 
496
 
 
497
 
 
498
class TestGlobalConfigItems(tests.TestCase):
1181
499
 
1182
500
    def test_user_id(self):
1183
 
        my_config = config.GlobalConfig.from_string(sample_config_text)
 
501
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
502
        my_config = config.GlobalConfig()
 
503
        my_config._parser = my_config._get_parser(file=config_file)
1184
504
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1185
505
                         my_config._get_user_id())
1186
506
 
1187
507
    def test_absent_user_id(self):
 
508
        config_file = StringIO("")
1188
509
        my_config = config.GlobalConfig()
 
510
        my_config._parser = my_config._get_parser(file=config_file)
1189
511
        self.assertEqual(None, my_config._get_user_id())
1190
512
 
1191
513
    def test_configured_editor(self):
1192
 
        my_config = config.GlobalConfig.from_string(sample_config_text)
1193
 
        editor = self.applyDeprecated(
1194
 
            deprecated_in((2, 4, 0)), my_config.get_editor)
1195
 
        self.assertEqual('vim', editor)
 
514
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
515
        my_config = config.GlobalConfig()
 
516
        my_config._parser = my_config._get_parser(file=config_file)
 
517
        self.assertEqual("vim", my_config.get_editor())
1196
518
 
1197
519
    def test_signatures_always(self):
1198
 
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
 
520
        config_file = StringIO(sample_always_signatures)
 
521
        my_config = config.GlobalConfig()
 
522
        my_config._parser = my_config._get_parser(file=config_file)
1199
523
        self.assertEqual(config.CHECK_NEVER,
1200
524
                         my_config.signature_checking())
1201
525
        self.assertEqual(config.SIGN_ALWAYS,
1203
527
        self.assertEqual(True, my_config.signature_needed())
1204
528
 
1205
529
    def test_signatures_if_possible(self):
1206
 
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
 
530
        config_file = StringIO(sample_maybe_signatures)
 
531
        my_config = config.GlobalConfig()
 
532
        my_config._parser = my_config._get_parser(file=config_file)
1207
533
        self.assertEqual(config.CHECK_NEVER,
1208
534
                         my_config.signature_checking())
1209
535
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
1211
537
        self.assertEqual(False, my_config.signature_needed())
1212
538
 
1213
539
    def test_signatures_ignore(self):
1214
 
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
 
540
        config_file = StringIO(sample_ignore_signatures)
 
541
        my_config = config.GlobalConfig()
 
542
        my_config._parser = my_config._get_parser(file=config_file)
1215
543
        self.assertEqual(config.CHECK_ALWAYS,
1216
544
                         my_config.signature_checking())
1217
545
        self.assertEqual(config.SIGN_NEVER,
1219
547
        self.assertEqual(False, my_config.signature_needed())
1220
548
 
1221
549
    def _get_sample_config(self):
1222
 
        my_config = config.GlobalConfig.from_string(sample_config_text)
 
550
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
551
        my_config = config.GlobalConfig()
 
552
        my_config._parser = my_config._get_parser(file=config_file)
1223
553
        return my_config
1224
554
 
1225
555
    def test_gpg_signing_command(self):
1227
557
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
1228
558
        self.assertEqual(False, my_config.signature_needed())
1229
559
 
1230
 
    def test_gpg_signing_key(self):
1231
 
        my_config = self._get_sample_config()
1232
 
        self.assertEqual("DD4D5088", my_config.gpg_signing_key())
1233
 
 
1234
560
    def _get_empty_config(self):
 
561
        config_file = StringIO("")
1235
562
        my_config = config.GlobalConfig()
 
563
        my_config._parser = my_config._get_parser(file=config_file)
1236
564
        return my_config
1237
565
 
1238
566
    def test_gpg_signing_command_unset(self):
1256
584
        my_config = self._get_sample_config()
1257
585
        self.assertEqual("short", my_config.log_format())
1258
586
 
1259
 
    def test_configured_acceptable_keys(self):
1260
 
        my_config = self._get_sample_config()
1261
 
        self.assertEqual("amy", my_config.acceptable_keys())
1262
 
 
1263
 
    def test_configured_validate_signatures_in_log(self):
1264
 
        my_config = self._get_sample_config()
1265
 
        self.assertEqual(True, my_config.validate_signatures_in_log())
1266
 
 
1267
587
    def test_get_alias(self):
1268
588
        my_config = self._get_sample_config()
1269
589
        self.assertEqual('help', my_config.get_alias('h'))
1284
604
        my_config = self._get_sample_config()
1285
605
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
1286
606
 
1287
 
    def test_get_change_editor(self):
1288
 
        my_config = self._get_sample_config()
1289
 
        change_editor = my_config.get_change_editor('old', 'new')
1290
 
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
1291
 
        self.assertEqual('vimdiff -of @new_path @old_path',
1292
 
                         ' '.join(change_editor.command_template))
1293
 
 
1294
 
    def test_get_no_change_editor(self):
1295
 
        my_config = self._get_empty_config()
1296
 
        change_editor = my_config.get_change_editor('old', 'new')
1297
 
        self.assertIs(None, change_editor)
1298
 
 
1299
 
    def test_get_merge_tools(self):
1300
 
        conf = self._get_sample_config()
1301
 
        tools = conf.get_merge_tools()
1302
 
        self.log(repr(tools))
1303
 
        self.assertEqual(
1304
 
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
1305
 
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
1306
 
            tools)
1307
 
 
1308
 
    def test_get_merge_tools_empty(self):
1309
 
        conf = self._get_empty_config()
1310
 
        tools = conf.get_merge_tools()
1311
 
        self.assertEqual({}, tools)
1312
 
 
1313
 
    def test_find_merge_tool(self):
1314
 
        conf = self._get_sample_config()
1315
 
        cmdline = conf.find_merge_tool('sometool')
1316
 
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
1317
 
 
1318
 
    def test_find_merge_tool_not_found(self):
1319
 
        conf = self._get_sample_config()
1320
 
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
1321
 
        self.assertIs(cmdline, None)
1322
 
 
1323
 
    def test_find_merge_tool_known(self):
1324
 
        conf = self._get_empty_config()
1325
 
        cmdline = conf.find_merge_tool('kdiff3')
1326
 
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
1327
 
 
1328
 
    def test_find_merge_tool_override_known(self):
1329
 
        conf = self._get_empty_config()
1330
 
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
1331
 
        cmdline = conf.find_merge_tool('kdiff3')
1332
 
        self.assertEqual('kdiff3 blah', cmdline)
1333
 
 
1334
607
 
1335
608
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
1336
609
 
1354
627
        self.assertIs(None, new_config.get_alias('commit'))
1355
628
 
1356
629
 
1357
 
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
 
630
class TestLocationConfig(tests.TestCaseInTempDir):
1358
631
 
1359
632
    def test_constructs(self):
1360
633
        my_config = config.LocationConfig('http://example.com')
1372
645
            parser = my_config._get_parser()
1373
646
        finally:
1374
647
            config.ConfigObj = oldparserclass
1375
 
        self.assertIsInstance(parser, InstrumentedConfigObj)
 
648
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1376
649
        self.assertEqual(parser._calls,
1377
650
                         [('__init__', config.locations_config_filename(),
1378
651
                           'utf-8')])
 
652
        config.ensure_config_dir_exists()
 
653
        #os.mkdir(config.config_dir())
 
654
        f = file(config.branches_config_filename(), 'wb')
 
655
        f.write('')
 
656
        f.close()
 
657
        oldparserclass = config.ConfigObj
 
658
        config.ConfigObj = InstrumentedConfigObj
 
659
        try:
 
660
            my_config = config.LocationConfig('http://www.example.com')
 
661
            parser = my_config._get_parser()
 
662
        finally:
 
663
            config.ConfigObj = oldparserclass
1379
664
 
1380
665
    def test_get_global_config(self):
1381
666
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
1382
667
        global_config = my_config._get_global_config()
1383
 
        self.assertIsInstance(global_config, config.GlobalConfig)
1384
 
        self.assertIs(global_config, my_config._get_global_config())
1385
 
 
1386
 
    def assertLocationMatching(self, expected):
1387
 
        self.assertEqual(expected,
1388
 
                         list(self.my_location_config._get_matching_sections()))
 
668
        self.failUnless(isinstance(global_config, config.GlobalConfig))
 
669
        self.failUnless(global_config is my_config._get_global_config())
1389
670
 
1390
671
    def test__get_matching_sections_no_match(self):
1391
672
        self.get_branch_config('/')
1392
 
        self.assertLocationMatching([])
 
673
        self.assertEqual([], self.my_location_config._get_matching_sections())
1393
674
 
1394
675
    def test__get_matching_sections_exact(self):
1395
676
        self.get_branch_config('http://www.example.com')
1396
 
        self.assertLocationMatching([('http://www.example.com', '')])
 
677
        self.assertEqual([('http://www.example.com', '')],
 
678
                         self.my_location_config._get_matching_sections())
1397
679
 
1398
680
    def test__get_matching_sections_suffix_does_not(self):
1399
681
        self.get_branch_config('http://www.example.com-com')
1400
 
        self.assertLocationMatching([])
 
682
        self.assertEqual([], self.my_location_config._get_matching_sections())
1401
683
 
1402
684
    def test__get_matching_sections_subdir_recursive(self):
1403
685
        self.get_branch_config('http://www.example.com/com')
1404
 
        self.assertLocationMatching([('http://www.example.com', 'com')])
 
686
        self.assertEqual([('http://www.example.com', 'com')],
 
687
                         self.my_location_config._get_matching_sections())
1405
688
 
1406
689
    def test__get_matching_sections_ignoreparent(self):
1407
690
        self.get_branch_config('http://www.example.com/ignoreparent')
1408
 
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1409
 
                                      '')])
 
691
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
 
692
                         self.my_location_config._get_matching_sections())
1410
693
 
1411
694
    def test__get_matching_sections_ignoreparent_subdir(self):
1412
695
        self.get_branch_config(
1413
696
            'http://www.example.com/ignoreparent/childbranch')
1414
 
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1415
 
                                      'childbranch')])
 
697
        self.assertEqual([('http://www.example.com/ignoreparent',
 
698
                           'childbranch')],
 
699
                         self.my_location_config._get_matching_sections())
1416
700
 
1417
701
    def test__get_matching_sections_subdir_trailing_slash(self):
1418
702
        self.get_branch_config('/b')
1419
 
        self.assertLocationMatching([('/b/', '')])
 
703
        self.assertEqual([('/b/', '')],
 
704
                         self.my_location_config._get_matching_sections())
1420
705
 
1421
706
    def test__get_matching_sections_subdir_child(self):
1422
707
        self.get_branch_config('/a/foo')
1423
 
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
 
708
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
 
709
                         self.my_location_config._get_matching_sections())
1424
710
 
1425
711
    def test__get_matching_sections_subdir_child_child(self):
1426
712
        self.get_branch_config('/a/foo/bar')
1427
 
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
 
713
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
 
714
                         self.my_location_config._get_matching_sections())
1428
715
 
1429
716
    def test__get_matching_sections_trailing_slash_with_children(self):
1430
717
        self.get_branch_config('/a/')
1431
 
        self.assertLocationMatching([('/a/', '')])
 
718
        self.assertEqual([('/a/', '')],
 
719
                         self.my_location_config._get_matching_sections())
1432
720
 
1433
721
    def test__get_matching_sections_explicit_over_glob(self):
1434
722
        # XXX: 2006-09-08 jamesh
1436
724
        # was a config section for '/a/?', it would get precedence
1437
725
        # over '/a/c'.
1438
726
        self.get_branch_config('/a/c')
1439
 
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
 
727
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
 
728
                         self.my_location_config._get_matching_sections())
1440
729
 
1441
730
    def test__get_option_policy_normal(self):
1442
731
        self.get_branch_config('http://www.example.com')
1464
753
            'http://www.example.com', 'appendpath_option'),
1465
754
            config.POLICY_APPENDPATH)
1466
755
 
1467
 
    def test__get_options_with_policy(self):
1468
 
        self.get_branch_config('/dir/subdir',
1469
 
                               location_config="""\
1470
 
[/dir]
1471
 
other_url = /other-dir
1472
 
other_url:policy = appendpath
1473
 
[/dir/subdir]
1474
 
other_url = /other-subdir
1475
 
""")
1476
 
        self.assertOptions(
1477
 
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
1478
 
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
1479
 
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
1480
 
            self.my_location_config)
1481
 
 
1482
756
    def test_location_without_username(self):
1483
757
        self.get_branch_config('http://www.example.com/ignoreparent')
1484
758
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1526
800
        self.get_branch_config('/a')
1527
801
        self.assertEqual("false", self.my_config.gpg_signing_command())
1528
802
 
1529
 
    def test_gpg_signing_key(self):
1530
 
        self.get_branch_config('/b')
1531
 
        self.assertEqual("DD4D5088", self.my_config.gpg_signing_key())
1532
 
 
1533
 
    def test_gpg_signing_key_default(self):
1534
 
        self.get_branch_config('/a')
1535
 
        self.assertEqual("erik@bagfors.nu", self.my_config.gpg_signing_key())
1536
 
 
1537
803
    def test_get_user_option_global(self):
1538
804
        self.get_branch_config('/a')
1539
805
        self.assertEqual('something',
1628
894
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1629
895
                         self.my_config.post_commit())
1630
896
 
1631
 
    def get_branch_config(self, location, global_config=None,
1632
 
                          location_config=None):
1633
 
        my_branch = FakeBranch(location)
 
897
    def get_branch_config(self, location, global_config=None):
1634
898
        if global_config is None:
1635
 
            global_config = sample_config_text
1636
 
        if location_config is None:
1637
 
            location_config = sample_branches_text
1638
 
 
1639
 
        my_global_config = config.GlobalConfig.from_string(global_config,
1640
 
                                                           save=True)
1641
 
        my_location_config = config.LocationConfig.from_string(
1642
 
            location_config, my_branch.base, save=True)
1643
 
        my_config = config.BranchConfig(my_branch)
1644
 
        self.my_config = my_config
1645
 
        self.my_location_config = my_config._get_location_config()
 
899
            global_file = StringIO(sample_config_text.encode('utf-8'))
 
900
        else:
 
901
            global_file = StringIO(global_config.encode('utf-8'))
 
902
        branches_file = StringIO(sample_branches_text.encode('utf-8'))
 
903
        self.my_config = config.BranchConfig(FakeBranch(location))
 
904
        # Force location config to use specified file
 
905
        self.my_location_config = self.my_config._get_location_config()
 
906
        self.my_location_config._get_parser(branches_file)
 
907
        # Force global config to use specified file
 
908
        self.my_config._get_global_config()._get_parser(global_file)
1646
909
 
1647
910
    def test_set_user_setting_sets_and_saves(self):
1648
911
        self.get_branch_config('/a/c')
1649
912
        record = InstrumentedConfigObj("foo")
1650
913
        self.my_location_config._parser = record
1651
914
 
1652
 
        self.callDeprecated(['The recurse option is deprecated as of '
1653
 
                             '0.14.  The section "/a/c" has been '
1654
 
                             'converted to use policies.'],
1655
 
                            self.my_config.set_user_option,
1656
 
                            'foo', 'bar', store=config.STORE_LOCATION)
1657
 
        self.assertEqual([('reload',),
1658
 
                          ('__contains__', '/a/c'),
 
915
        real_mkdir = os.mkdir
 
916
        self.created = False
 
917
        def checked_mkdir(path, mode=0777):
 
918
            self.log('making directory: %s', path)
 
919
            real_mkdir(path, mode)
 
920
            self.created = True
 
921
 
 
922
        os.mkdir = checked_mkdir
 
923
        try:
 
924
            self.callDeprecated(['The recurse option is deprecated as of '
 
925
                                 '0.14.  The section "/a/c" has been '
 
926
                                 'converted to use policies.'],
 
927
                                self.my_config.set_user_option,
 
928
                                'foo', 'bar', store=config.STORE_LOCATION)
 
929
        finally:
 
930
            os.mkdir = real_mkdir
 
931
 
 
932
        self.failUnless(self.created, 'Failed to create ~/.bazaar')
 
933
        self.assertEqual([('__contains__', '/a/c'),
1659
934
                          ('__contains__', '/a/c/'),
1660
935
                          ('__setitem__', '/a/c', {}),
1661
936
                          ('__getitem__', '/a/c'),
1690
965
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1691
966
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1692
967
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1693
 
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
 
968
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
1694
969
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1695
970
 
1696
971
 
1704
979
option = exact
1705
980
"""
1706
981
 
 
982
 
1707
983
class TestBranchConfigItems(tests.TestCaseInTempDir):
1708
984
 
1709
985
    def get_branch_config(self, global_config=None, location=None,
1710
986
                          location_config=None, branch_data_config=None):
1711
 
        my_branch = FakeBranch(location)
 
987
        my_config = config.BranchConfig(FakeBranch(location))
1712
988
        if global_config is not None:
1713
 
            my_global_config = config.GlobalConfig.from_string(global_config,
1714
 
                                                               save=True)
 
989
            global_file = StringIO(global_config.encode('utf-8'))
 
990
            my_config._get_global_config()._get_parser(global_file)
 
991
        self.my_location_config = my_config._get_location_config()
1715
992
        if location_config is not None:
1716
 
            my_location_config = config.LocationConfig.from_string(
1717
 
                location_config, my_branch.base, save=True)
1718
 
        my_config = config.BranchConfig(my_branch)
 
993
            location_file = StringIO(location_config.encode('utf-8'))
 
994
            self.my_location_config._get_parser(location_file)
1719
995
        if branch_data_config is not None:
1720
996
            my_config.branch.control_files.files['branch.conf'] = \
1721
997
                branch_data_config
1735
1011
                         my_config.username())
1736
1012
 
1737
1013
    def test_not_set_in_branch(self):
1738
 
        my_config = self.get_branch_config(global_config=sample_config_text)
 
1014
        my_config = self.get_branch_config(sample_config_text)
1739
1015
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1740
1016
                         my_config._get_user_id())
1741
1017
        my_config.branch.control_files.files['email'] = "John"
1742
1018
        self.assertEqual("John", my_config._get_user_id())
1743
1019
 
1744
1020
    def test_BZR_EMAIL_OVERRIDES(self):
1745
 
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
 
1021
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
1746
1022
        branch = FakeBranch()
1747
1023
        my_config = config.BranchConfig(branch)
1748
1024
        self.assertEqual("Robert Collins <robertc@example.org>",
1765
1041
 
1766
1042
    def test_gpg_signing_command(self):
1767
1043
        my_config = self.get_branch_config(
1768
 
            global_config=sample_config_text,
1769
1044
            # branch data cannot set gpg_signing_command
1770
1045
            branch_data_config="gpg_signing_command=pgp")
 
1046
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
1047
        my_config._get_global_config()._get_parser(config_file)
1771
1048
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1772
1049
 
1773
1050
    def test_get_user_option_global(self):
1774
 
        my_config = self.get_branch_config(global_config=sample_config_text)
 
1051
        branch = FakeBranch()
 
1052
        my_config = config.BranchConfig(branch)
 
1053
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
1054
        (my_config._get_global_config()._get_parser(config_file))
1775
1055
        self.assertEqual('something',
1776
1056
                         my_config.get_user_option('user_global_option'))
1777
1057
 
1778
1058
    def test_post_commit_default(self):
1779
 
        my_config = self.get_branch_config(global_config=sample_config_text,
1780
 
                                      location='/a/c',
1781
 
                                      location_config=sample_branches_text)
 
1059
        branch = FakeBranch()
 
1060
        my_config = self.get_branch_config(sample_config_text, '/a/c',
 
1061
                                           sample_branches_text)
1782
1062
        self.assertEqual(my_config.branch.base, '/a/c')
1783
1063
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1784
1064
                         my_config.post_commit())
1785
1065
        my_config.set_user_option('post_commit', 'rmtree_root')
1786
 
        # post-commit is ignored when present in branch data
 
1066
        # post-commit is ignored when bresent in branch data
1787
1067
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1788
1068
                         my_config.post_commit())
1789
1069
        my_config.set_user_option('post_commit', 'rmtree_root',
1791
1071
        self.assertEqual('rmtree_root', my_config.post_commit())
1792
1072
 
1793
1073
    def test_config_precedence(self):
1794
 
        # FIXME: eager test, luckily no persitent config file makes it fail
1795
 
        # -- vila 20100716
1796
1074
        my_config = self.get_branch_config(global_config=precedence_global)
1797
1075
        self.assertEqual(my_config.get_user_option('option'), 'global')
1798
1076
        my_config = self.get_branch_config(global_config=precedence_global,
1799
 
                                           branch_data_config=precedence_branch)
 
1077
                                      branch_data_config=precedence_branch)
1800
1078
        self.assertEqual(my_config.get_user_option('option'), 'branch')
1801
 
        my_config = self.get_branch_config(
1802
 
            global_config=precedence_global,
1803
 
            branch_data_config=precedence_branch,
1804
 
            location_config=precedence_location)
 
1079
        my_config = self.get_branch_config(global_config=precedence_global,
 
1080
                                      branch_data_config=precedence_branch,
 
1081
                                      location_config=precedence_location)
1805
1082
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
1806
 
        my_config = self.get_branch_config(
1807
 
            global_config=precedence_global,
1808
 
            branch_data_config=precedence_branch,
1809
 
            location_config=precedence_location,
1810
 
            location='http://example.com/specific')
 
1083
        my_config = self.get_branch_config(global_config=precedence_global,
 
1084
                                      branch_data_config=precedence_branch,
 
1085
                                      location_config=precedence_location,
 
1086
                                      location='http://example.com/specific')
1811
1087
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1812
1088
 
1813
1089
    def test_get_mail_client(self):
1903
1179
 
1904
1180
class TestTransportConfig(tests.TestCaseWithTransport):
1905
1181
 
1906
 
    def test_load_utf8(self):
1907
 
        """Ensure we can load an utf8-encoded file."""
1908
 
        t = self.get_transport()
1909
 
        unicode_user = u'b\N{Euro Sign}ar'
1910
 
        unicode_content = u'user=%s' % (unicode_user,)
1911
 
        utf8_content = unicode_content.encode('utf8')
1912
 
        # Store the raw content in the config file
1913
 
        t.put_bytes('foo.conf', utf8_content)
1914
 
        conf = config.TransportConfig(t, 'foo.conf')
1915
 
        self.assertEquals(unicode_user, conf.get_option('user'))
1916
 
 
1917
 
    def test_load_non_ascii(self):
1918
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
1919
 
        t = self.get_transport()
1920
 
        t.put_bytes('foo.conf', 'user=foo\n#\xff\n')
1921
 
        conf = config.TransportConfig(t, 'foo.conf')
1922
 
        self.assertRaises(errors.ConfigContentError, conf._get_configobj)
1923
 
 
1924
 
    def test_load_erroneous_content(self):
1925
 
        """Ensure we display a proper error on content that can't be parsed."""
1926
 
        t = self.get_transport()
1927
 
        t.put_bytes('foo.conf', '[open_section\n')
1928
 
        conf = config.TransportConfig(t, 'foo.conf')
1929
 
        self.assertRaises(errors.ParseConfigError, conf._get_configobj)
1930
 
 
1931
1182
    def test_get_value(self):
1932
1183
        """Test that retreiving a value from a section is possible"""
1933
 
        bzrdir_config = config.TransportConfig(self.get_transport('.'),
 
1184
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1934
1185
                                               'control.conf')
1935
1186
        bzrdir_config.set_option('value', 'key', 'SECTION')
1936
1187
        bzrdir_config.set_option('value2', 'key2')
1956
1207
 
1957
1208
    def test_set_unset_default_stack_on(self):
1958
1209
        my_dir = self.make_bzrdir('.')
1959
 
        bzrdir_config = config.BzrDirConfig(my_dir)
 
1210
        bzrdir_config = config.BzrDirConfig(my_dir.transport)
1960
1211
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1961
1212
        bzrdir_config.set_default_stack_on('Foo')
1962
1213
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1966
1217
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1967
1218
 
1968
1219
 
1969
 
class TestOldConfigHooks(tests.TestCaseWithTransport):
1970
 
 
1971
 
    def setUp(self):
1972
 
        super(TestOldConfigHooks, self).setUp()
1973
 
        create_configs_with_file_option(self)
1974
 
 
1975
 
    def assertGetHook(self, conf, name, value):
1976
 
        calls = []
1977
 
        def hook(*args):
1978
 
            calls.append(args)
1979
 
        config.OldConfigHooks.install_named_hook('get', hook, None)
1980
 
        self.addCleanup(
1981
 
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
1982
 
        self.assertLength(0, calls)
1983
 
        actual_value = conf.get_user_option(name)
1984
 
        self.assertEquals(value, actual_value)
1985
 
        self.assertLength(1, calls)
1986
 
        self.assertEquals((conf, name, value), calls[0])
1987
 
 
1988
 
    def test_get_hook_bazaar(self):
1989
 
        self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
1990
 
 
1991
 
    def test_get_hook_locations(self):
1992
 
        self.assertGetHook(self.locations_config, 'file', 'locations')
1993
 
 
1994
 
    def test_get_hook_branch(self):
1995
 
        # Since locations masks branch, we define a different option
1996
 
        self.branch_config.set_user_option('file2', 'branch')
1997
 
        self.assertGetHook(self.branch_config, 'file2', 'branch')
1998
 
 
1999
 
    def assertSetHook(self, conf, name, value):
2000
 
        calls = []
2001
 
        def hook(*args):
2002
 
            calls.append(args)
2003
 
        config.OldConfigHooks.install_named_hook('set', hook, None)
2004
 
        self.addCleanup(
2005
 
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
2006
 
        self.assertLength(0, calls)
2007
 
        conf.set_user_option(name, value)
2008
 
        self.assertLength(1, calls)
2009
 
        # We can't assert the conf object below as different configs use
2010
 
        # different means to implement set_user_option and we care only about
2011
 
        # coverage here.
2012
 
        self.assertEquals((name, value), calls[0][1:])
2013
 
 
2014
 
    def test_set_hook_bazaar(self):
2015
 
        self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
2016
 
 
2017
 
    def test_set_hook_locations(self):
2018
 
        self.assertSetHook(self.locations_config, 'foo', 'locations')
2019
 
 
2020
 
    def test_set_hook_branch(self):
2021
 
        self.assertSetHook(self.branch_config, 'foo', 'branch')
2022
 
 
2023
 
    def assertRemoveHook(self, conf, name, section_name=None):
2024
 
        calls = []
2025
 
        def hook(*args):
2026
 
            calls.append(args)
2027
 
        config.OldConfigHooks.install_named_hook('remove', hook, None)
2028
 
        self.addCleanup(
2029
 
            config.OldConfigHooks.uninstall_named_hook, 'remove', None)
2030
 
        self.assertLength(0, calls)
2031
 
        conf.remove_user_option(name, section_name)
2032
 
        self.assertLength(1, calls)
2033
 
        # We can't assert the conf object below as different configs use
2034
 
        # different means to implement remove_user_option and we care only about
2035
 
        # coverage here.
2036
 
        self.assertEquals((name,), calls[0][1:])
2037
 
 
2038
 
    def test_remove_hook_bazaar(self):
2039
 
        self.assertRemoveHook(self.bazaar_config, 'file')
2040
 
 
2041
 
    def test_remove_hook_locations(self):
2042
 
        self.assertRemoveHook(self.locations_config, 'file',
2043
 
                              self.locations_config.location)
2044
 
 
2045
 
    def test_remove_hook_branch(self):
2046
 
        self.assertRemoveHook(self.branch_config, 'file')
2047
 
 
2048
 
    def assertLoadHook(self, name, conf_class, *conf_args):
2049
 
        calls = []
2050
 
        def hook(*args):
2051
 
            calls.append(args)
2052
 
        config.OldConfigHooks.install_named_hook('load', hook, None)
2053
 
        self.addCleanup(
2054
 
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
2055
 
        self.assertLength(0, calls)
2056
 
        # Build a config
2057
 
        conf = conf_class(*conf_args)
2058
 
        # Access an option to trigger a load
2059
 
        conf.get_user_option(name)
2060
 
        self.assertLength(1, calls)
2061
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2062
 
 
2063
 
    def test_load_hook_bazaar(self):
2064
 
        self.assertLoadHook('file', config.GlobalConfig)
2065
 
 
2066
 
    def test_load_hook_locations(self):
2067
 
        self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
2068
 
 
2069
 
    def test_load_hook_branch(self):
2070
 
        self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
2071
 
 
2072
 
    def assertSaveHook(self, conf):
2073
 
        calls = []
2074
 
        def hook(*args):
2075
 
            calls.append(args)
2076
 
        config.OldConfigHooks.install_named_hook('save', hook, None)
2077
 
        self.addCleanup(
2078
 
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
2079
 
        self.assertLength(0, calls)
2080
 
        # Setting an option triggers a save
2081
 
        conf.set_user_option('foo', 'bar')
2082
 
        self.assertLength(1, calls)
2083
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2084
 
 
2085
 
    def test_save_hook_bazaar(self):
2086
 
        self.assertSaveHook(self.bazaar_config)
2087
 
 
2088
 
    def test_save_hook_locations(self):
2089
 
        self.assertSaveHook(self.locations_config)
2090
 
 
2091
 
    def test_save_hook_branch(self):
2092
 
        self.assertSaveHook(self.branch_config)
2093
 
 
2094
 
 
2095
 
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
2096
 
    """Tests config hooks for remote configs.
2097
 
 
2098
 
    No tests for the remove hook as this is not implemented there.
2099
 
    """
2100
 
 
2101
 
    def setUp(self):
2102
 
        super(TestOldConfigHooksForRemote, self).setUp()
2103
 
        self.transport_server = test_server.SmartTCPServer_for_testing
2104
 
        create_configs_with_file_option(self)
2105
 
 
2106
 
    def assertGetHook(self, conf, name, value):
2107
 
        calls = []
2108
 
        def hook(*args):
2109
 
            calls.append(args)
2110
 
        config.OldConfigHooks.install_named_hook('get', hook, None)
2111
 
        self.addCleanup(
2112
 
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
2113
 
        self.assertLength(0, calls)
2114
 
        actual_value = conf.get_option(name)
2115
 
        self.assertEquals(value, actual_value)
2116
 
        self.assertLength(1, calls)
2117
 
        self.assertEquals((conf, name, value), calls[0])
2118
 
 
2119
 
    def test_get_hook_remote_branch(self):
2120
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2121
 
        self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
2122
 
 
2123
 
    def test_get_hook_remote_bzrdir(self):
2124
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2125
 
        conf = remote_bzrdir._get_config()
2126
 
        conf.set_option('remotedir', 'file')
2127
 
        self.assertGetHook(conf, 'file', 'remotedir')
2128
 
 
2129
 
    def assertSetHook(self, conf, name, value):
2130
 
        calls = []
2131
 
        def hook(*args):
2132
 
            calls.append(args)
2133
 
        config.OldConfigHooks.install_named_hook('set', hook, None)
2134
 
        self.addCleanup(
2135
 
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
2136
 
        self.assertLength(0, calls)
2137
 
        conf.set_option(value, name)
2138
 
        self.assertLength(1, calls)
2139
 
        # We can't assert the conf object below as different configs use
2140
 
        # different means to implement set_user_option and we care only about
2141
 
        # coverage here.
2142
 
        self.assertEquals((name, value), calls[0][1:])
2143
 
 
2144
 
    def test_set_hook_remote_branch(self):
2145
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2146
 
        self.addCleanup(remote_branch.lock_write().unlock)
2147
 
        self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
2148
 
 
2149
 
    def test_set_hook_remote_bzrdir(self):
2150
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2151
 
        self.addCleanup(remote_branch.lock_write().unlock)
2152
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2153
 
        self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
2154
 
 
2155
 
    def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
2156
 
        calls = []
2157
 
        def hook(*args):
2158
 
            calls.append(args)
2159
 
        config.OldConfigHooks.install_named_hook('load', hook, None)
2160
 
        self.addCleanup(
2161
 
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
2162
 
        self.assertLength(0, calls)
2163
 
        # Build a config
2164
 
        conf = conf_class(*conf_args)
2165
 
        # Access an option to trigger a load
2166
 
        conf.get_option(name)
2167
 
        self.assertLength(expected_nb_calls, calls)
2168
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2169
 
 
2170
 
    def test_load_hook_remote_branch(self):
2171
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2172
 
        self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
2173
 
 
2174
 
    def test_load_hook_remote_bzrdir(self):
2175
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2176
 
        # The config file doesn't exist, set an option to force its creation
2177
 
        conf = remote_bzrdir._get_config()
2178
 
        conf.set_option('remotedir', 'file')
2179
 
        # We get one call for the server and one call for the client, this is
2180
 
        # caused by the differences in implementations betwen
2181
 
        # SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
2182
 
        # SmartServerBranchGetConfigFile (in smart/branch.py)
2183
 
        self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
2184
 
 
2185
 
    def assertSaveHook(self, conf):
2186
 
        calls = []
2187
 
        def hook(*args):
2188
 
            calls.append(args)
2189
 
        config.OldConfigHooks.install_named_hook('save', hook, None)
2190
 
        self.addCleanup(
2191
 
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
2192
 
        self.assertLength(0, calls)
2193
 
        # Setting an option triggers a save
2194
 
        conf.set_option('foo', 'bar')
2195
 
        self.assertLength(1, calls)
2196
 
        # Since we can't assert about conf, we just use the number of calls ;-/
2197
 
 
2198
 
    def test_save_hook_remote_branch(self):
2199
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2200
 
        self.addCleanup(remote_branch.lock_write().unlock)
2201
 
        self.assertSaveHook(remote_branch._get_config())
2202
 
 
2203
 
    def test_save_hook_remote_bzrdir(self):
2204
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
2205
 
        self.addCleanup(remote_branch.lock_write().unlock)
2206
 
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
2207
 
        self.assertSaveHook(remote_bzrdir._get_config())
2208
 
 
2209
 
 
2210
 
class TestOption(tests.TestCase):
2211
 
 
2212
 
    def test_default_value(self):
2213
 
        opt = config.Option('foo', default='bar')
2214
 
        self.assertEquals('bar', opt.get_default())
2215
 
 
2216
 
 
2217
 
class TestOptionRegistry(tests.TestCase):
2218
 
 
2219
 
    def setUp(self):
2220
 
        super(TestOptionRegistry, self).setUp()
2221
 
        # Always start with an empty registry
2222
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2223
 
        self.registry = config.option_registry
2224
 
 
2225
 
    def test_register(self):
2226
 
        opt = config.Option('foo')
2227
 
        self.registry.register(opt)
2228
 
        self.assertIs(opt, self.registry.get('foo'))
2229
 
 
2230
 
    def test_registered_help(self):
2231
 
        opt = config.Option('foo', help='A simple option')
2232
 
        self.registry.register(opt)
2233
 
        self.assertEquals('A simple option', self.registry.get_help('foo'))
2234
 
 
2235
 
    lazy_option = config.Option('lazy_foo', help='Lazy help')
2236
 
 
2237
 
    def test_register_lazy(self):
2238
 
        self.registry.register_lazy('lazy_foo', self.__module__,
2239
 
                                    'TestOptionRegistry.lazy_option')
2240
 
        self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2241
 
 
2242
 
    def test_registered_lazy_help(self):
2243
 
        self.registry.register_lazy('lazy_foo', self.__module__,
2244
 
                                    'TestOptionRegistry.lazy_option')
2245
 
        self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
2246
 
 
2247
 
 
2248
 
class TestRegisteredOptions(tests.TestCase):
2249
 
    """All registered options should verify some constraints."""
2250
 
 
2251
 
    scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2252
 
                 in config.option_registry.iteritems()]
2253
 
 
2254
 
    def setUp(self):
2255
 
        super(TestRegisteredOptions, self).setUp()
2256
 
        self.registry = config.option_registry
2257
 
 
2258
 
    def test_proper_name(self):
2259
 
        # An option should be registered under its own name, this can't be
2260
 
        # checked at registration time for the lazy ones.
2261
 
        self.assertEquals(self.option_name, self.option.name)
2262
 
 
2263
 
    def test_help_is_set(self):
2264
 
        option_help = self.registry.get_help(self.option_name)
2265
 
        self.assertNotEquals(None, option_help)
2266
 
        # Come on, think about the user, he really wants to know what the
2267
 
        # option is about
2268
 
        self.assertIsNot(None, option_help)
2269
 
        self.assertNotEquals('', option_help)
2270
 
 
2271
 
 
2272
 
class TestSection(tests.TestCase):
2273
 
 
2274
 
    # FIXME: Parametrize so that all sections produced by Stores run these
2275
 
    # tests -- vila 2011-04-01
2276
 
 
2277
 
    def test_get_a_value(self):
2278
 
        a_dict = dict(foo='bar')
2279
 
        section = config.Section('myID', a_dict)
2280
 
        self.assertEquals('bar', section.get('foo'))
2281
 
 
2282
 
    def test_get_unknown_option(self):
2283
 
        a_dict = dict()
2284
 
        section = config.Section(None, a_dict)
2285
 
        self.assertEquals('out of thin air',
2286
 
                          section.get('foo', 'out of thin air'))
2287
 
 
2288
 
    def test_options_is_shared(self):
2289
 
        a_dict = dict()
2290
 
        section = config.Section(None, a_dict)
2291
 
        self.assertIs(a_dict, section.options)
2292
 
 
2293
 
 
2294
 
class TestMutableSection(tests.TestCase):
2295
 
 
2296
 
    # FIXME: Parametrize so that all sections (including os.environ and the
2297
 
    # ones produced by Stores) run these tests -- vila 2011-04-01
2298
 
 
2299
 
    def test_set(self):
2300
 
        a_dict = dict(foo='bar')
2301
 
        section = config.MutableSection('myID', a_dict)
2302
 
        section.set('foo', 'new_value')
2303
 
        self.assertEquals('new_value', section.get('foo'))
2304
 
        # The change appears in the shared section
2305
 
        self.assertEquals('new_value', a_dict.get('foo'))
2306
 
        # We keep track of the change
2307
 
        self.assertTrue('foo' in section.orig)
2308
 
        self.assertEquals('bar', section.orig.get('foo'))
2309
 
 
2310
 
    def test_set_preserve_original_once(self):
2311
 
        a_dict = dict(foo='bar')
2312
 
        section = config.MutableSection('myID', a_dict)
2313
 
        section.set('foo', 'first_value')
2314
 
        section.set('foo', 'second_value')
2315
 
        # We keep track of the original value
2316
 
        self.assertTrue('foo' in section.orig)
2317
 
        self.assertEquals('bar', section.orig.get('foo'))
2318
 
 
2319
 
    def test_remove(self):
2320
 
        a_dict = dict(foo='bar')
2321
 
        section = config.MutableSection('myID', a_dict)
2322
 
        section.remove('foo')
2323
 
        # We get None for unknown options via the default value
2324
 
        self.assertEquals(None, section.get('foo'))
2325
 
        # Or we just get the default value
2326
 
        self.assertEquals('unknown', section.get('foo', 'unknown'))
2327
 
        self.assertFalse('foo' in section.options)
2328
 
        # We keep track of the deletion
2329
 
        self.assertTrue('foo' in section.orig)
2330
 
        self.assertEquals('bar', section.orig.get('foo'))
2331
 
 
2332
 
    def test_remove_new_option(self):
2333
 
        a_dict = dict()
2334
 
        section = config.MutableSection('myID', a_dict)
2335
 
        section.set('foo', 'bar')
2336
 
        section.remove('foo')
2337
 
        self.assertFalse('foo' in section.options)
2338
 
        # The option didn't exist initially so it we need to keep track of it
2339
 
        # with a special value
2340
 
        self.assertTrue('foo' in section.orig)
2341
 
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
2342
 
 
2343
 
 
2344
 
class TestStore(tests.TestCaseWithTransport):
2345
 
 
2346
 
    def assertSectionContent(self, expected, section):
2347
 
        """Assert that some options have the proper values in a section."""
2348
 
        expected_name, expected_options = expected
2349
 
        self.assertEquals(expected_name, section.id)
2350
 
        self.assertEquals(
2351
 
            expected_options,
2352
 
            dict([(k, section.get(k)) for k in expected_options.keys()]))
2353
 
 
2354
 
 
2355
 
class TestReadonlyStore(TestStore):
2356
 
 
2357
 
    scenarios = [(key, {'get_store': builder}) for key, builder
2358
 
                 in config.test_store_builder_registry.iteritems()]
2359
 
 
2360
 
    def setUp(self):
2361
 
        super(TestReadonlyStore, self).setUp()
2362
 
 
2363
 
    def test_building_delays_load(self):
2364
 
        store = self.get_store(self)
2365
 
        self.assertEquals(False, store.is_loaded())
2366
 
        store._load_from_string('')
2367
 
        self.assertEquals(True, store.is_loaded())
2368
 
 
2369
 
    def test_get_no_sections_for_empty(self):
2370
 
        store = self.get_store(self)
2371
 
        store._load_from_string('')
2372
 
        self.assertEquals([], list(store.get_sections()))
2373
 
 
2374
 
    def test_get_default_section(self):
2375
 
        store = self.get_store(self)
2376
 
        store._load_from_string('foo=bar')
2377
 
        sections = list(store.get_sections())
2378
 
        self.assertLength(1, sections)
2379
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2380
 
 
2381
 
    def test_get_named_section(self):
2382
 
        store = self.get_store(self)
2383
 
        store._load_from_string('[baz]\nfoo=bar')
2384
 
        sections = list(store.get_sections())
2385
 
        self.assertLength(1, sections)
2386
 
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2387
 
 
2388
 
    def test_load_from_string_fails_for_non_empty_store(self):
2389
 
        store = self.get_store(self)
2390
 
        store._load_from_string('foo=bar')
2391
 
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2392
 
 
2393
 
 
2394
 
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2395
 
    """Simulate loading a config store without content of various encodings.
2396
 
 
2397
 
    All files produced by bzr are in utf8 content.
2398
 
 
2399
 
    Users may modify them manually and end up with a file that can't be
2400
 
    loaded. We need to issue proper error messages in this case.
2401
 
    """
2402
 
 
2403
 
    invalid_utf8_char = '\xff'
2404
 
 
2405
 
    def test_load_utf8(self):
2406
 
        """Ensure we can load an utf8-encoded file."""
2407
 
        t = self.get_transport()
2408
 
        # From http://pad.lv/799212
2409
 
        unicode_user = u'b\N{Euro Sign}ar'
2410
 
        unicode_content = u'user=%s' % (unicode_user,)
2411
 
        utf8_content = unicode_content.encode('utf8')
2412
 
        # Store the raw content in the config file
2413
 
        t.put_bytes('foo.conf', utf8_content)
2414
 
        store = config.IniFileStore(t, 'foo.conf')
2415
 
        store.load()
2416
 
        stack = config.Stack([store.get_sections], store)
2417
 
        self.assertEquals(unicode_user, stack.get('user'))
2418
 
 
2419
 
    def test_load_non_ascii(self):
2420
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2421
 
        t = self.get_transport()
2422
 
        t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2423
 
        store = config.IniFileStore(t, 'foo.conf')
2424
 
        self.assertRaises(errors.ConfigContentError, store.load)
2425
 
 
2426
 
    def test_load_erroneous_content(self):
2427
 
        """Ensure we display a proper error on content that can't be parsed."""
2428
 
        t = self.get_transport()
2429
 
        t.put_bytes('foo.conf', '[open_section\n')
2430
 
        store = config.IniFileStore(t, 'foo.conf')
2431
 
        self.assertRaises(errors.ParseConfigError, store.load)
2432
 
 
2433
 
 
2434
 
class TestIniConfigContent(tests.TestCaseWithTransport):
2435
 
    """Simulate loading a IniBasedConfig without content of various encodings.
2436
 
 
2437
 
    All files produced by bzr are in utf8 content.
2438
 
 
2439
 
    Users may modify them manually and end up with a file that can't be
2440
 
    loaded. We need to issue proper error messages in this case.
2441
 
    """
2442
 
 
2443
 
    invalid_utf8_char = '\xff'
2444
 
 
2445
 
    def test_load_utf8(self):
2446
 
        """Ensure we can load an utf8-encoded file."""
2447
 
        # From http://pad.lv/799212
2448
 
        unicode_user = u'b\N{Euro Sign}ar'
2449
 
        unicode_content = u'user=%s' % (unicode_user,)
2450
 
        utf8_content = unicode_content.encode('utf8')
2451
 
        # Store the raw content in the config file
2452
 
        with open('foo.conf', 'wb') as f:
2453
 
            f.write(utf8_content)
2454
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2455
 
        self.assertEquals(unicode_user, conf.get_user_option('user'))
2456
 
 
2457
 
    def test_load_badly_encoded_content(self):
2458
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2459
 
        with open('foo.conf', 'wb') as f:
2460
 
            f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
2461
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2462
 
        self.assertRaises(errors.ConfigContentError, conf._get_parser)
2463
 
 
2464
 
    def test_load_erroneous_content(self):
2465
 
        """Ensure we display a proper error on content that can't be parsed."""
2466
 
        with open('foo.conf', 'wb') as f:
2467
 
            f.write('[open_section\n')
2468
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2469
 
        self.assertRaises(errors.ParseConfigError, conf._get_parser)
2470
 
 
2471
 
 
2472
 
class TestMutableStore(TestStore):
2473
 
 
2474
 
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2475
 
                 in config.test_store_builder_registry.iteritems()]
2476
 
 
2477
 
    def setUp(self):
2478
 
        super(TestMutableStore, self).setUp()
2479
 
        self.transport = self.get_transport()
2480
 
 
2481
 
    def has_store(self, store):
2482
 
        store_basename = urlutils.relative_url(self.transport.external_url(),
2483
 
                                               store.external_url())
2484
 
        return self.transport.has(store_basename)
2485
 
 
2486
 
    def test_save_empty_creates_no_file(self):
2487
 
        # FIXME: There should be a better way than relying on the test
2488
 
        # parametrization to identify branch.conf -- vila 2011-0526
2489
 
        if self.store_id in ('branch', 'remote_branch'):
2490
 
            raise tests.TestNotApplicable(
2491
 
                'branch.conf is *always* created when a branch is initialized')
2492
 
        store = self.get_store(self)
2493
 
        store.save()
2494
 
        self.assertEquals(False, self.has_store(store))
2495
 
 
2496
 
    def test_save_emptied_succeeds(self):
2497
 
        store = self.get_store(self)
2498
 
        store._load_from_string('foo=bar\n')
2499
 
        section = store.get_mutable_section(None)
2500
 
        section.remove('foo')
2501
 
        store.save()
2502
 
        self.assertEquals(True, self.has_store(store))
2503
 
        modified_store = self.get_store(self)
2504
 
        sections = list(modified_store.get_sections())
2505
 
        self.assertLength(0, sections)
2506
 
 
2507
 
    def test_save_with_content_succeeds(self):
2508
 
        # FIXME: There should be a better way than relying on the test
2509
 
        # parametrization to identify branch.conf -- vila 2011-0526
2510
 
        if self.store_id in ('branch', 'remote_branch'):
2511
 
            raise tests.TestNotApplicable(
2512
 
                'branch.conf is *always* created when a branch is initialized')
2513
 
        store = self.get_store(self)
2514
 
        store._load_from_string('foo=bar\n')
2515
 
        self.assertEquals(False, self.has_store(store))
2516
 
        store.save()
2517
 
        self.assertEquals(True, self.has_store(store))
2518
 
        modified_store = self.get_store(self)
2519
 
        sections = list(modified_store.get_sections())
2520
 
        self.assertLength(1, sections)
2521
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2522
 
 
2523
 
    def test_set_option_in_empty_store(self):
2524
 
        store = self.get_store(self)
2525
 
        section = store.get_mutable_section(None)
2526
 
        section.set('foo', 'bar')
2527
 
        store.save()
2528
 
        modified_store = self.get_store(self)
2529
 
        sections = list(modified_store.get_sections())
2530
 
        self.assertLength(1, sections)
2531
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2532
 
 
2533
 
    def test_set_option_in_default_section(self):
2534
 
        store = self.get_store(self)
2535
 
        store._load_from_string('')
2536
 
        section = store.get_mutable_section(None)
2537
 
        section.set('foo', 'bar')
2538
 
        store.save()
2539
 
        modified_store = self.get_store(self)
2540
 
        sections = list(modified_store.get_sections())
2541
 
        self.assertLength(1, sections)
2542
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2543
 
 
2544
 
    def test_set_option_in_named_section(self):
2545
 
        store = self.get_store(self)
2546
 
        store._load_from_string('')
2547
 
        section = store.get_mutable_section('baz')
2548
 
        section.set('foo', 'bar')
2549
 
        store.save()
2550
 
        modified_store = self.get_store(self)
2551
 
        sections = list(modified_store.get_sections())
2552
 
        self.assertLength(1, sections)
2553
 
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2554
 
 
2555
 
    def test_load_hook(self):
2556
 
        # We first needs to ensure that the store exists
2557
 
        store = self.get_store(self)
2558
 
        section = store.get_mutable_section('baz')
2559
 
        section.set('foo', 'bar')
2560
 
        store.save()
2561
 
        # Now we can try to load it
2562
 
        store = self.get_store(self)
2563
 
        calls = []
2564
 
        def hook(*args):
2565
 
            calls.append(args)
2566
 
        config.ConfigHooks.install_named_hook('load', hook, None)
2567
 
        self.assertLength(0, calls)
2568
 
        store.load()
2569
 
        self.assertLength(1, calls)
2570
 
        self.assertEquals((store,), calls[0])
2571
 
 
2572
 
    def test_save_hook(self):
2573
 
        calls = []
2574
 
        def hook(*args):
2575
 
            calls.append(args)
2576
 
        config.ConfigHooks.install_named_hook('save', hook, None)
2577
 
        self.assertLength(0, calls)
2578
 
        store = self.get_store(self)
2579
 
        section = store.get_mutable_section('baz')
2580
 
        section.set('foo', 'bar')
2581
 
        store.save()
2582
 
        self.assertLength(1, calls)
2583
 
        self.assertEquals((store,), calls[0])
2584
 
 
2585
 
 
2586
 
class TestIniFileStore(TestStore):
2587
 
 
2588
 
    def test_loading_unknown_file_fails(self):
2589
 
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
2590
 
        self.assertRaises(errors.NoSuchFile, store.load)
2591
 
 
2592
 
    def test_invalid_content(self):
2593
 
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2594
 
        self.assertEquals(False, store.is_loaded())
2595
 
        exc = self.assertRaises(
2596
 
            errors.ParseConfigError, store._load_from_string,
2597
 
            'this is invalid !')
2598
 
        self.assertEndsWith(exc.filename, 'foo.conf')
2599
 
        # And the load failed
2600
 
        self.assertEquals(False, store.is_loaded())
2601
 
 
2602
 
    def test_get_embedded_sections(self):
2603
 
        # A more complicated example (which also shows that section names and
2604
 
        # option names share the same name space...)
2605
 
        # FIXME: This should be fixed by forbidding dicts as values ?
2606
 
        # -- vila 2011-04-05
2607
 
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2608
 
        store._load_from_string('''
2609
 
foo=bar
2610
 
l=1,2
2611
 
[DEFAULT]
2612
 
foo_in_DEFAULT=foo_DEFAULT
2613
 
[bar]
2614
 
foo_in_bar=barbar
2615
 
[baz]
2616
 
foo_in_baz=barbaz
2617
 
[[qux]]
2618
 
foo_in_qux=quux
2619
 
''')
2620
 
        sections = list(store.get_sections())
2621
 
        self.assertLength(4, sections)
2622
 
        # The default section has no name.
2623
 
        # List values are provided as lists
2624
 
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
2625
 
                                  sections[0])
2626
 
        self.assertSectionContent(
2627
 
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2628
 
        self.assertSectionContent(
2629
 
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
2630
 
        # sub sections are provided as embedded dicts.
2631
 
        self.assertSectionContent(
2632
 
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2633
 
            sections[3])
2634
 
 
2635
 
 
2636
 
class TestLockableIniFileStore(TestStore):
2637
 
 
2638
 
    def test_create_store_in_created_dir(self):
2639
 
        self.assertPathDoesNotExist('dir')
2640
 
        t = self.get_transport('dir/subdir')
2641
 
        store = config.LockableIniFileStore(t, 'foo.conf')
2642
 
        store.get_mutable_section(None).set('foo', 'bar')
2643
 
        store.save()
2644
 
        self.assertPathExists('dir/subdir')
2645
 
 
2646
 
 
2647
 
class TestConcurrentStoreUpdates(TestStore):
2648
 
    """Test that Stores properly handle conccurent updates.
2649
 
 
2650
 
    New Store implementation may fail some of these tests but until such
2651
 
    implementations exist it's hard to properly filter them from the scenarios
2652
 
    applied here. If you encounter such a case, contact the bzr devs.
2653
 
    """
2654
 
 
2655
 
    scenarios = [(key, {'get_stack': builder}) for key, builder
2656
 
                 in config.test_stack_builder_registry.iteritems()]
2657
 
 
2658
 
    def setUp(self):
2659
 
        super(TestConcurrentStoreUpdates, self).setUp()
2660
 
        self._content = 'one=1\ntwo=2\n'
2661
 
        self.stack = self.get_stack(self)
2662
 
        if not isinstance(self.stack, config._CompatibleStack):
2663
 
            raise tests.TestNotApplicable(
2664
 
                '%s is not meant to be compatible with the old config design'
2665
 
                % (self.stack,))
2666
 
        self.stack.store._load_from_string(self._content)
2667
 
        # Flush the store
2668
 
        self.stack.store.save()
2669
 
 
2670
 
    def test_simple_read_access(self):
2671
 
        self.assertEquals('1', self.stack.get('one'))
2672
 
 
2673
 
    def test_simple_write_access(self):
2674
 
        self.stack.set('one', 'one')
2675
 
        self.assertEquals('one', self.stack.get('one'))
2676
 
 
2677
 
    def test_listen_to_the_last_speaker(self):
2678
 
        c1 = self.stack
2679
 
        c2 = self.get_stack(self)
2680
 
        c1.set('one', 'ONE')
2681
 
        c2.set('two', 'TWO')
2682
 
        self.assertEquals('ONE', c1.get('one'))
2683
 
        self.assertEquals('TWO', c2.get('two'))
2684
 
        # The second update respect the first one
2685
 
        self.assertEquals('ONE', c2.get('one'))
2686
 
 
2687
 
    def test_last_speaker_wins(self):
2688
 
        # If the same config is not shared, the same variable modified twice
2689
 
        # can only see a single result.
2690
 
        c1 = self.stack
2691
 
        c2 = self.get_stack(self)
2692
 
        c1.set('one', 'c1')
2693
 
        c2.set('one', 'c2')
2694
 
        self.assertEquals('c2', c2.get('one'))
2695
 
        # The first modification is still available until another refresh
2696
 
        # occur
2697
 
        self.assertEquals('c1', c1.get('one'))
2698
 
        c1.set('two', 'done')
2699
 
        self.assertEquals('c2', c1.get('one'))
2700
 
 
2701
 
    def test_writes_are_serialized(self):
2702
 
        c1 = self.stack
2703
 
        c2 = self.get_stack(self)
2704
 
 
2705
 
        # We spawn a thread that will pause *during* the config saving.
2706
 
        before_writing = threading.Event()
2707
 
        after_writing = threading.Event()
2708
 
        writing_done = threading.Event()
2709
 
        c1_save_without_locking_orig = c1.store.save_without_locking
2710
 
        def c1_save_without_locking():
2711
 
            before_writing.set()
2712
 
            c1_save_without_locking_orig()
2713
 
            # The lock is held. We wait for the main thread to decide when to
2714
 
            # continue
2715
 
            after_writing.wait()
2716
 
        c1.store.save_without_locking = c1_save_without_locking
2717
 
        def c1_set():
2718
 
            c1.set('one', 'c1')
2719
 
            writing_done.set()
2720
 
        t1 = threading.Thread(target=c1_set)
2721
 
        # Collect the thread after the test
2722
 
        self.addCleanup(t1.join)
2723
 
        # Be ready to unblock the thread if the test goes wrong
2724
 
        self.addCleanup(after_writing.set)
2725
 
        t1.start()
2726
 
        before_writing.wait()
2727
 
        self.assertRaises(errors.LockContention,
2728
 
                          c2.set, 'one', 'c2')
2729
 
        self.assertEquals('c1', c1.get('one'))
2730
 
        # Let the lock be released
2731
 
        after_writing.set()
2732
 
        writing_done.wait()
2733
 
        c2.set('one', 'c2')
2734
 
        self.assertEquals('c2', c2.get('one'))
2735
 
 
2736
 
    def test_read_while_writing(self):
2737
 
       c1 = self.stack
2738
 
       # We spawn a thread that will pause *during* the write
2739
 
       ready_to_write = threading.Event()
2740
 
       do_writing = threading.Event()
2741
 
       writing_done = threading.Event()
2742
 
       # We override the _save implementation so we know the store is locked
2743
 
       c1_save_without_locking_orig = c1.store.save_without_locking
2744
 
       def c1_save_without_locking():
2745
 
           ready_to_write.set()
2746
 
           # The lock is held. We wait for the main thread to decide when to
2747
 
           # continue
2748
 
           do_writing.wait()
2749
 
           c1_save_without_locking_orig()
2750
 
           writing_done.set()
2751
 
       c1.store.save_without_locking = c1_save_without_locking
2752
 
       def c1_set():
2753
 
           c1.set('one', 'c1')
2754
 
       t1 = threading.Thread(target=c1_set)
2755
 
       # Collect the thread after the test
2756
 
       self.addCleanup(t1.join)
2757
 
       # Be ready to unblock the thread if the test goes wrong
2758
 
       self.addCleanup(do_writing.set)
2759
 
       t1.start()
2760
 
       # Ensure the thread is ready to write
2761
 
       ready_to_write.wait()
2762
 
       self.assertEquals('c1', c1.get('one'))
2763
 
       # If we read during the write, we get the old value
2764
 
       c2 = self.get_stack(self)
2765
 
       self.assertEquals('1', c2.get('one'))
2766
 
       # Let the writing occur and ensure it occurred
2767
 
       do_writing.set()
2768
 
       writing_done.wait()
2769
 
       # Now we get the updated value
2770
 
       c3 = self.get_stack(self)
2771
 
       self.assertEquals('c1', c3.get('one'))
2772
 
 
2773
 
    # FIXME: It may be worth looking into removing the lock dir when it's not
2774
 
    # needed anymore and look at possible fallouts for concurrent lockers. This
2775
 
    # will matter if/when we use config files outside of bazaar directories
2776
 
    # (.bazaar or .bzr) -- vila 20110-04-11
2777
 
 
2778
 
 
2779
 
class TestSectionMatcher(TestStore):
2780
 
 
2781
 
    scenarios = [('location', {'matcher': config.LocationMatcher})]
2782
 
 
2783
 
    def get_store(self, file_name):
2784
 
        return config.IniFileStore(self.get_readonly_transport(), file_name)
2785
 
 
2786
 
    def test_no_matches_for_empty_stores(self):
2787
 
        store = self.get_store('foo.conf')
2788
 
        store._load_from_string('')
2789
 
        matcher = self.matcher(store, '/bar')
2790
 
        self.assertEquals([], list(matcher.get_sections()))
2791
 
 
2792
 
    def test_build_doesnt_load_store(self):
2793
 
        store = self.get_store('foo.conf')
2794
 
        matcher = self.matcher(store, '/bar')
2795
 
        self.assertFalse(store.is_loaded())
2796
 
 
2797
 
 
2798
 
class TestLocationSection(tests.TestCase):
2799
 
 
2800
 
    def get_section(self, options, extra_path):
2801
 
        section = config.Section('foo', options)
2802
 
        # We don't care about the length so we use '0'
2803
 
        return config.LocationSection(section, 0, extra_path)
2804
 
 
2805
 
    def test_simple_option(self):
2806
 
        section = self.get_section({'foo': 'bar'}, '')
2807
 
        self.assertEquals('bar', section.get('foo'))
2808
 
 
2809
 
    def test_option_with_extra_path(self):
2810
 
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
2811
 
                                   'baz')
2812
 
        self.assertEquals('bar/baz', section.get('foo'))
2813
 
 
2814
 
    def test_invalid_policy(self):
2815
 
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
2816
 
                                   'baz')
2817
 
        # invalid policies are ignored
2818
 
        self.assertEquals('bar', section.get('foo'))
2819
 
 
2820
 
 
2821
 
class TestLocationMatcher(TestStore):
2822
 
 
2823
 
    def get_store(self, file_name):
2824
 
        return config.IniFileStore(self.get_readonly_transport(), file_name)
2825
 
 
2826
 
    def test_more_specific_sections_first(self):
2827
 
        store = self.get_store('foo.conf')
2828
 
        store._load_from_string('''
2829
 
[/foo]
2830
 
section=/foo
2831
 
[/foo/bar]
2832
 
section=/foo/bar
2833
 
''')
2834
 
        self.assertEquals(['/foo', '/foo/bar'],
2835
 
                          [section.id for section in store.get_sections()])
2836
 
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
2837
 
        sections = list(matcher.get_sections())
2838
 
        self.assertEquals([3, 2],
2839
 
                          [section.length for section in sections])
2840
 
        self.assertEquals(['/foo/bar', '/foo'],
2841
 
                          [section.id for section in sections])
2842
 
        self.assertEquals(['baz', 'bar/baz'],
2843
 
                          [section.extra_path for section in sections])
2844
 
 
2845
 
    def test_appendpath_in_no_name_section(self):
2846
 
        # It's a bit weird to allow appendpath in a no-name section, but
2847
 
        # someone may found a use for it
2848
 
        store = self.get_store('foo.conf')
2849
 
        store._load_from_string('''
2850
 
foo=bar
2851
 
foo:policy = appendpath
2852
 
''')
2853
 
        matcher = config.LocationMatcher(store, 'dir/subdir')
2854
 
        sections = list(matcher.get_sections())
2855
 
        self.assertLength(1, sections)
2856
 
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
2857
 
 
2858
 
    def test_file_urls_are_normalized(self):
2859
 
        store = self.get_store('foo.conf')
2860
 
        if sys.platform == 'win32':
2861
 
            expected_url = 'file:///C:/dir/subdir'
2862
 
            expected_location = 'C:/dir/subdir'
2863
 
        else:
2864
 
            expected_url = 'file:///dir/subdir'
2865
 
            expected_location = '/dir/subdir'
2866
 
        matcher = config.LocationMatcher(store, expected_url)
2867
 
        self.assertEquals(expected_location, matcher.location)
2868
 
 
2869
 
 
2870
 
class TestStackGet(tests.TestCase):
2871
 
 
2872
 
    # FIXME: This should be parametrized for all known Stack or dedicated
2873
 
    # paramerized tests created to avoid bloating -- vila 2011-03-31
2874
 
 
2875
 
    def overrideOptionRegistry(self):
2876
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2877
 
 
2878
 
    def test_single_config_get(self):
2879
 
        conf = dict(foo='bar')
2880
 
        conf_stack = config.Stack([conf])
2881
 
        self.assertEquals('bar', conf_stack.get('foo'))
2882
 
 
2883
 
    def test_get_with_registered_default_value(self):
2884
 
        conf_stack = config.Stack([dict()])
2885
 
        opt = config.Option('foo', default='bar')
2886
 
        self.overrideOptionRegistry()
2887
 
        config.option_registry.register('foo', opt)
2888
 
        self.assertEquals('bar', conf_stack.get('foo'))
2889
 
 
2890
 
    def test_get_without_registered_default_value(self):
2891
 
        conf_stack = config.Stack([dict()])
2892
 
        opt = config.Option('foo')
2893
 
        self.overrideOptionRegistry()
2894
 
        config.option_registry.register('foo', opt)
2895
 
        self.assertEquals(None, conf_stack.get('foo'))
2896
 
 
2897
 
    def test_get_without_default_value_for_not_registered(self):
2898
 
        conf_stack = config.Stack([dict()])
2899
 
        opt = config.Option('foo')
2900
 
        self.overrideOptionRegistry()
2901
 
        self.assertEquals(None, conf_stack.get('foo'))
2902
 
 
2903
 
    def test_get_first_definition(self):
2904
 
        conf1 = dict(foo='bar')
2905
 
        conf2 = dict(foo='baz')
2906
 
        conf_stack = config.Stack([conf1, conf2])
2907
 
        self.assertEquals('bar', conf_stack.get('foo'))
2908
 
 
2909
 
    def test_get_embedded_definition(self):
2910
 
        conf1 = dict(yy='12')
2911
 
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
2912
 
        conf_stack = config.Stack([conf1, conf2])
2913
 
        self.assertEquals('baz', conf_stack.get('foo'))
2914
 
 
2915
 
    def test_get_for_empty_section_callable(self):
2916
 
        conf_stack = config.Stack([lambda : []])
2917
 
        self.assertEquals(None, conf_stack.get('foo'))
2918
 
 
2919
 
    def test_get_for_broken_callable(self):
2920
 
        # Trying to use and invalid callable raises an exception on first use
2921
 
        conf_stack = config.Stack([lambda : object()])
2922
 
        self.assertRaises(TypeError, conf_stack.get, 'foo')
2923
 
 
2924
 
 
2925
 
class TestStackWithTransport(tests.TestCaseWithTransport):
2926
 
 
2927
 
    scenarios = [(key, {'get_stack': builder}) for key, builder
2928
 
                 in config.test_stack_builder_registry.iteritems()]
2929
 
 
2930
 
 
2931
 
class TestConcreteStacks(TestStackWithTransport):
2932
 
 
2933
 
    def test_build_stack(self):
2934
 
        # Just a smoke test to help debug builders
2935
 
        stack = self.get_stack(self)
2936
 
 
2937
 
 
2938
 
class TestStackGet(TestStackWithTransport):
2939
 
 
2940
 
    def setUp(self):
2941
 
        super(TestStackGet, self).setUp()
2942
 
        self.conf = self.get_stack(self)
2943
 
 
2944
 
    def test_get_for_empty_stack(self):
2945
 
        self.assertEquals(None, self.conf.get('foo'))
2946
 
 
2947
 
    def test_get_hook(self):
2948
 
        self.conf.store._load_from_string('foo=bar')
2949
 
        calls = []
2950
 
        def hook(*args):
2951
 
            calls.append(args)
2952
 
        config.ConfigHooks.install_named_hook('get', hook, None)
2953
 
        self.assertLength(0, calls)
2954
 
        value = self.conf.get('foo')
2955
 
        self.assertEquals('bar', value)
2956
 
        self.assertLength(1, calls)
2957
 
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
2958
 
 
2959
 
 
2960
 
class TestStackGetWithConverter(TestStackGet):
2961
 
 
2962
 
    def setUp(self):
2963
 
        super(TestStackGetWithConverter, self).setUp()
2964
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2965
 
        self.registry = config.option_registry
2966
 
 
2967
 
    def register_bool_option(self, name, default, invalid=None):
2968
 
        b = config.Option(name, default=default, help='A boolean.',
2969
 
                          from_unicode=config.bool_from_store,
2970
 
                          invalid=invalid)
2971
 
        self.registry.register(b)
2972
 
 
2973
 
    def test_get_with_bool_not_defined_default_true(self):
2974
 
        self.register_bool_option('foo', True)
2975
 
        self.assertEquals(True, self.conf.get('foo'))
2976
 
 
2977
 
    def test_get_with_bool_not_defined_default_false(self):
2978
 
        self.register_bool_option('foo', False)
2979
 
        self.assertEquals(False, self.conf.get('foo'))
2980
 
 
2981
 
    def test_get_with_bool_converter_not_default(self):
2982
 
        self.register_bool_option('foo', False)
2983
 
        self.conf.store._load_from_string('foo=yes')
2984
 
        self.assertEquals(True, self.conf.get('foo'))
2985
 
 
2986
 
    def test_get_with_bool_converter_invalid_string(self):
2987
 
        self.register_bool_option('foo', False)
2988
 
        self.conf.store._load_from_string('foo=not-a-boolean')
2989
 
        self.assertEquals(False, self.conf.get('foo'))
2990
 
 
2991
 
    def test_get_with_bool_converter_invalid_list(self):
2992
 
        self.register_bool_option('foo', False)
2993
 
        self.conf.store._load_from_string('foo=not,a,boolean')
2994
 
        self.assertEquals(False, self.conf.get('foo'))
2995
 
 
2996
 
    def test_get_invalid_warns(self):
2997
 
        self.register_bool_option('foo', False, invalid='warning')
2998
 
        self.conf.store._load_from_string('foo=not-a-boolean')
2999
 
        warnings = []
3000
 
        def warning(*args):
3001
 
            warnings.append(args[0] % args[1:])
3002
 
        self.overrideAttr(trace, 'warning', warning)
3003
 
        self.assertEquals(False, self.conf.get('foo'))
3004
 
        self.assertLength(1, warnings)
3005
 
        self.assertEquals('Value "not-a-boolean" is not valid for "foo"',
3006
 
                          warnings[0])
3007
 
 
3008
 
    def test_get_invalid_errors(self):
3009
 
        self.register_bool_option('foo', False, invalid='error')
3010
 
        self.conf.store._load_from_string('foo=not-a-boolean')
3011
 
        self.assertRaises(errors.ConfigOptionValueError, self.conf.get, 'foo')
3012
 
 
3013
 
    def register_integer_option(self, name, default):
3014
 
        i = config.Option(name, default=default, help='An integer.',
3015
 
                          from_unicode=config.int_from_store)
3016
 
        self.registry.register(i)
3017
 
 
3018
 
    def test_get_with_integer_not_defined_returns_default(self):
3019
 
        self.register_integer_option('foo', 42)
3020
 
        self.assertEquals(42, self.conf.get('foo'))
3021
 
 
3022
 
    def test_get_with_integer_converter_not_default(self):
3023
 
        self.register_integer_option('foo', 42)
3024
 
        self.conf.store._load_from_string('foo=16')
3025
 
        self.assertEquals(16, self.conf.get('foo'))
3026
 
 
3027
 
    def test_get_with_integer_converter_invalid_string(self):
3028
 
        # We don't set a default value
3029
 
        self.register_integer_option('foo', None)
3030
 
        self.conf.store._load_from_string('foo=forty-two')
3031
 
        # No default value, so we should get None
3032
 
        self.assertEquals(None, self.conf.get('foo'))
3033
 
 
3034
 
    def test_get_with_integer_converter_invalid_list(self):
3035
 
        # We don't set a default value
3036
 
        self.register_integer_option('foo', None)
3037
 
        self.conf.store._load_from_string('foo=a,list')
3038
 
        # No default value, so we should get None
3039
 
        self.assertEquals(None, self.conf.get('foo'))
3040
 
 
3041
 
    def register_list_option(self, name, default):
3042
 
        l = config.Option(name, default=default, help='A list.',
3043
 
                          from_unicode=config.list_from_store)
3044
 
        self.registry.register(l)
3045
 
 
3046
 
    def test_get_with_list_not_defined_returns_default(self):
3047
 
        self.register_list_option('foo', [])
3048
 
        self.assertEquals([], self.conf.get('foo'))
3049
 
 
3050
 
    def test_get_with_list_converter_nothing(self):
3051
 
        self.register_list_option('foo', [1])
3052
 
        self.conf.store._load_from_string('foo=')
3053
 
        self.assertEquals([], self.conf.get('foo'))
3054
 
 
3055
 
    def test_get_with_list_converter_no_item(self):
3056
 
        self.register_list_option('foo', [1])
3057
 
        self.conf.store._load_from_string('foo=,')
3058
 
        self.assertEquals([], self.conf.get('foo'))
3059
 
 
3060
 
    def test_get_with_list_converter_one_boolean(self):
3061
 
        self.register_list_option('foo', [1])
3062
 
        self.conf.store._load_from_string('foo=True')
3063
 
        # We get a list of one string
3064
 
        self.assertEquals(['True'], self.conf.get('foo'))
3065
 
 
3066
 
    def test_get_with_list_converter_one_integer(self):
3067
 
        self.register_list_option('foo', [1])
3068
 
        self.conf.store._load_from_string('foo=2')
3069
 
        # We get a list of one string
3070
 
        self.assertEquals(['2'], self.conf.get('foo'))
3071
 
 
3072
 
    def test_get_with_list_converter_one_string(self):
3073
 
        self.register_list_option('foo', ['foo'])
3074
 
        self.conf.store._load_from_string('foo=bar')
3075
 
        # We get a list of one string
3076
 
        self.assertEquals(['bar'], self.conf.get('foo'))
3077
 
 
3078
 
    def test_get_with_list_converter_many_items(self):
3079
 
        self.register_list_option('foo', [1])
3080
 
        self.conf.store._load_from_string('foo=m,o,r,e')
3081
 
        self.assertEquals(['m', 'o', 'r', 'e'], self.conf.get('foo'))
3082
 
 
3083
 
 
3084
 
class TestStackSet(TestStackWithTransport):
3085
 
 
3086
 
    def test_simple_set(self):
3087
 
        conf = self.get_stack(self)
3088
 
        conf.store._load_from_string('foo=bar')
3089
 
        self.assertEquals('bar', conf.get('foo'))
3090
 
        conf.set('foo', 'baz')
3091
 
        # Did we get it back ?
3092
 
        self.assertEquals('baz', conf.get('foo'))
3093
 
 
3094
 
    def test_set_creates_a_new_section(self):
3095
 
        conf = self.get_stack(self)
3096
 
        conf.set('foo', 'baz')
3097
 
        self.assertEquals, 'baz', conf.get('foo')
3098
 
 
3099
 
    def test_set_hook(self):
3100
 
        calls = []
3101
 
        def hook(*args):
3102
 
            calls.append(args)
3103
 
        config.ConfigHooks.install_named_hook('set', hook, None)
3104
 
        self.assertLength(0, calls)
3105
 
        conf = self.get_stack(self)
3106
 
        conf.set('foo', 'bar')
3107
 
        self.assertLength(1, calls)
3108
 
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
3109
 
 
3110
 
 
3111
 
class TestStackRemove(TestStackWithTransport):
3112
 
 
3113
 
    def test_remove_existing(self):
3114
 
        conf = self.get_stack(self)
3115
 
        conf.store._load_from_string('foo=bar')
3116
 
        self.assertEquals('bar', conf.get('foo'))
3117
 
        conf.remove('foo')
3118
 
        # Did we get it back ?
3119
 
        self.assertEquals(None, conf.get('foo'))
3120
 
 
3121
 
    def test_remove_unknown(self):
3122
 
        conf = self.get_stack(self)
3123
 
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3124
 
 
3125
 
    def test_remove_hook(self):
3126
 
        calls = []
3127
 
        def hook(*args):
3128
 
            calls.append(args)
3129
 
        config.ConfigHooks.install_named_hook('remove', hook, None)
3130
 
        self.assertLength(0, calls)
3131
 
        conf = self.get_stack(self)
3132
 
        conf.store._load_from_string('foo=bar')
3133
 
        conf.remove('foo')
3134
 
        self.assertLength(1, calls)
3135
 
        self.assertEquals((conf, 'foo'), calls[0])
3136
 
 
3137
 
 
3138
 
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3139
 
 
3140
 
    def setUp(self):
3141
 
        super(TestConfigGetOptions, self).setUp()
3142
 
        create_configs(self)
3143
 
 
3144
 
    def test_no_variable(self):
3145
 
        # Using branch should query branch, locations and bazaar
3146
 
        self.assertOptions([], self.branch_config)
3147
 
 
3148
 
    def test_option_in_bazaar(self):
3149
 
        self.bazaar_config.set_user_option('file', 'bazaar')
3150
 
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
3151
 
                           self.bazaar_config)
3152
 
 
3153
 
    def test_option_in_locations(self):
3154
 
        self.locations_config.set_user_option('file', 'locations')
3155
 
        self.assertOptions(
3156
 
            [('file', 'locations', self.tree.basedir, 'locations')],
3157
 
            self.locations_config)
3158
 
 
3159
 
    def test_option_in_branch(self):
3160
 
        self.branch_config.set_user_option('file', 'branch')
3161
 
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
3162
 
                           self.branch_config)
3163
 
 
3164
 
    def test_option_in_bazaar_and_branch(self):
3165
 
        self.bazaar_config.set_user_option('file', 'bazaar')
3166
 
        self.branch_config.set_user_option('file', 'branch')
3167
 
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
3168
 
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3169
 
                           self.branch_config)
3170
 
 
3171
 
    def test_option_in_branch_and_locations(self):
3172
 
        # Hmm, locations override branch :-/
3173
 
        self.locations_config.set_user_option('file', 'locations')
3174
 
        self.branch_config.set_user_option('file', 'branch')
3175
 
        self.assertOptions(
3176
 
            [('file', 'locations', self.tree.basedir, 'locations'),
3177
 
             ('file', 'branch', 'DEFAULT', 'branch'),],
3178
 
            self.branch_config)
3179
 
 
3180
 
    def test_option_in_bazaar_locations_and_branch(self):
3181
 
        self.bazaar_config.set_user_option('file', 'bazaar')
3182
 
        self.locations_config.set_user_option('file', 'locations')
3183
 
        self.branch_config.set_user_option('file', 'branch')
3184
 
        self.assertOptions(
3185
 
            [('file', 'locations', self.tree.basedir, 'locations'),
3186
 
             ('file', 'branch', 'DEFAULT', 'branch'),
3187
 
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3188
 
            self.branch_config)
3189
 
 
3190
 
 
3191
 
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
3192
 
 
3193
 
    def setUp(self):
3194
 
        super(TestConfigRemoveOption, self).setUp()
3195
 
        create_configs_with_file_option(self)
3196
 
 
3197
 
    def test_remove_in_locations(self):
3198
 
        self.locations_config.remove_user_option('file', self.tree.basedir)
3199
 
        self.assertOptions(
3200
 
            [('file', 'branch', 'DEFAULT', 'branch'),
3201
 
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3202
 
            self.branch_config)
3203
 
 
3204
 
    def test_remove_in_branch(self):
3205
 
        self.branch_config.remove_user_option('file')
3206
 
        self.assertOptions(
3207
 
            [('file', 'locations', self.tree.basedir, 'locations'),
3208
 
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
3209
 
            self.branch_config)
3210
 
 
3211
 
    def test_remove_in_bazaar(self):
3212
 
        self.bazaar_config.remove_user_option('file')
3213
 
        self.assertOptions(
3214
 
            [('file', 'locations', self.tree.basedir, 'locations'),
3215
 
             ('file', 'branch', 'DEFAULT', 'branch'),],
3216
 
            self.branch_config)
3217
 
 
3218
 
 
3219
 
class TestConfigGetSections(tests.TestCaseWithTransport):
3220
 
 
3221
 
    def setUp(self):
3222
 
        super(TestConfigGetSections, self).setUp()
3223
 
        create_configs(self)
3224
 
 
3225
 
    def assertSectionNames(self, expected, conf, name=None):
3226
 
        """Check which sections are returned for a given config.
3227
 
 
3228
 
        If fallback configurations exist their sections can be included.
3229
 
 
3230
 
        :param expected: A list of section names.
3231
 
 
3232
 
        :param conf: The configuration that will be queried.
3233
 
 
3234
 
        :param name: An optional section name that will be passed to
3235
 
            get_sections().
3236
 
        """
3237
 
        sections = list(conf._get_sections(name))
3238
 
        self.assertLength(len(expected), sections)
3239
 
        self.assertEqual(expected, [name for name, _, _ in sections])
3240
 
 
3241
 
    def test_bazaar_default_section(self):
3242
 
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
3243
 
 
3244
 
    def test_locations_default_section(self):
3245
 
        # No sections are defined in an empty file
3246
 
        self.assertSectionNames([], self.locations_config)
3247
 
 
3248
 
    def test_locations_named_section(self):
3249
 
        self.locations_config.set_user_option('file', 'locations')
3250
 
        self.assertSectionNames([self.tree.basedir], self.locations_config)
3251
 
 
3252
 
    def test_locations_matching_sections(self):
3253
 
        loc_config = self.locations_config
3254
 
        loc_config.set_user_option('file', 'locations')
3255
 
        # We need to cheat a bit here to create an option in sections above and
3256
 
        # below the 'location' one.
3257
 
        parser = loc_config._get_parser()
3258
 
        # locations.cong deals with '/' ignoring native os.sep
3259
 
        location_names = self.tree.basedir.split('/')
3260
 
        parent = '/'.join(location_names[:-1])
3261
 
        child = '/'.join(location_names + ['child'])
3262
 
        parser[parent] = {}
3263
 
        parser[parent]['file'] = 'parent'
3264
 
        parser[child] = {}
3265
 
        parser[child]['file'] = 'child'
3266
 
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
3267
 
 
3268
 
    def test_branch_data_default_section(self):
3269
 
        self.assertSectionNames([None],
3270
 
                                self.branch_config._get_branch_data_config())
3271
 
 
3272
 
    def test_branch_default_sections(self):
3273
 
        # No sections are defined in an empty locations file
3274
 
        self.assertSectionNames([None, 'DEFAULT'],
3275
 
                                self.branch_config)
3276
 
        # Unless we define an option
3277
 
        self.branch_config._get_location_config().set_user_option(
3278
 
            'file', 'locations')
3279
 
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
3280
 
                                self.branch_config)
3281
 
 
3282
 
    def test_bazaar_named_section(self):
3283
 
        # We need to cheat as the API doesn't give direct access to sections
3284
 
        # other than DEFAULT.
3285
 
        self.bazaar_config.set_alias('bazaar', 'bzr')
3286
 
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
3287
 
 
3288
 
 
3289
1220
class TestAuthenticationConfigFile(tests.TestCase):
3290
1221
    """Test the authentication.conf file matching"""
3291
1222
 
3306
1237
        self.assertEquals({}, conf._get_config())
3307
1238
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
3308
1239
 
3309
 
    def test_non_utf8_config(self):
3310
 
        conf = config.AuthenticationConfig(_file=StringIO(
3311
 
                'foo = bar\xff'))
3312
 
        self.assertRaises(errors.ConfigContentError, conf._get_config)
3313
 
 
3314
1240
    def test_missing_auth_section_header(self):
3315
1241
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
3316
1242
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3337
1263
"""))
3338
1264
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3339
1265
 
3340
 
    def test_unknown_password_encoding(self):
3341
 
        conf = config.AuthenticationConfig(_file=StringIO(
3342
 
                """[broken]
3343
 
scheme=ftp
3344
 
user=joe
3345
 
password_encoding=unknown
3346
 
"""))
3347
 
        self.assertRaises(ValueError, conf.get_password,
3348
 
                          'ftp', 'foo.net', 'joe')
3349
 
 
3350
1266
    def test_credentials_for_scheme_host(self):
3351
1267
        conf = config.AuthenticationConfig(_file=StringIO(
3352
1268
                """# Identity on foo.net
3496
1412
        self.assertEquals(True, credentials.get('verify_certificates'))
3497
1413
 
3498
1414
 
3499
 
class TestAuthenticationStorage(tests.TestCaseInTempDir):
3500
 
 
3501
 
    def test_set_credentials(self):
3502
 
        conf = config.AuthenticationConfig()
3503
 
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
3504
 
        99, path='/foo', verify_certificates=False, realm='realm')
3505
 
        credentials = conf.get_credentials(host='host', scheme='scheme',
3506
 
                                           port=99, path='/foo',
3507
 
                                           realm='realm')
3508
 
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
3509
 
                       'verify_certificates': False, 'scheme': 'scheme', 
3510
 
                       'host': 'host', 'port': 99, 'path': '/foo', 
3511
 
                       'realm': 'realm'}
3512
 
        self.assertEqual(CREDENTIALS, credentials)
3513
 
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
3514
 
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
3515
 
        self.assertEqual(CREDENTIALS, credentials_from_disk)
3516
 
 
3517
 
    def test_reset_credentials_different_name(self):
3518
 
        conf = config.AuthenticationConfig()
3519
 
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
3520
 
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
3521
 
        self.assertIs(None, conf._get_config().get('name'))
3522
 
        credentials = conf.get_credentials(host='host', scheme='scheme')
3523
 
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
3524
 
                       'password', 'verify_certificates': True, 
3525
 
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
3526
 
                       'path': None, 'realm': None}
3527
 
        self.assertEqual(CREDENTIALS, credentials)
3528
 
 
3529
 
 
3530
1415
class TestAuthenticationConfig(tests.TestCase):
3531
1416
    """Test AuthenticationConfig behaviour"""
3532
1417
 
3533
 
    def _check_default_password_prompt(self, expected_prompt_format, scheme,
3534
 
                                       host=None, port=None, realm=None,
3535
 
                                       path=None):
 
1418
    def _check_default_prompt(self, expected_prompt_format, scheme,
 
1419
                              host=None, port=None, realm=None, path=None):
3536
1420
        if host is None:
3537
1421
            host = 'bar.org'
3538
1422
        user, password = 'jim', 'precious'
3541
1425
            'user': user, 'realm': realm}
3542
1426
 
3543
1427
        stdout = tests.StringIOWrapper()
3544
 
        stderr = tests.StringIOWrapper()
3545
1428
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
3546
 
                                            stdout=stdout, stderr=stderr)
 
1429
                                            stdout=stdout)
3547
1430
        # We use an empty conf so that the user is always prompted
3548
1431
        conf = config.AuthenticationConfig()
3549
1432
        self.assertEquals(password,
3550
1433
                          conf.get_password(scheme, host, user, port=port,
3551
1434
                                            realm=realm, path=path))
3552
 
        self.assertEquals(expected_prompt, stderr.getvalue())
3553
 
        self.assertEquals('', stdout.getvalue())
3554
 
 
3555
 
    def _check_default_username_prompt(self, expected_prompt_format, scheme,
3556
 
                                       host=None, port=None, realm=None,
3557
 
                                       path=None):
3558
 
        if host is None:
3559
 
            host = 'bar.org'
3560
 
        username = 'jim'
3561
 
        expected_prompt = expected_prompt_format % {
3562
 
            'scheme': scheme, 'host': host, 'port': port,
3563
 
            'realm': realm}
3564
 
        stdout = tests.StringIOWrapper()
3565
 
        stderr = tests.StringIOWrapper()
3566
 
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
3567
 
                                            stdout=stdout, stderr=stderr)
3568
 
        # We use an empty conf so that the user is always prompted
3569
 
        conf = config.AuthenticationConfig()
3570
 
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
3571
 
                          realm=realm, path=path, ask=True))
3572
 
        self.assertEquals(expected_prompt, stderr.getvalue())
3573
 
        self.assertEquals('', stdout.getvalue())
3574
 
 
3575
 
    def test_username_defaults_prompts(self):
3576
 
        # HTTP prompts can't be tested here, see test_http.py
3577
 
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
3578
 
        self._check_default_username_prompt(
3579
 
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
3580
 
        self._check_default_username_prompt(
3581
 
            u'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
3582
 
 
3583
 
    def test_username_default_no_prompt(self):
3584
 
        conf = config.AuthenticationConfig()
3585
 
        self.assertEquals(None,
3586
 
            conf.get_user('ftp', 'example.com'))
3587
 
        self.assertEquals("explicitdefault",
3588
 
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
3589
 
 
3590
 
    def test_password_default_prompts(self):
3591
 
        # HTTP prompts can't be tested here, see test_http.py
3592
 
        self._check_default_password_prompt(
3593
 
            u'FTP %(user)s@%(host)s password: ', 'ftp')
3594
 
        self._check_default_password_prompt(
3595
 
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
3596
 
        self._check_default_password_prompt(
3597
 
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
 
1435
        self.assertEquals(stdout.getvalue(), expected_prompt)
 
1436
 
 
1437
    def test_default_prompts(self):
 
1438
        # HTTP prompts can't be tested here, see test_http.py
 
1439
        self._check_default_prompt('FTP %(user)s@%(host)s password: ', 'ftp')
 
1440
        self._check_default_prompt('FTP %(user)s@%(host)s:%(port)d password: ',
 
1441
                                   'ftp', port=10020)
 
1442
 
 
1443
        self._check_default_prompt('SSH %(user)s@%(host)s:%(port)d password: ',
 
1444
                                   'ssh', port=12345)
3598
1445
        # SMTP port handling is a bit special (it's handled if embedded in the
3599
1446
        # host too)
3600
1447
        # FIXME: should we: forbid that, extend it to other schemes, leave
3601
1448
        # things as they are that's fine thank you ?
3602
 
        self._check_default_password_prompt(
3603
 
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
3604
 
        self._check_default_password_prompt(
3605
 
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
3606
 
        self._check_default_password_prompt(
3607
 
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
 
1449
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
 
1450
                                   'smtp')
 
1451
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
 
1452
                                   'smtp', host='bar.org:10025')
 
1453
        self._check_default_prompt(
 
1454
            'SMTP %(user)s@%(host)s:%(port)d password: ',
 
1455
            'smtp', port=10025)
3608
1456
 
3609
1457
    def test_ssh_password_emits_warning(self):
3610
1458
        conf = config.AuthenticationConfig(_file=StringIO(
3617
1465
"""))
3618
1466
        entered_password = 'typed-by-hand'
3619
1467
        stdout = tests.StringIOWrapper()
3620
 
        stderr = tests.StringIOWrapper()
3621
1468
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
3622
 
                                            stdout=stdout, stderr=stderr)
 
1469
                                            stdout=stdout)
3623
1470
 
3624
1471
        # Since the password defined in the authentication config is ignored,
3625
1472
        # the user is prompted
3626
1473
        self.assertEquals(entered_password,
3627
1474
                          conf.get_password('ssh', 'bar.org', user='jim'))
3628
1475
        self.assertContainsRe(
3629
 
            self.get_log(),
 
1476
            self._get_log(keep_log_file=True),
3630
1477
            'password ignored in section \[ssh with password\]')
3631
1478
 
3632
1479
    def test_ssh_without_password_doesnt_emit_warning(self):
3639
1486
"""))
3640
1487
        entered_password = 'typed-by-hand'
3641
1488
        stdout = tests.StringIOWrapper()
3642
 
        stderr = tests.StringIOWrapper()
3643
1489
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
3644
 
                                            stdout=stdout,
3645
 
                                            stderr=stderr)
 
1490
                                            stdout=stdout)
3646
1491
 
3647
1492
        # Since the password defined in the authentication config is ignored,
3648
1493
        # the user is prompted
3651
1496
        # No warning shoud be emitted since there is no password. We are only
3652
1497
        # providing "user".
3653
1498
        self.assertNotContainsRe(
3654
 
            self.get_log(),
 
1499
            self._get_log(keep_log_file=True),
3655
1500
            'password ignored in section \[ssh with password\]')
3656
1501
 
3657
 
    def test_uses_fallback_stores(self):
3658
 
        self.overrideAttr(config, 'credential_store_registry',
3659
 
                          config.CredentialStoreRegistry())
3660
 
        store = StubCredentialStore()
3661
 
        store.add_credentials("http", "example.com", "joe", "secret")
3662
 
        config.credential_store_registry.register("stub", store, fallback=True)
3663
 
        conf = config.AuthenticationConfig(_file=StringIO())
3664
 
        creds = conf.get_credentials("http", "example.com")
3665
 
        self.assertEquals("joe", creds["user"])
3666
 
        self.assertEquals("secret", creds["password"])
3667
 
 
3668
 
 
3669
 
class StubCredentialStore(config.CredentialStore):
3670
 
 
3671
 
    def __init__(self):
3672
 
        self._username = {}
3673
 
        self._password = {}
3674
 
 
3675
 
    def add_credentials(self, scheme, host, user, password=None):
3676
 
        self._username[(scheme, host)] = user
3677
 
        self._password[(scheme, host)] = password
3678
 
 
3679
 
    def get_credentials(self, scheme, host, port=None, user=None,
3680
 
        path=None, realm=None):
3681
 
        key = (scheme, host)
3682
 
        if not key in self._username:
3683
 
            return None
3684
 
        return { "scheme": scheme, "host": host, "port": port,
3685
 
                "user": self._username[key], "password": self._password[key]}
3686
 
 
3687
 
 
3688
 
class CountingCredentialStore(config.CredentialStore):
3689
 
 
3690
 
    def __init__(self):
3691
 
        self._calls = 0
3692
 
 
3693
 
    def get_credentials(self, scheme, host, port=None, user=None,
3694
 
        path=None, realm=None):
3695
 
        self._calls += 1
3696
 
        return None
3697
 
 
3698
 
 
3699
 
class TestCredentialStoreRegistry(tests.TestCase):
3700
 
 
3701
 
    def _get_cs_registry(self):
3702
 
        return config.credential_store_registry
3703
 
 
3704
 
    def test_default_credential_store(self):
3705
 
        r = self._get_cs_registry()
3706
 
        default = r.get_credential_store(None)
3707
 
        self.assertIsInstance(default, config.PlainTextCredentialStore)
3708
 
 
3709
 
    def test_unknown_credential_store(self):
3710
 
        r = self._get_cs_registry()
3711
 
        # It's hard to imagine someone creating a credential store named
3712
 
        # 'unknown' so we use that as an never registered key.
3713
 
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
3714
 
 
3715
 
    def test_fallback_none_registered(self):
3716
 
        r = config.CredentialStoreRegistry()
3717
 
        self.assertEquals(None,
3718
 
                          r.get_fallback_credentials("http", "example.com"))
3719
 
 
3720
 
    def test_register(self):
3721
 
        r = config.CredentialStoreRegistry()
3722
 
        r.register("stub", StubCredentialStore(), fallback=False)
3723
 
        r.register("another", StubCredentialStore(), fallback=True)
3724
 
        self.assertEquals(["another", "stub"], r.keys())
3725
 
 
3726
 
    def test_register_lazy(self):
3727
 
        r = config.CredentialStoreRegistry()
3728
 
        r.register_lazy("stub", "bzrlib.tests.test_config",
3729
 
                        "StubCredentialStore", fallback=False)
3730
 
        self.assertEquals(["stub"], r.keys())
3731
 
        self.assertIsInstance(r.get_credential_store("stub"),
3732
 
                              StubCredentialStore)
3733
 
 
3734
 
    def test_is_fallback(self):
3735
 
        r = config.CredentialStoreRegistry()
3736
 
        r.register("stub1", None, fallback=False)
3737
 
        r.register("stub2", None, fallback=True)
3738
 
        self.assertEquals(False, r.is_fallback("stub1"))
3739
 
        self.assertEquals(True, r.is_fallback("stub2"))
3740
 
 
3741
 
    def test_no_fallback(self):
3742
 
        r = config.CredentialStoreRegistry()
3743
 
        store = CountingCredentialStore()
3744
 
        r.register("count", store, fallback=False)
3745
 
        self.assertEquals(None,
3746
 
                          r.get_fallback_credentials("http", "example.com"))
3747
 
        self.assertEquals(0, store._calls)
3748
 
 
3749
 
    def test_fallback_credentials(self):
3750
 
        r = config.CredentialStoreRegistry()
3751
 
        store = StubCredentialStore()
3752
 
        store.add_credentials("http", "example.com",
3753
 
                              "somebody", "geheim")
3754
 
        r.register("stub", store, fallback=True)
3755
 
        creds = r.get_fallback_credentials("http", "example.com")
3756
 
        self.assertEquals("somebody", creds["user"])
3757
 
        self.assertEquals("geheim", creds["password"])
3758
 
 
3759
 
    def test_fallback_first_wins(self):
3760
 
        r = config.CredentialStoreRegistry()
3761
 
        stub1 = StubCredentialStore()
3762
 
        stub1.add_credentials("http", "example.com",
3763
 
                              "somebody", "stub1")
3764
 
        r.register("stub1", stub1, fallback=True)
3765
 
        stub2 = StubCredentialStore()
3766
 
        stub2.add_credentials("http", "example.com",
3767
 
                              "somebody", "stub2")
3768
 
        r.register("stub2", stub1, fallback=True)
3769
 
        creds = r.get_fallback_credentials("http", "example.com")
3770
 
        self.assertEquals("somebody", creds["user"])
3771
 
        self.assertEquals("stub1", creds["password"])
3772
 
 
3773
 
 
3774
 
class TestPlainTextCredentialStore(tests.TestCase):
3775
 
 
3776
 
    def test_decode_password(self):
3777
 
        r = config.credential_store_registry
3778
 
        plain_text = r.get_credential_store()
3779
 
        decoded = plain_text.decode_password(dict(password='secret'))
3780
 
        self.assertEquals('secret', decoded)
3781
 
 
3782
1502
 
3783
1503
# FIXME: Once we have a way to declare authentication to all test servers, we
3784
1504
# can implement generic tests.
3790
1510
# test_user_prompted ?
3791
1511
class TestAuthenticationRing(tests.TestCaseWithTransport):
3792
1512
    pass
3793
 
 
3794
 
 
3795
 
class TestAutoUserId(tests.TestCase):
3796
 
    """Test inferring an automatic user name."""
3797
 
 
3798
 
    def test_auto_user_id(self):
3799
 
        """Automatic inference of user name.
3800
 
        
3801
 
        This is a bit hard to test in an isolated way, because it depends on
3802
 
        system functions that go direct to /etc or perhaps somewhere else.
3803
 
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
3804
 
        to be able to choose a user name with no configuration.
3805
 
        """
3806
 
        if sys.platform == 'win32':
3807
 
            raise tests.TestSkipped(
3808
 
                "User name inference not implemented on win32")
3809
 
        realname, address = config._auto_user_id()
3810
 
        if os.path.exists('/etc/mailname'):
3811
 
            self.assertIsNot(None, realname)
3812
 
            self.assertIsNot(None, address)
3813
 
        else:
3814
 
            self.assertEquals((None, None), (realname, address))
3815