~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

MergeĀ lp:~gz/bzr/path_from_environ_832028

Show diffs side-by-side

added added

removed removed

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