~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Jelmer Vernooij
  • Date: 2012-01-24 13:14:06 UTC
  • mto: (6445.4.5 nested-trees-spec)
  • mto: This revision was merged to the branch mainline in revision 6518.
  • Revision ID: jelmer@samba.org-20120124131406-wedftkorbpv37bm0
Import nested tree doc from devnotes.

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_branch_only_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.BranchOnlyStack(b)
 
155
config.test_stack_builder_registry.register('branch_only',
 
156
                                            build_branch_only_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()
343
531
 
344
532
    def test_post_commit_default(self):
345
533
        my_config = config.Config()
346
 
        self.assertEqual(None, my_config.post_commit())
 
534
        self.assertEqual(None, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
535
                                                    my_config.post_commit))
 
536
 
347
537
 
348
538
    def test_log_format_default(self):
349
539
        my_config = config.Config()
350
 
        self.assertEqual('long', my_config.log_format())
 
540
        self.assertEqual('long',
 
541
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
542
                                              my_config.log_format))
 
543
 
 
544
    def test_acceptable_keys_default(self):
 
545
        my_config = config.Config()
 
546
        self.assertEqual(None, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
547
            my_config.acceptable_keys))
 
548
 
 
549
    def test_validate_signatures_in_log_default(self):
 
550
        my_config = config.Config()
 
551
        self.assertEqual(False, my_config.validate_signatures_in_log())
351
552
 
352
553
    def test_get_change_editor(self):
353
554
        my_config = InstrumentedConfig()
362
563
 
363
564
    def setUp(self):
364
565
        super(TestConfigPath, self).setUp()
365
 
        os.environ['HOME'] = '/home/bogus'
366
 
        os.environ['XDG_CACHE_DIR'] = ''
 
566
        self.overrideEnv('HOME', '/home/bogus')
 
567
        self.overrideEnv('XDG_CACHE_DIR', '')
367
568
        if sys.platform == 'win32':
368
 
            os.environ['BZR_HOME'] = \
369
 
                r'C:\Documents and Settings\bogus\Application Data'
 
569
            self.overrideEnv(
 
570
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
370
571
            self.bzr_home = \
371
572
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
372
573
        else:
392
593
            '/home/bogus/.cache')
393
594
 
394
595
 
 
596
class TestXDGConfigDir(tests.TestCaseInTempDir):
 
597
    # must be in temp dir because config tests for the existence of the bazaar
 
598
    # subdirectory of $XDG_CONFIG_HOME
 
599
 
 
600
    def setUp(self):
 
601
        if sys.platform in ('darwin', 'win32'):
 
602
            raise tests.TestNotApplicable(
 
603
                'XDG config dir not used on this platform')
 
604
        super(TestXDGConfigDir, self).setUp()
 
605
        self.overrideEnv('HOME', self.test_home_dir)
 
606
        # BZR_HOME overrides everything we want to test so unset it.
 
607
        self.overrideEnv('BZR_HOME', None)
 
608
 
 
609
    def test_xdg_config_dir_exists(self):
 
610
        """When ~/.config/bazaar exists, use it as the config dir."""
 
611
        newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
 
612
        os.makedirs(newdir)
 
613
        self.assertEqual(config.config_dir(), newdir)
 
614
 
 
615
    def test_xdg_config_home(self):
 
616
        """When XDG_CONFIG_HOME is set, use it."""
 
617
        xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
 
618
        self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
 
619
        newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
 
620
        os.makedirs(newdir)
 
621
        self.assertEqual(config.config_dir(), newdir)
 
622
 
 
623
 
395
624
class TestIniConfig(tests.TestCaseInTempDir):
396
625
 
397
626
    def make_config_parser(self, s):
411
640
    def test_cached(self):
412
641
        my_config = config.IniBasedConfig.from_string(sample_config_text)
413
642
        parser = my_config._get_parser()
414
 
        self.failUnless(my_config._get_parser() is parser)
 
643
        self.assertTrue(my_config._get_parser() is parser)
415
644
 
416
645
    def _dummy_chown(self, path, uid, gid):
417
646
        self.path, self.uid, self.gid = path, uid, gid
442
671
            ' Use IniBasedConfig(_content=xxx) instead.'],
443
672
            conf._get_parser, file=config_file)
444
673
 
 
674
 
445
675
class TestIniConfigSaving(tests.TestCaseInTempDir):
446
676
 
447
677
    def test_cant_save_without_a_file_name(self):
455
685
        self.assertFileEqual(content, 'test.conf')
456
686
 
457
687
 
 
688
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
 
689
    """What is the default value of expand for config options.
 
690
 
 
691
    This is an opt-in beta feature used to evaluate whether or not option
 
692
    references can appear in dangerous place raising exceptions, disapearing
 
693
    (and as such corrupting data) or if it's safe to activate the option by
 
694
    default.
 
695
 
 
696
    Note that these tests relies on config._expand_default_value being already
 
697
    overwritten in the parent class setUp.
 
698
    """
 
699
 
 
700
    def setUp(self):
 
701
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
 
702
        self.config = None
 
703
        self.warnings = []
 
704
        def warning(*args):
 
705
            self.warnings.append(args[0] % args[1:])
 
706
        self.overrideAttr(trace, 'warning', warning)
 
707
 
 
708
    def get_config(self, expand):
 
709
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
 
710
                                            save=True)
 
711
        return c
 
712
 
 
713
    def assertExpandIs(self, expected):
 
714
        actual = config._get_expand_default_value()
 
715
        #self.config.get_user_option_as_bool('bzr.config.expand')
 
716
        self.assertEquals(expected, actual)
 
717
 
 
718
    def test_default_is_None(self):
 
719
        self.assertEquals(None, config._expand_default_value)
 
720
 
 
721
    def test_default_is_False_even_if_None(self):
 
722
        self.config = self.get_config(None)
 
723
        self.assertExpandIs(False)
 
724
 
 
725
    def test_default_is_False_even_if_invalid(self):
 
726
        self.config = self.get_config('<your choice>')
 
727
        self.assertExpandIs(False)
 
728
        # ...
 
729
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
 
730
        # Wait, you've been warned !
 
731
        self.assertLength(1, self.warnings)
 
732
        self.assertEquals(
 
733
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
 
734
            self.warnings[0])
 
735
 
 
736
    def test_default_is_True(self):
 
737
        self.config = self.get_config(True)
 
738
        self.assertExpandIs(True)
 
739
 
 
740
    def test_default_is_False(self):
 
741
        self.config = self.get_config(False)
 
742
        self.assertExpandIs(False)
 
743
 
 
744
 
 
745
class TestIniConfigOptionExpansion(tests.TestCase):
 
746
    """Test option expansion from the IniConfig level.
 
747
 
 
748
    What we really want here is to test the Config level, but the class being
 
749
    abstract as far as storing values is concerned, this can't be done
 
750
    properly (yet).
 
751
    """
 
752
    # FIXME: This should be rewritten when all configs share a storage
 
753
    # implementation -- vila 2011-02-18
 
754
 
 
755
    def get_config(self, string=None):
 
756
        if string is None:
 
757
            string = ''
 
758
        c = config.IniBasedConfig.from_string(string)
 
759
        return c
 
760
 
 
761
    def assertExpansion(self, expected, conf, string, env=None):
 
762
        self.assertEquals(expected, conf.expand_options(string, env))
 
763
 
 
764
    def test_no_expansion(self):
 
765
        c = self.get_config('')
 
766
        self.assertExpansion('foo', c, 'foo')
 
767
 
 
768
    def test_env_adding_options(self):
 
769
        c = self.get_config('')
 
770
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
771
 
 
772
    def test_env_overriding_options(self):
 
773
        c = self.get_config('foo=baz')
 
774
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
 
775
 
 
776
    def test_simple_ref(self):
 
777
        c = self.get_config('foo=xxx')
 
778
        self.assertExpansion('xxx', c, '{foo}')
 
779
 
 
780
    def test_unknown_ref(self):
 
781
        c = self.get_config('')
 
782
        self.assertRaises(errors.ExpandingUnknownOption,
 
783
                          c.expand_options, '{foo}')
 
784
 
 
785
    def test_indirect_ref(self):
 
786
        c = self.get_config('''
 
787
foo=xxx
 
788
bar={foo}
 
789
''')
 
790
        self.assertExpansion('xxx', c, '{bar}')
 
791
 
 
792
    def test_embedded_ref(self):
 
793
        c = self.get_config('''
 
794
foo=xxx
 
795
bar=foo
 
796
''')
 
797
        self.assertExpansion('xxx', c, '{{bar}}')
 
798
 
 
799
    def test_simple_loop(self):
 
800
        c = self.get_config('foo={foo}')
 
801
        self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
 
802
 
 
803
    def test_indirect_loop(self):
 
804
        c = self.get_config('''
 
805
foo={bar}
 
806
bar={baz}
 
807
baz={foo}''')
 
808
        e = self.assertRaises(errors.OptionExpansionLoop,
 
809
                              c.expand_options, '{foo}')
 
810
        self.assertEquals('foo->bar->baz', e.refs)
 
811
        self.assertEquals('{foo}', e.string)
 
812
 
 
813
    def test_list(self):
 
814
        conf = self.get_config('''
 
815
foo=start
 
816
bar=middle
 
817
baz=end
 
818
list={foo},{bar},{baz}
 
819
''')
 
820
        self.assertEquals(['start', 'middle', 'end'],
 
821
                           conf.get_user_option('list', expand=True))
 
822
 
 
823
    def test_cascading_list(self):
 
824
        conf = self.get_config('''
 
825
foo=start,{bar}
 
826
bar=middle,{baz}
 
827
baz=end
 
828
list={foo}
 
829
''')
 
830
        self.assertEquals(['start', 'middle', 'end'],
 
831
                           conf.get_user_option('list', expand=True))
 
832
 
 
833
    def test_pathological_hidden_list(self):
 
834
        conf = self.get_config('''
 
835
foo=bin
 
836
bar=go
 
837
start={foo
 
838
middle=},{
 
839
end=bar}
 
840
hidden={start}{middle}{end}
 
841
''')
 
842
        # Nope, it's either a string or a list, and the list wins as soon as a
 
843
        # ',' appears, so the string concatenation never occur.
 
844
        self.assertEquals(['{foo', '}', '{', 'bar}'],
 
845
                          conf.get_user_option('hidden', expand=True))
 
846
 
 
847
 
 
848
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
 
849
 
 
850
    def get_config(self, location, string=None):
 
851
        if string is None:
 
852
            string = ''
 
853
        # Since we don't save the config we won't strictly require to inherit
 
854
        # from TestCaseInTempDir, but an error occurs so quickly...
 
855
        c = config.LocationConfig.from_string(string, location)
 
856
        return c
 
857
 
 
858
    def test_dont_cross_unrelated_section(self):
 
859
        c = self.get_config('/another/branch/path','''
 
860
[/one/branch/path]
 
861
foo = hello
 
862
bar = {foo}/2
 
863
 
 
864
[/another/branch/path]
 
865
bar = {foo}/2
 
866
''')
 
867
        self.assertRaises(errors.ExpandingUnknownOption,
 
868
                          c.get_user_option, 'bar', expand=True)
 
869
 
 
870
    def test_cross_related_sections(self):
 
871
        c = self.get_config('/project/branch/path','''
 
872
[/project]
 
873
foo = qu
 
874
 
 
875
[/project/branch/path]
 
876
bar = {foo}ux
 
877
''')
 
878
        self.assertEquals('quux', c.get_user_option('bar', expand=True))
 
879
 
 
880
 
458
881
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
459
882
 
460
883
    def test_cannot_reload_without_name(self):
477
900
 
478
901
class TestLockableConfig(tests.TestCaseInTempDir):
479
902
 
 
903
    scenarios = lockable_config_scenarios()
 
904
 
480
905
    # Set by load_tests
481
906
    config_class = None
482
907
    config_args = None
538
963
        def c1_write_config_file():
539
964
            before_writing.set()
540
965
            c1_orig()
541
 
            # The lock is held we wait for the main thread to decide when to
 
966
            # The lock is held. We wait for the main thread to decide when to
542
967
            # continue
543
968
            after_writing.wait()
544
969
        c1._write_config_file = c1_write_config_file
571
996
       c1_orig = c1._write_config_file
572
997
       def c1_write_config_file():
573
998
           ready_to_write.set()
574
 
           # The lock is held we wait for the main thread to decide when to
 
999
           # The lock is held. We wait for the main thread to decide when to
575
1000
           # continue
576
1001
           do_writing.wait()
577
1002
           c1_orig()
636
1061
        # automatically cast to list
637
1062
        self.assertEqual(['x'], get_list('one_item'))
638
1063
 
 
1064
    def test_get_user_option_as_int_from_SI(self):
 
1065
        conf, parser = self.make_config_parser("""
 
1066
plain = 100
 
1067
si_k = 5k,
 
1068
si_kb = 5kb,
 
1069
si_m = 5M,
 
1070
si_mb = 5MB,
 
1071
si_g = 5g,
 
1072
si_gb = 5gB,
 
1073
""")
 
1074
        def get_si(s, default=None):
 
1075
            return self.applyDeprecated(
 
1076
                deprecated_in((2, 5, 0)),
 
1077
                conf.get_user_option_as_int_from_SI, s, default)
 
1078
        self.assertEqual(100, get_si('plain'))
 
1079
        self.assertEqual(5000, get_si('si_k'))
 
1080
        self.assertEqual(5000, get_si('si_kb'))
 
1081
        self.assertEqual(5000000, get_si('si_m'))
 
1082
        self.assertEqual(5000000, get_si('si_mb'))
 
1083
        self.assertEqual(5000000000, get_si('si_g'))
 
1084
        self.assertEqual(5000000000, get_si('si_gb'))
 
1085
        self.assertEqual(None, get_si('non-exist'))
 
1086
        self.assertEqual(42, get_si('non-exist-with-default',  42))
 
1087
 
639
1088
 
640
1089
class TestSupressWarning(TestIniConfig):
641
1090
 
668
1117
            parser = my_config._get_parser()
669
1118
        finally:
670
1119
            config.ConfigObj = oldparserclass
671
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
1120
        self.assertIsInstance(parser, InstrumentedConfigObj)
672
1121
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
673
1122
                                          'utf-8')])
674
1123
 
685
1134
        my_config = config.BranchConfig(branch)
686
1135
        location_config = my_config._get_location_config()
687
1136
        self.assertEqual(branch.base, location_config.location)
688
 
        self.failUnless(location_config is my_config._get_location_config())
 
1137
        self.assertIs(location_config, my_config._get_location_config())
689
1138
 
690
1139
    def test_get_config(self):
691
1140
        """The Branch.get_config method works properly"""
778
1227
        assertWarning(None)
779
1228
 
780
1229
 
781
 
class TestGlobalConfigItems(tests.TestCase):
 
1230
class TestGlobalConfigItems(tests.TestCaseInTempDir):
782
1231
 
783
1232
    def test_user_id(self):
784
1233
        my_config = config.GlobalConfig.from_string(sample_config_text)
791
1240
 
792
1241
    def test_configured_editor(self):
793
1242
        my_config = config.GlobalConfig.from_string(sample_config_text)
794
 
        self.assertEqual("vim", my_config.get_editor())
 
1243
        editor = self.applyDeprecated(
 
1244
            deprecated_in((2, 4, 0)), my_config.get_editor)
 
1245
        self.assertEqual('vim', editor)
795
1246
 
796
1247
    def test_signatures_always(self):
797
1248
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
798
1249
        self.assertEqual(config.CHECK_NEVER,
799
 
                         my_config.signature_checking())
 
1250
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1251
                             my_config.signature_checking))
800
1252
        self.assertEqual(config.SIGN_ALWAYS,
801
 
                         my_config.signing_policy())
802
 
        self.assertEqual(True, my_config.signature_needed())
 
1253
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1254
                             my_config.signing_policy))
 
1255
        self.assertEqual(True,
 
1256
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1257
                my_config.signature_needed))
803
1258
 
804
1259
    def test_signatures_if_possible(self):
805
1260
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
806
1261
        self.assertEqual(config.CHECK_NEVER,
807
 
                         my_config.signature_checking())
 
1262
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1263
                             my_config.signature_checking))
808
1264
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
809
 
                         my_config.signing_policy())
810
 
        self.assertEqual(False, my_config.signature_needed())
 
1265
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1266
                             my_config.signing_policy))
 
1267
        self.assertEqual(False, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1268
            my_config.signature_needed))
811
1269
 
812
1270
    def test_signatures_ignore(self):
813
1271
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
814
1272
        self.assertEqual(config.CHECK_ALWAYS,
815
 
                         my_config.signature_checking())
 
1273
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1274
                             my_config.signature_checking))
816
1275
        self.assertEqual(config.SIGN_NEVER,
817
 
                         my_config.signing_policy())
818
 
        self.assertEqual(False, my_config.signature_needed())
 
1276
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1277
                             my_config.signing_policy))
 
1278
        self.assertEqual(False, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1279
            my_config.signature_needed))
819
1280
 
820
1281
    def _get_sample_config(self):
821
1282
        my_config = config.GlobalConfig.from_string(sample_config_text)
823
1284
 
824
1285
    def test_gpg_signing_command(self):
825
1286
        my_config = self._get_sample_config()
826
 
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
827
 
        self.assertEqual(False, my_config.signature_needed())
 
1287
        self.assertEqual("gnome-gpg",
 
1288
            self.applyDeprecated(
 
1289
                deprecated_in((2, 5, 0)), my_config.gpg_signing_command))
 
1290
        self.assertEqual(False, self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1291
            my_config.signature_needed))
 
1292
 
 
1293
    def test_gpg_signing_key(self):
 
1294
        my_config = self._get_sample_config()
 
1295
        self.assertEqual("DD4D5088",
 
1296
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1297
                my_config.gpg_signing_key))
828
1298
 
829
1299
    def _get_empty_config(self):
830
1300
        my_config = config.GlobalConfig()
832
1302
 
833
1303
    def test_gpg_signing_command_unset(self):
834
1304
        my_config = self._get_empty_config()
835
 
        self.assertEqual("gpg", my_config.gpg_signing_command())
 
1305
        self.assertEqual("gpg",
 
1306
            self.applyDeprecated(
 
1307
                deprecated_in((2, 5, 0)), my_config.gpg_signing_command))
836
1308
 
837
1309
    def test_get_user_option_default(self):
838
1310
        my_config = self._get_empty_config()
845
1317
 
846
1318
    def test_post_commit_default(self):
847
1319
        my_config = self._get_sample_config()
848
 
        self.assertEqual(None, my_config.post_commit())
 
1320
        self.assertEqual(None,
 
1321
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1322
                                              my_config.post_commit))
849
1323
 
850
1324
    def test_configured_logformat(self):
851
1325
        my_config = self._get_sample_config()
852
 
        self.assertEqual("short", my_config.log_format())
 
1326
        self.assertEqual("short",
 
1327
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1328
                                              my_config.log_format))
 
1329
 
 
1330
    def test_configured_acceptable_keys(self):
 
1331
        my_config = self._get_sample_config()
 
1332
        self.assertEqual("amy",
 
1333
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1334
                my_config.acceptable_keys))
 
1335
 
 
1336
    def test_configured_validate_signatures_in_log(self):
 
1337
        my_config = self._get_sample_config()
 
1338
        self.assertEqual(True, my_config.validate_signatures_in_log())
853
1339
 
854
1340
    def test_get_alias(self):
855
1341
        my_config = self._get_sample_config()
883
1369
        change_editor = my_config.get_change_editor('old', 'new')
884
1370
        self.assertIs(None, change_editor)
885
1371
 
 
1372
    def test_get_merge_tools(self):
 
1373
        conf = self._get_sample_config()
 
1374
        tools = conf.get_merge_tools()
 
1375
        self.log(repr(tools))
 
1376
        self.assertEqual(
 
1377
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
 
1378
            u'sometool' : u'sometool {base} {this} {other} -o {result}',
 
1379
            u'newtool' : u'"newtool with spaces" {this_temp}'},
 
1380
            tools)
 
1381
 
 
1382
    def test_get_merge_tools_empty(self):
 
1383
        conf = self._get_empty_config()
 
1384
        tools = conf.get_merge_tools()
 
1385
        self.assertEqual({}, tools)
 
1386
 
 
1387
    def test_find_merge_tool(self):
 
1388
        conf = self._get_sample_config()
 
1389
        cmdline = conf.find_merge_tool('sometool')
 
1390
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
 
1391
 
 
1392
    def test_find_merge_tool_not_found(self):
 
1393
        conf = self._get_sample_config()
 
1394
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
 
1395
        self.assertIs(cmdline, None)
 
1396
 
 
1397
    def test_find_merge_tool_known(self):
 
1398
        conf = self._get_empty_config()
 
1399
        cmdline = conf.find_merge_tool('kdiff3')
 
1400
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
 
1401
 
 
1402
    def test_find_merge_tool_override_known(self):
 
1403
        conf = self._get_empty_config()
 
1404
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
 
1405
        cmdline = conf.find_merge_tool('kdiff3')
 
1406
        self.assertEqual('kdiff3 blah', cmdline)
 
1407
 
886
1408
 
887
1409
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
888
1410
 
906
1428
        self.assertIs(None, new_config.get_alias('commit'))
907
1429
 
908
1430
 
909
 
class TestLocationConfig(tests.TestCaseInTempDir):
 
1431
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
910
1432
 
911
1433
    def test_constructs(self):
912
1434
        my_config = config.LocationConfig('http://example.com')
924
1446
            parser = my_config._get_parser()
925
1447
        finally:
926
1448
            config.ConfigObj = oldparserclass
927
 
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
1449
        self.assertIsInstance(parser, InstrumentedConfigObj)
928
1450
        self.assertEqual(parser._calls,
929
1451
                         [('__init__', config.locations_config_filename(),
930
1452
                           'utf-8')])
932
1454
    def test_get_global_config(self):
933
1455
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
934
1456
        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())
 
1457
        self.assertIsInstance(global_config, config.GlobalConfig)
 
1458
        self.assertIs(global_config, my_config._get_global_config())
 
1459
 
 
1460
    def assertLocationMatching(self, expected):
 
1461
        self.assertEqual(expected,
 
1462
                         list(self.my_location_config._get_matching_sections()))
937
1463
 
938
1464
    def test__get_matching_sections_no_match(self):
939
1465
        self.get_branch_config('/')
940
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1466
        self.assertLocationMatching([])
941
1467
 
942
1468
    def test__get_matching_sections_exact(self):
943
1469
        self.get_branch_config('http://www.example.com')
944
 
        self.assertEqual([('http://www.example.com', '')],
945
 
                         self.my_location_config._get_matching_sections())
 
1470
        self.assertLocationMatching([('http://www.example.com', '')])
946
1471
 
947
1472
    def test__get_matching_sections_suffix_does_not(self):
948
1473
        self.get_branch_config('http://www.example.com-com')
949
 
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
1474
        self.assertLocationMatching([])
950
1475
 
951
1476
    def test__get_matching_sections_subdir_recursive(self):
952
1477
        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())
 
1478
        self.assertLocationMatching([('http://www.example.com', 'com')])
955
1479
 
956
1480
    def test__get_matching_sections_ignoreparent(self):
957
1481
        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())
 
1482
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1483
                                      '')])
960
1484
 
961
1485
    def test__get_matching_sections_ignoreparent_subdir(self):
962
1486
        self.get_branch_config(
963
1487
            'http://www.example.com/ignoreparent/childbranch')
964
 
        self.assertEqual([('http://www.example.com/ignoreparent',
965
 
                           'childbranch')],
966
 
                         self.my_location_config._get_matching_sections())
 
1488
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
 
1489
                                      'childbranch')])
967
1490
 
968
1491
    def test__get_matching_sections_subdir_trailing_slash(self):
969
1492
        self.get_branch_config('/b')
970
 
        self.assertEqual([('/b/', '')],
971
 
                         self.my_location_config._get_matching_sections())
 
1493
        self.assertLocationMatching([('/b/', '')])
972
1494
 
973
1495
    def test__get_matching_sections_subdir_child(self):
974
1496
        self.get_branch_config('/a/foo')
975
 
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
976
 
                         self.my_location_config._get_matching_sections())
 
1497
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
977
1498
 
978
1499
    def test__get_matching_sections_subdir_child_child(self):
979
1500
        self.get_branch_config('/a/foo/bar')
980
 
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
981
 
                         self.my_location_config._get_matching_sections())
 
1501
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
982
1502
 
983
1503
    def test__get_matching_sections_trailing_slash_with_children(self):
984
1504
        self.get_branch_config('/a/')
985
 
        self.assertEqual([('/a/', '')],
986
 
                         self.my_location_config._get_matching_sections())
 
1505
        self.assertLocationMatching([('/a/', '')])
987
1506
 
988
1507
    def test__get_matching_sections_explicit_over_glob(self):
989
1508
        # XXX: 2006-09-08 jamesh
991
1510
        # was a config section for '/a/?', it would get precedence
992
1511
        # over '/a/c'.
993
1512
        self.get_branch_config('/a/c')
994
 
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
995
 
                         self.my_location_config._get_matching_sections())
 
1513
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
996
1514
 
997
1515
    def test__get_option_policy_normal(self):
998
1516
        self.get_branch_config('http://www.example.com')
1020
1538
            'http://www.example.com', 'appendpath_option'),
1021
1539
            config.POLICY_APPENDPATH)
1022
1540
 
 
1541
    def test__get_options_with_policy(self):
 
1542
        self.get_branch_config('/dir/subdir',
 
1543
                               location_config="""\
 
1544
[/dir]
 
1545
other_url = /other-dir
 
1546
other_url:policy = appendpath
 
1547
[/dir/subdir]
 
1548
other_url = /other-subdir
 
1549
""")
 
1550
        self.assertOptions(
 
1551
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
 
1552
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
 
1553
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
 
1554
            self.my_location_config)
 
1555
 
1023
1556
    def test_location_without_username(self):
1024
1557
        self.get_branch_config('http://www.example.com/ignoreparent')
1025
1558
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1040
1573
        self.get_branch_config('http://www.example.com',
1041
1574
                                 global_config=sample_ignore_signatures)
1042
1575
        self.assertEqual(config.CHECK_ALWAYS,
1043
 
                         self.my_config.signature_checking())
 
1576
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1577
                             self.my_config.signature_checking))
1044
1578
        self.assertEqual(config.SIGN_NEVER,
1045
 
                         self.my_config.signing_policy())
 
1579
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1580
                             self.my_config.signing_policy))
1046
1581
 
1047
1582
    def test_signatures_never(self):
1048
1583
        self.get_branch_config('/a/c')
1049
1584
        self.assertEqual(config.CHECK_NEVER,
1050
 
                         self.my_config.signature_checking())
 
1585
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1586
                             self.my_config.signature_checking))
1051
1587
 
1052
1588
    def test_signatures_when_available(self):
1053
1589
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
1054
1590
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1055
 
                         self.my_config.signature_checking())
 
1591
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1592
                             self.my_config.signature_checking))
1056
1593
 
1057
1594
    def test_signatures_always(self):
1058
1595
        self.get_branch_config('/b')
1059
1596
        self.assertEqual(config.CHECK_ALWAYS,
1060
 
                         self.my_config.signature_checking())
 
1597
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1598
                         self.my_config.signature_checking))
1061
1599
 
1062
1600
    def test_gpg_signing_command(self):
1063
1601
        self.get_branch_config('/b')
1064
 
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
 
1602
        self.assertEqual("gnome-gpg",
 
1603
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1604
                self.my_config.gpg_signing_command))
1065
1605
 
1066
1606
    def test_gpg_signing_command_missing(self):
1067
1607
        self.get_branch_config('/a')
1068
 
        self.assertEqual("false", self.my_config.gpg_signing_command())
 
1608
        self.assertEqual("false",
 
1609
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1610
                self.my_config.gpg_signing_command))
 
1611
 
 
1612
    def test_gpg_signing_key(self):
 
1613
        self.get_branch_config('/b')
 
1614
        self.assertEqual("DD4D5088", self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1615
            self.my_config.gpg_signing_key))
 
1616
 
 
1617
    def test_gpg_signing_key_default(self):
 
1618
        self.get_branch_config('/a')
 
1619
        self.assertEqual("erik@bagfors.nu",
 
1620
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1621
                self.my_config.gpg_signing_key))
1069
1622
 
1070
1623
    def test_get_user_option_global(self):
1071
1624
        self.get_branch_config('/a')
1159
1712
    def test_post_commit_default(self):
1160
1713
        self.get_branch_config('/a/c')
1161
1714
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1162
 
                         self.my_config.post_commit())
 
1715
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1716
                                              self.my_config.post_commit))
1163
1717
 
1164
 
    def get_branch_config(self, location, global_config=None):
 
1718
    def get_branch_config(self, location, global_config=None,
 
1719
                          location_config=None):
1165
1720
        my_branch = FakeBranch(location)
1166
1721
        if global_config is None:
1167
1722
            global_config = sample_config_text
 
1723
        if location_config is None:
 
1724
            location_config = sample_branches_text
1168
1725
 
1169
1726
        my_global_config = config.GlobalConfig.from_string(global_config,
1170
1727
                                                           save=True)
1171
1728
        my_location_config = config.LocationConfig.from_string(
1172
 
            sample_branches_text, my_branch.base, save=True)
 
1729
            location_config, my_branch.base, save=True)
1173
1730
        my_config = config.BranchConfig(my_branch)
1174
1731
        self.my_config = my_config
1175
1732
        self.my_location_config = my_config._get_location_config()
1220
1777
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1221
1778
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1222
1779
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1223
 
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
1780
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1224
1781
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1225
1782
 
1226
1783
 
1252
1809
        return my_config
1253
1810
 
1254
1811
    def test_user_id(self):
1255
 
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
 
1812
        branch = FakeBranch()
1256
1813
        my_config = config.BranchConfig(branch)
1257
 
        self.assertEqual("Robert Collins <robertc@example.net>",
1258
 
                         my_config.username())
 
1814
        self.assertIsNot(None, my_config.username())
1259
1815
        my_config.branch.control_files.files['email'] = "John"
1260
1816
        my_config.set_user_option('email',
1261
1817
                                  "Robert Collins <robertc@example.org>")
1262
 
        self.assertEqual("John", my_config.username())
1263
 
        del my_config.branch.control_files.files['email']
1264
1818
        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())
 
1819
                        my_config.username())
1273
1820
 
1274
1821
    def test_BZR_EMAIL_OVERRIDES(self):
1275
 
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
 
1822
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1276
1823
        branch = FakeBranch()
1277
1824
        my_config = config.BranchConfig(branch)
1278
1825
        self.assertEqual("Robert Collins <robertc@example.org>",
1281
1828
    def test_signatures_forced(self):
1282
1829
        my_config = self.get_branch_config(
1283
1830
            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())
 
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))
1287
1839
 
1288
1840
    def test_signatures_forced_branch(self):
1289
1841
        my_config = self.get_branch_config(
1290
1842
            global_config=sample_ignore_signatures,
1291
1843
            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())
 
1844
        self.assertEqual(config.CHECK_NEVER,
 
1845
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1846
                my_config.signature_checking))
 
1847
        self.assertEqual(config.SIGN_ALWAYS,
 
1848
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1849
                my_config.signing_policy))
 
1850
        self.assertTrue(self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1851
            my_config.signature_needed))
1295
1852
 
1296
1853
    def test_gpg_signing_command(self):
1297
1854
        my_config = self.get_branch_config(
1298
1855
            global_config=sample_config_text,
1299
1856
            # branch data cannot set gpg_signing_command
1300
1857
            branch_data_config="gpg_signing_command=pgp")
1301
 
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
 
1858
        self.assertEqual('gnome-gpg',
 
1859
            self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1860
                my_config.gpg_signing_command))
1302
1861
 
1303
1862
    def test_get_user_option_global(self):
1304
1863
        my_config = self.get_branch_config(global_config=sample_config_text)
1311
1870
                                      location_config=sample_branches_text)
1312
1871
        self.assertEqual(my_config.branch.base, '/a/c')
1313
1872
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1314
 
                         my_config.post_commit())
 
1873
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1874
                                              my_config.post_commit))
1315
1875
        my_config.set_user_option('post_commit', 'rmtree_root')
1316
1876
        # post-commit is ignored when present in branch data
1317
1877
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1318
 
                         my_config.post_commit())
 
1878
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1879
                                              my_config.post_commit))
1319
1880
        my_config.set_user_option('post_commit', 'rmtree_root',
1320
1881
                                  store=config.STORE_LOCATION)
1321
 
        self.assertEqual('rmtree_root', my_config.post_commit())
 
1882
        self.assertEqual('rmtree_root',
 
1883
                         self.applyDeprecated(deprecated_in((2, 5, 0)),
 
1884
                                              my_config.post_commit))
1322
1885
 
1323
1886
    def test_config_precedence(self):
1324
1887
        # FIXME: eager test, luckily no persitent config file makes it fail
1433
1996
 
1434
1997
class TestTransportConfig(tests.TestCaseWithTransport):
1435
1998
 
 
1999
    def test_load_utf8(self):
 
2000
        """Ensure we can load an utf8-encoded file."""
 
2001
        t = self.get_transport()
 
2002
        unicode_user = u'b\N{Euro Sign}ar'
 
2003
        unicode_content = u'user=%s' % (unicode_user,)
 
2004
        utf8_content = unicode_content.encode('utf8')
 
2005
        # Store the raw content in the config file
 
2006
        t.put_bytes('foo.conf', utf8_content)
 
2007
        conf = config.TransportConfig(t, 'foo.conf')
 
2008
        self.assertEquals(unicode_user, conf.get_option('user'))
 
2009
 
 
2010
    def test_load_non_ascii(self):
 
2011
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
 
2012
        t = self.get_transport()
 
2013
        t.put_bytes('foo.conf', 'user=foo\n#\xff\n')
 
2014
        conf = config.TransportConfig(t, 'foo.conf')
 
2015
        self.assertRaises(errors.ConfigContentError, conf._get_configobj)
 
2016
 
 
2017
    def test_load_erroneous_content(self):
 
2018
        """Ensure we display a proper error on content that can't be parsed."""
 
2019
        t = self.get_transport()
 
2020
        t.put_bytes('foo.conf', '[open_section\n')
 
2021
        conf = config.TransportConfig(t, 'foo.conf')
 
2022
        self.assertRaises(errors.ParseConfigError, conf._get_configobj)
 
2023
 
 
2024
    def test_load_permission_denied(self):
 
2025
        """Ensure we get an empty config file if the file is inaccessible."""
 
2026
        warnings = []
 
2027
        def warning(*args):
 
2028
            warnings.append(args[0] % args[1:])
 
2029
        self.overrideAttr(trace, 'warning', warning)
 
2030
 
 
2031
        class DenyingTransport(object):
 
2032
 
 
2033
            def __init__(self, base):
 
2034
                self.base = base
 
2035
 
 
2036
            def get_bytes(self, relpath):
 
2037
                raise errors.PermissionDenied(relpath, "")
 
2038
 
 
2039
        cfg = config.TransportConfig(
 
2040
            DenyingTransport("nonexisting://"), 'control.conf')
 
2041
        self.assertIs(None, cfg.get_option('non-existant', 'SECTION'))
 
2042
        self.assertEquals(
 
2043
            warnings,
 
2044
            [u'Permission denied while trying to open configuration file '
 
2045
             u'nonexisting:///control.conf.'])
 
2046
 
1436
2047
    def test_get_value(self):
1437
2048
        """Test that retreiving a value from a section is possible"""
1438
 
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
 
2049
        bzrdir_config = config.TransportConfig(self.get_transport('.'),
1439
2050
                                               'control.conf')
1440
2051
        bzrdir_config.set_option('value', 'key', 'SECTION')
1441
2052
        bzrdir_config.set_option('value2', 'key2')
1471
2082
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1472
2083
 
1473
2084
 
 
2085
class TestOldConfigHooks(tests.TestCaseWithTransport):
 
2086
 
 
2087
    def setUp(self):
 
2088
        super(TestOldConfigHooks, self).setUp()
 
2089
        create_configs_with_file_option(self)
 
2090
 
 
2091
    def assertGetHook(self, conf, name, value):
 
2092
        calls = []
 
2093
        def hook(*args):
 
2094
            calls.append(args)
 
2095
        config.OldConfigHooks.install_named_hook('get', hook, None)
 
2096
        self.addCleanup(
 
2097
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
 
2098
        self.assertLength(0, calls)
 
2099
        actual_value = conf.get_user_option(name)
 
2100
        self.assertEquals(value, actual_value)
 
2101
        self.assertLength(1, calls)
 
2102
        self.assertEquals((conf, name, value), calls[0])
 
2103
 
 
2104
    def test_get_hook_bazaar(self):
 
2105
        self.assertGetHook(self.bazaar_config, 'file', 'bazaar')
 
2106
 
 
2107
    def test_get_hook_locations(self):
 
2108
        self.assertGetHook(self.locations_config, 'file', 'locations')
 
2109
 
 
2110
    def test_get_hook_branch(self):
 
2111
        # Since locations masks branch, we define a different option
 
2112
        self.branch_config.set_user_option('file2', 'branch')
 
2113
        self.assertGetHook(self.branch_config, 'file2', 'branch')
 
2114
 
 
2115
    def assertSetHook(self, conf, name, value):
 
2116
        calls = []
 
2117
        def hook(*args):
 
2118
            calls.append(args)
 
2119
        config.OldConfigHooks.install_named_hook('set', hook, None)
 
2120
        self.addCleanup(
 
2121
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
 
2122
        self.assertLength(0, calls)
 
2123
        conf.set_user_option(name, value)
 
2124
        self.assertLength(1, calls)
 
2125
        # We can't assert the conf object below as different configs use
 
2126
        # different means to implement set_user_option and we care only about
 
2127
        # coverage here.
 
2128
        self.assertEquals((name, value), calls[0][1:])
 
2129
 
 
2130
    def test_set_hook_bazaar(self):
 
2131
        self.assertSetHook(self.bazaar_config, 'foo', 'bazaar')
 
2132
 
 
2133
    def test_set_hook_locations(self):
 
2134
        self.assertSetHook(self.locations_config, 'foo', 'locations')
 
2135
 
 
2136
    def test_set_hook_branch(self):
 
2137
        self.assertSetHook(self.branch_config, 'foo', 'branch')
 
2138
 
 
2139
    def assertRemoveHook(self, conf, name, section_name=None):
 
2140
        calls = []
 
2141
        def hook(*args):
 
2142
            calls.append(args)
 
2143
        config.OldConfigHooks.install_named_hook('remove', hook, None)
 
2144
        self.addCleanup(
 
2145
            config.OldConfigHooks.uninstall_named_hook, 'remove', None)
 
2146
        self.assertLength(0, calls)
 
2147
        conf.remove_user_option(name, section_name)
 
2148
        self.assertLength(1, calls)
 
2149
        # We can't assert the conf object below as different configs use
 
2150
        # different means to implement remove_user_option and we care only about
 
2151
        # coverage here.
 
2152
        self.assertEquals((name,), calls[0][1:])
 
2153
 
 
2154
    def test_remove_hook_bazaar(self):
 
2155
        self.assertRemoveHook(self.bazaar_config, 'file')
 
2156
 
 
2157
    def test_remove_hook_locations(self):
 
2158
        self.assertRemoveHook(self.locations_config, 'file',
 
2159
                              self.locations_config.location)
 
2160
 
 
2161
    def test_remove_hook_branch(self):
 
2162
        self.assertRemoveHook(self.branch_config, 'file')
 
2163
 
 
2164
    def assertLoadHook(self, name, conf_class, *conf_args):
 
2165
        calls = []
 
2166
        def hook(*args):
 
2167
            calls.append(args)
 
2168
        config.OldConfigHooks.install_named_hook('load', hook, None)
 
2169
        self.addCleanup(
 
2170
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
 
2171
        self.assertLength(0, calls)
 
2172
        # Build a config
 
2173
        conf = conf_class(*conf_args)
 
2174
        # Access an option to trigger a load
 
2175
        conf.get_user_option(name)
 
2176
        self.assertLength(1, calls)
 
2177
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2178
 
 
2179
    def test_load_hook_bazaar(self):
 
2180
        self.assertLoadHook('file', config.GlobalConfig)
 
2181
 
 
2182
    def test_load_hook_locations(self):
 
2183
        self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
 
2184
 
 
2185
    def test_load_hook_branch(self):
 
2186
        self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
 
2187
 
 
2188
    def assertSaveHook(self, conf):
 
2189
        calls = []
 
2190
        def hook(*args):
 
2191
            calls.append(args)
 
2192
        config.OldConfigHooks.install_named_hook('save', hook, None)
 
2193
        self.addCleanup(
 
2194
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
 
2195
        self.assertLength(0, calls)
 
2196
        # Setting an option triggers a save
 
2197
        conf.set_user_option('foo', 'bar')
 
2198
        self.assertLength(1, calls)
 
2199
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2200
 
 
2201
    def test_save_hook_bazaar(self):
 
2202
        self.assertSaveHook(self.bazaar_config)
 
2203
 
 
2204
    def test_save_hook_locations(self):
 
2205
        self.assertSaveHook(self.locations_config)
 
2206
 
 
2207
    def test_save_hook_branch(self):
 
2208
        self.assertSaveHook(self.branch_config)
 
2209
 
 
2210
 
 
2211
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
 
2212
    """Tests config hooks for remote configs.
 
2213
 
 
2214
    No tests for the remove hook as this is not implemented there.
 
2215
    """
 
2216
 
 
2217
    def setUp(self):
 
2218
        super(TestOldConfigHooksForRemote, self).setUp()
 
2219
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2220
        create_configs_with_file_option(self)
 
2221
 
 
2222
    def assertGetHook(self, conf, name, value):
 
2223
        calls = []
 
2224
        def hook(*args):
 
2225
            calls.append(args)
 
2226
        config.OldConfigHooks.install_named_hook('get', hook, None)
 
2227
        self.addCleanup(
 
2228
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
 
2229
        self.assertLength(0, calls)
 
2230
        actual_value = conf.get_option(name)
 
2231
        self.assertEquals(value, actual_value)
 
2232
        self.assertLength(1, calls)
 
2233
        self.assertEquals((conf, name, value), calls[0])
 
2234
 
 
2235
    def test_get_hook_remote_branch(self):
 
2236
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2237
        self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
 
2238
 
 
2239
    def test_get_hook_remote_bzrdir(self):
 
2240
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2241
        conf = remote_bzrdir._get_config()
 
2242
        conf.set_option('remotedir', 'file')
 
2243
        self.assertGetHook(conf, 'file', 'remotedir')
 
2244
 
 
2245
    def assertSetHook(self, conf, name, value):
 
2246
        calls = []
 
2247
        def hook(*args):
 
2248
            calls.append(args)
 
2249
        config.OldConfigHooks.install_named_hook('set', hook, None)
 
2250
        self.addCleanup(
 
2251
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
 
2252
        self.assertLength(0, calls)
 
2253
        conf.set_option(value, name)
 
2254
        self.assertLength(1, calls)
 
2255
        # We can't assert the conf object below as different configs use
 
2256
        # different means to implement set_user_option and we care only about
 
2257
        # coverage here.
 
2258
        self.assertEquals((name, value), calls[0][1:])
 
2259
 
 
2260
    def test_set_hook_remote_branch(self):
 
2261
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2262
        self.addCleanup(remote_branch.lock_write().unlock)
 
2263
        self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
 
2264
 
 
2265
    def test_set_hook_remote_bzrdir(self):
 
2266
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2267
        self.addCleanup(remote_branch.lock_write().unlock)
 
2268
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2269
        self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
 
2270
 
 
2271
    def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
 
2272
        calls = []
 
2273
        def hook(*args):
 
2274
            calls.append(args)
 
2275
        config.OldConfigHooks.install_named_hook('load', hook, None)
 
2276
        self.addCleanup(
 
2277
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
 
2278
        self.assertLength(0, calls)
 
2279
        # Build a config
 
2280
        conf = conf_class(*conf_args)
 
2281
        # Access an option to trigger a load
 
2282
        conf.get_option(name)
 
2283
        self.assertLength(expected_nb_calls, calls)
 
2284
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2285
 
 
2286
    def test_load_hook_remote_branch(self):
 
2287
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2288
        self.assertLoadHook(1, 'file', remote.RemoteBranchConfig, remote_branch)
 
2289
 
 
2290
    def test_load_hook_remote_bzrdir(self):
 
2291
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2292
        # The config file doesn't exist, set an option to force its creation
 
2293
        conf = remote_bzrdir._get_config()
 
2294
        conf.set_option('remotedir', 'file')
 
2295
        # We get one call for the server and one call for the client, this is
 
2296
        # caused by the differences in implementations betwen
 
2297
        # SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
 
2298
        # SmartServerBranchGetConfigFile (in smart/branch.py)
 
2299
        self.assertLoadHook(2 ,'file', remote.RemoteBzrDirConfig, remote_bzrdir)
 
2300
 
 
2301
    def assertSaveHook(self, conf):
 
2302
        calls = []
 
2303
        def hook(*args):
 
2304
            calls.append(args)
 
2305
        config.OldConfigHooks.install_named_hook('save', hook, None)
 
2306
        self.addCleanup(
 
2307
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
 
2308
        self.assertLength(0, calls)
 
2309
        # Setting an option triggers a save
 
2310
        conf.set_option('foo', 'bar')
 
2311
        self.assertLength(1, calls)
 
2312
        # Since we can't assert about conf, we just use the number of calls ;-/
 
2313
 
 
2314
    def test_save_hook_remote_branch(self):
 
2315
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2316
        self.addCleanup(remote_branch.lock_write().unlock)
 
2317
        self.assertSaveHook(remote_branch._get_config())
 
2318
 
 
2319
    def test_save_hook_remote_bzrdir(self):
 
2320
        remote_branch = branch.Branch.open(self.get_url('tree'))
 
2321
        self.addCleanup(remote_branch.lock_write().unlock)
 
2322
        remote_bzrdir = bzrdir.BzrDir.open(self.get_url('tree'))
 
2323
        self.assertSaveHook(remote_bzrdir._get_config())
 
2324
 
 
2325
 
 
2326
class TestOption(tests.TestCase):
 
2327
 
 
2328
    def test_default_value(self):
 
2329
        opt = config.Option('foo', default='bar')
 
2330
        self.assertEquals('bar', opt.get_default())
 
2331
 
 
2332
    def test_callable_default_value(self):
 
2333
        def bar_as_unicode():
 
2334
            return u'bar'
 
2335
        opt = config.Option('foo', default=bar_as_unicode)
 
2336
        self.assertEquals('bar', opt.get_default())
 
2337
 
 
2338
    def test_default_value_from_env(self):
 
2339
        opt = config.Option('foo', default='bar', default_from_env=['FOO'])
 
2340
        self.overrideEnv('FOO', 'quux')
 
2341
        # Env variable provides a default taking over the option one
 
2342
        self.assertEquals('quux', opt.get_default())
 
2343
 
 
2344
    def test_first_default_value_from_env_wins(self):
 
2345
        opt = config.Option('foo', default='bar',
 
2346
                            default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
 
2347
        self.overrideEnv('FOO', 'foo')
 
2348
        self.overrideEnv('BAZ', 'baz')
 
2349
        # The first env var set wins
 
2350
        self.assertEquals('foo', opt.get_default())
 
2351
 
 
2352
    def test_not_supported_list_default_value(self):
 
2353
        self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
 
2354
 
 
2355
    def test_not_supported_object_default_value(self):
 
2356
        self.assertRaises(AssertionError, config.Option, 'foo',
 
2357
                          default=object())
 
2358
 
 
2359
    def test_not_supported_callable_default_value_not_unicode(self):
 
2360
        def bar_not_unicode():
 
2361
            return 'bar'
 
2362
        opt = config.Option('foo', default=bar_not_unicode)
 
2363
        self.assertRaises(AssertionError, opt.get_default)
 
2364
 
 
2365
 
 
2366
class TestOptionConverterMixin(object):
 
2367
 
 
2368
    def assertConverted(self, expected, opt, value):
 
2369
        self.assertEquals(expected, opt.convert_from_unicode(None, value))
 
2370
 
 
2371
    def assertWarns(self, opt, value):
 
2372
        warnings = []
 
2373
        def warning(*args):
 
2374
            warnings.append(args[0] % args[1:])
 
2375
        self.overrideAttr(trace, 'warning', warning)
 
2376
        self.assertEquals(None, opt.convert_from_unicode(None, value))
 
2377
        self.assertLength(1, warnings)
 
2378
        self.assertEquals(
 
2379
            'Value "%s" is not valid for "%s"' % (value, opt.name),
 
2380
            warnings[0])
 
2381
 
 
2382
    def assertErrors(self, opt, value):
 
2383
        self.assertRaises(errors.ConfigOptionValueError,
 
2384
                          opt.convert_from_unicode, None, value)
 
2385
 
 
2386
    def assertConvertInvalid(self, opt, invalid_value):
 
2387
        opt.invalid = None
 
2388
        self.assertEquals(None, opt.convert_from_unicode(None, invalid_value))
 
2389
        opt.invalid = 'warning'
 
2390
        self.assertWarns(opt, invalid_value)
 
2391
        opt.invalid = 'error'
 
2392
        self.assertErrors(opt, invalid_value)
 
2393
 
 
2394
 
 
2395
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
 
2396
 
 
2397
    def get_option(self):
 
2398
        return config.Option('foo', help='A boolean.',
 
2399
                             from_unicode=config.bool_from_store)
 
2400
 
 
2401
    def test_convert_invalid(self):
 
2402
        opt = self.get_option()
 
2403
        # A string that is not recognized as a boolean
 
2404
        self.assertConvertInvalid(opt, u'invalid-boolean')
 
2405
        # A list of strings is never recognized as a boolean
 
2406
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
 
2407
 
 
2408
    def test_convert_valid(self):
 
2409
        opt = self.get_option()
 
2410
        self.assertConverted(True, opt, u'True')
 
2411
        self.assertConverted(True, opt, u'1')
 
2412
        self.assertConverted(False, opt, u'False')
 
2413
 
 
2414
 
 
2415
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
 
2416
 
 
2417
    def get_option(self):
 
2418
        return config.Option('foo', help='An integer.',
 
2419
                             from_unicode=config.int_from_store)
 
2420
 
 
2421
    def test_convert_invalid(self):
 
2422
        opt = self.get_option()
 
2423
        # A string that is not recognized as an integer
 
2424
        self.assertConvertInvalid(opt, u'forty-two')
 
2425
        # A list of strings is never recognized as an integer
 
2426
        self.assertConvertInvalid(opt, [u'a', u'list'])
 
2427
 
 
2428
    def test_convert_valid(self):
 
2429
        opt = self.get_option()
 
2430
        self.assertConverted(16, opt, u'16')
 
2431
 
 
2432
 
 
2433
class TestOptionWithSIUnitConverter(tests.TestCase, TestOptionConverterMixin):
 
2434
 
 
2435
    def get_option(self):
 
2436
        return config.Option('foo', help='An integer in SI units.',
 
2437
                             from_unicode=config.int_SI_from_store)
 
2438
 
 
2439
    def test_convert_invalid(self):
 
2440
        opt = self.get_option()
 
2441
        self.assertConvertInvalid(opt, u'not-a-unit')
 
2442
        self.assertConvertInvalid(opt, u'Gb') # Forgot the int
 
2443
        self.assertConvertInvalid(opt, u'1b') # Forgot the unit
 
2444
        self.assertConvertInvalid(opt, u'1GG')
 
2445
        self.assertConvertInvalid(opt, u'1Mbb')
 
2446
        self.assertConvertInvalid(opt, u'1MM')
 
2447
 
 
2448
    def test_convert_valid(self):
 
2449
        opt = self.get_option()
 
2450
        self.assertConverted(int(5e3), opt, u'5kb')
 
2451
        self.assertConverted(int(5e6), opt, u'5M')
 
2452
        self.assertConverted(int(5e6), opt, u'5MB')
 
2453
        self.assertConverted(int(5e9), opt, u'5g')
 
2454
        self.assertConverted(int(5e9), opt, u'5gB')
 
2455
        self.assertConverted(100, opt, u'100')
 
2456
 
 
2457
 
 
2458
class TestListOption(tests.TestCase, TestOptionConverterMixin):
 
2459
 
 
2460
    def get_option(self):
 
2461
        return config.ListOption('foo', help='A list.')
 
2462
 
 
2463
    def test_convert_invalid(self):
 
2464
        opt = self.get_option()
 
2465
        # We don't even try to convert a list into a list, we only expect
 
2466
        # strings
 
2467
        self.assertConvertInvalid(opt, [1])
 
2468
        # No string is invalid as all forms can be converted to a list
 
2469
 
 
2470
    def test_convert_valid(self):
 
2471
        opt = self.get_option()
 
2472
        # An empty string is an empty list
 
2473
        self.assertConverted([], opt, '') # Using a bare str() just in case
 
2474
        self.assertConverted([], opt, u'')
 
2475
        # A boolean
 
2476
        self.assertConverted([u'True'], opt, u'True')
 
2477
        # An integer
 
2478
        self.assertConverted([u'42'], opt, u'42')
 
2479
        # A single string
 
2480
        self.assertConverted([u'bar'], opt, u'bar')
 
2481
 
 
2482
 
 
2483
class TestOptionRegistry(tests.TestCase):
 
2484
 
 
2485
    def setUp(self):
 
2486
        super(TestOptionRegistry, self).setUp()
 
2487
        # Always start with an empty registry
 
2488
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
2489
        self.registry = config.option_registry
 
2490
 
 
2491
    def test_register(self):
 
2492
        opt = config.Option('foo')
 
2493
        self.registry.register(opt)
 
2494
        self.assertIs(opt, self.registry.get('foo'))
 
2495
 
 
2496
    def test_registered_help(self):
 
2497
        opt = config.Option('foo', help='A simple option')
 
2498
        self.registry.register(opt)
 
2499
        self.assertEquals('A simple option', self.registry.get_help('foo'))
 
2500
 
 
2501
    lazy_option = config.Option('lazy_foo', help='Lazy help')
 
2502
 
 
2503
    def test_register_lazy(self):
 
2504
        self.registry.register_lazy('lazy_foo', self.__module__,
 
2505
                                    'TestOptionRegistry.lazy_option')
 
2506
        self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
 
2507
 
 
2508
    def test_registered_lazy_help(self):
 
2509
        self.registry.register_lazy('lazy_foo', self.__module__,
 
2510
                                    'TestOptionRegistry.lazy_option')
 
2511
        self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
 
2512
 
 
2513
 
 
2514
class TestRegisteredOptions(tests.TestCase):
 
2515
    """All registered options should verify some constraints."""
 
2516
 
 
2517
    scenarios = [(key, {'option_name': key, 'option': option}) for key, option
 
2518
                 in config.option_registry.iteritems()]
 
2519
 
 
2520
    def setUp(self):
 
2521
        super(TestRegisteredOptions, self).setUp()
 
2522
        self.registry = config.option_registry
 
2523
 
 
2524
    def test_proper_name(self):
 
2525
        # An option should be registered under its own name, this can't be
 
2526
        # checked at registration time for the lazy ones.
 
2527
        self.assertEquals(self.option_name, self.option.name)
 
2528
 
 
2529
    def test_help_is_set(self):
 
2530
        option_help = self.registry.get_help(self.option_name)
 
2531
        self.assertNotEquals(None, option_help)
 
2532
        # Come on, think about the user, he really wants to know what the
 
2533
        # option is about
 
2534
        self.assertIsNot(None, option_help)
 
2535
        self.assertNotEquals('', option_help)
 
2536
 
 
2537
 
 
2538
class TestSection(tests.TestCase):
 
2539
 
 
2540
    # FIXME: Parametrize so that all sections produced by Stores run these
 
2541
    # tests -- vila 2011-04-01
 
2542
 
 
2543
    def test_get_a_value(self):
 
2544
        a_dict = dict(foo='bar')
 
2545
        section = config.Section('myID', a_dict)
 
2546
        self.assertEquals('bar', section.get('foo'))
 
2547
 
 
2548
    def test_get_unknown_option(self):
 
2549
        a_dict = dict()
 
2550
        section = config.Section(None, a_dict)
 
2551
        self.assertEquals('out of thin air',
 
2552
                          section.get('foo', 'out of thin air'))
 
2553
 
 
2554
    def test_options_is_shared(self):
 
2555
        a_dict = dict()
 
2556
        section = config.Section(None, a_dict)
 
2557
        self.assertIs(a_dict, section.options)
 
2558
 
 
2559
 
 
2560
class TestMutableSection(tests.TestCase):
 
2561
 
 
2562
    scenarios = [('mutable',
 
2563
                  {'get_section':
 
2564
                       lambda opts: config.MutableSection('myID', opts)},),
 
2565
        ]
 
2566
 
 
2567
    def test_set(self):
 
2568
        a_dict = dict(foo='bar')
 
2569
        section = self.get_section(a_dict)
 
2570
        section.set('foo', 'new_value')
 
2571
        self.assertEquals('new_value', section.get('foo'))
 
2572
        # The change appears in the shared section
 
2573
        self.assertEquals('new_value', a_dict.get('foo'))
 
2574
        # We keep track of the change
 
2575
        self.assertTrue('foo' in section.orig)
 
2576
        self.assertEquals('bar', section.orig.get('foo'))
 
2577
 
 
2578
    def test_set_preserve_original_once(self):
 
2579
        a_dict = dict(foo='bar')
 
2580
        section = self.get_section(a_dict)
 
2581
        section.set('foo', 'first_value')
 
2582
        section.set('foo', 'second_value')
 
2583
        # We keep track of the original value
 
2584
        self.assertTrue('foo' in section.orig)
 
2585
        self.assertEquals('bar', section.orig.get('foo'))
 
2586
 
 
2587
    def test_remove(self):
 
2588
        a_dict = dict(foo='bar')
 
2589
        section = self.get_section(a_dict)
 
2590
        section.remove('foo')
 
2591
        # We get None for unknown options via the default value
 
2592
        self.assertEquals(None, section.get('foo'))
 
2593
        # Or we just get the default value
 
2594
        self.assertEquals('unknown', section.get('foo', 'unknown'))
 
2595
        self.assertFalse('foo' in section.options)
 
2596
        # We keep track of the deletion
 
2597
        self.assertTrue('foo' in section.orig)
 
2598
        self.assertEquals('bar', section.orig.get('foo'))
 
2599
 
 
2600
    def test_remove_new_option(self):
 
2601
        a_dict = dict()
 
2602
        section = self.get_section(a_dict)
 
2603
        section.set('foo', 'bar')
 
2604
        section.remove('foo')
 
2605
        self.assertFalse('foo' in section.options)
 
2606
        # The option didn't exist initially so it we need to keep track of it
 
2607
        # with a special value
 
2608
        self.assertTrue('foo' in section.orig)
 
2609
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
 
2610
 
 
2611
 
 
2612
class TestCommandLineStore(tests.TestCase):
 
2613
 
 
2614
    def setUp(self):
 
2615
        super(TestCommandLineStore, self).setUp()
 
2616
        self.store = config.CommandLineStore()
 
2617
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
2618
 
 
2619
    def get_section(self):
 
2620
        """Get the unique section for the command line overrides."""
 
2621
        sections = list(self.store.get_sections())
 
2622
        self.assertLength(1, sections)
 
2623
        store, section = sections[0]
 
2624
        self.assertEquals(self.store, store)
 
2625
        return section
 
2626
 
 
2627
    def test_no_override(self):
 
2628
        self.store._from_cmdline([])
 
2629
        section = self.get_section()
 
2630
        self.assertLength(0, list(section.iter_option_names()))
 
2631
 
 
2632
    def test_simple_override(self):
 
2633
        self.store._from_cmdline(['a=b'])
 
2634
        section = self.get_section()
 
2635
        self.assertEqual('b', section.get('a'))
 
2636
 
 
2637
    def test_list_override(self):
 
2638
        opt = config.ListOption('l')
 
2639
        config.option_registry.register(opt)
 
2640
        self.store._from_cmdline(['l=1,2,3'])
 
2641
        val = self.get_section().get('l')
 
2642
        self.assertEqual('1,2,3', val)
 
2643
        # Reminder: lists should be registered as such explicitely, otherwise
 
2644
        # the conversion needs to be done afterwards.
 
2645
        self.assertEqual(['1', '2', '3'],
 
2646
                         opt.convert_from_unicode(self.store, val))
 
2647
 
 
2648
    def test_multiple_overrides(self):
 
2649
        self.store._from_cmdline(['a=b', 'x=y'])
 
2650
        section = self.get_section()
 
2651
        self.assertEquals('b', section.get('a'))
 
2652
        self.assertEquals('y', section.get('x'))
 
2653
 
 
2654
    def test_wrong_syntax(self):
 
2655
        self.assertRaises(errors.BzrCommandError,
 
2656
                          self.store._from_cmdline, ['a=b', 'c'])
 
2657
 
 
2658
class TestStoreMinimalAPI(tests.TestCaseWithTransport):
 
2659
 
 
2660
    scenarios = [(key, {'get_store': builder}) for key, builder
 
2661
                 in config.test_store_builder_registry.iteritems()] + [
 
2662
        ('cmdline', {'get_store': lambda test: config.CommandLineStore()})]
 
2663
 
 
2664
    def test_id(self):
 
2665
        store = self.get_store(self)
 
2666
        if type(store) == config.TransportIniFileStore:
 
2667
            raise tests.TestNotApplicable(
 
2668
                "%s is not a concrete Store implementation"
 
2669
                " so it doesn't need an id" % (store.__class__.__name__,))
 
2670
        self.assertIsNot(None, store.id)
 
2671
 
 
2672
 
 
2673
class TestStore(tests.TestCaseWithTransport):
 
2674
 
 
2675
    def assertSectionContent(self, expected, (store, section)):
 
2676
        """Assert that some options have the proper values in a section."""
 
2677
        expected_name, expected_options = expected
 
2678
        self.assertEquals(expected_name, section.id)
 
2679
        self.assertEquals(
 
2680
            expected_options,
 
2681
            dict([(k, section.get(k)) for k in expected_options.keys()]))
 
2682
 
 
2683
 
 
2684
class TestReadonlyStore(TestStore):
 
2685
 
 
2686
    scenarios = [(key, {'get_store': builder}) for key, builder
 
2687
                 in config.test_store_builder_registry.iteritems()]
 
2688
 
 
2689
    def test_building_delays_load(self):
 
2690
        store = self.get_store(self)
 
2691
        self.assertEquals(False, store.is_loaded())
 
2692
        store._load_from_string('')
 
2693
        self.assertEquals(True, store.is_loaded())
 
2694
 
 
2695
    def test_get_no_sections_for_empty(self):
 
2696
        store = self.get_store(self)
 
2697
        store._load_from_string('')
 
2698
        self.assertEquals([], list(store.get_sections()))
 
2699
 
 
2700
    def test_get_default_section(self):
 
2701
        store = self.get_store(self)
 
2702
        store._load_from_string('foo=bar')
 
2703
        sections = list(store.get_sections())
 
2704
        self.assertLength(1, sections)
 
2705
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2706
 
 
2707
    def test_get_named_section(self):
 
2708
        store = self.get_store(self)
 
2709
        store._load_from_string('[baz]\nfoo=bar')
 
2710
        sections = list(store.get_sections())
 
2711
        self.assertLength(1, sections)
 
2712
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
2713
 
 
2714
    def test_load_from_string_fails_for_non_empty_store(self):
 
2715
        store = self.get_store(self)
 
2716
        store._load_from_string('foo=bar')
 
2717
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
 
2718
 
 
2719
 
 
2720
class TestStoreQuoting(TestStore):
 
2721
 
 
2722
    scenarios = [(key, {'get_store': builder}) for key, builder
 
2723
                 in config.test_store_builder_registry.iteritems()]
 
2724
 
 
2725
    def setUp(self):
 
2726
        super(TestStoreQuoting, self).setUp()
 
2727
        self.store = self.get_store(self)
 
2728
        # We need a loaded store but any content will do
 
2729
        self.store._load_from_string('')
 
2730
 
 
2731
    def assertIdempotent(self, s):
 
2732
        """Assert that quoting an unquoted string is a no-op and vice-versa.
 
2733
 
 
2734
        What matters here is that option values, as they appear in a store, can
 
2735
        be safely round-tripped out of the store and back.
 
2736
 
 
2737
        :param s: A string, quoted if required.
 
2738
        """
 
2739
        self.assertEquals(s, self.store.quote(self.store.unquote(s)))
 
2740
        self.assertEquals(s, self.store.unquote(self.store.quote(s)))
 
2741
 
 
2742
    def test_empty_string(self):
 
2743
        if isinstance(self.store, config.IniFileStore):
 
2744
            # configobj._quote doesn't handle empty values
 
2745
            self.assertRaises(AssertionError,
 
2746
                              self.assertIdempotent, '')
 
2747
        else:
 
2748
            self.assertIdempotent('')
 
2749
        # But quoted empty strings are ok
 
2750
        self.assertIdempotent('""')
 
2751
 
 
2752
    def test_embedded_spaces(self):
 
2753
        self.assertIdempotent('" a b c "')
 
2754
 
 
2755
    def test_embedded_commas(self):
 
2756
        self.assertIdempotent('" a , b c "')
 
2757
 
 
2758
    def test_simple_comma(self):
 
2759
        if isinstance(self.store, config.IniFileStore):
 
2760
            # configobj requires that lists are special-cased
 
2761
           self.assertRaises(AssertionError,
 
2762
                             self.assertIdempotent, ',')
 
2763
        else:
 
2764
            self.assertIdempotent(',')
 
2765
        # When a single comma is required, quoting is also required
 
2766
        self.assertIdempotent('","')
 
2767
 
 
2768
    def test_list(self):
 
2769
        if isinstance(self.store, config.IniFileStore):
 
2770
            # configobj requires that lists are special-cased
 
2771
            self.assertRaises(AssertionError,
 
2772
                              self.assertIdempotent, 'a,b')
 
2773
        else:
 
2774
            self.assertIdempotent('a,b')
 
2775
 
 
2776
 
 
2777
class TestDictFromStore(tests.TestCase):
 
2778
 
 
2779
    def test_unquote_not_string(self):
 
2780
        conf = config.MemoryStack('x=2\n[a_section]\na=1\n')
 
2781
        value = conf.get('a_section')
 
2782
        # Urgh, despite 'conf' asking for the no-name section, we get the
 
2783
        # content of another section as a dict o_O
 
2784
        self.assertEquals({'a': '1'}, value)
 
2785
        unquoted = conf.store.unquote(value)
 
2786
        # Which cannot be unquoted but shouldn't crash either (the use cases
 
2787
        # are getting the value or displaying it. In the later case, '%s' will
 
2788
        # do).
 
2789
        self.assertEquals({'a': '1'}, unquoted)
 
2790
        self.assertEquals("{u'a': u'1'}", '%s' % (unquoted,))
 
2791
 
 
2792
 
 
2793
class TestIniFileStoreContent(tests.TestCaseWithTransport):
 
2794
    """Simulate loading a config store with content of various encodings.
 
2795
 
 
2796
    All files produced by bzr are in utf8 content.
 
2797
 
 
2798
    Users may modify them manually and end up with a file that can't be
 
2799
    loaded. We need to issue proper error messages in this case.
 
2800
    """
 
2801
 
 
2802
    invalid_utf8_char = '\xff'
 
2803
 
 
2804
    def test_load_utf8(self):
 
2805
        """Ensure we can load an utf8-encoded file."""
 
2806
        t = self.get_transport()
 
2807
        # From http://pad.lv/799212
 
2808
        unicode_user = u'b\N{Euro Sign}ar'
 
2809
        unicode_content = u'user=%s' % (unicode_user,)
 
2810
        utf8_content = unicode_content.encode('utf8')
 
2811
        # Store the raw content in the config file
 
2812
        t.put_bytes('foo.conf', utf8_content)
 
2813
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2814
        store.load()
 
2815
        stack = config.Stack([store.get_sections], store)
 
2816
        self.assertEquals(unicode_user, stack.get('user'))
 
2817
 
 
2818
    def test_load_non_ascii(self):
 
2819
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
 
2820
        t = self.get_transport()
 
2821
        t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
 
2822
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2823
        self.assertRaises(errors.ConfigContentError, store.load)
 
2824
 
 
2825
    def test_load_erroneous_content(self):
 
2826
        """Ensure we display a proper error on content that can't be parsed."""
 
2827
        t = self.get_transport()
 
2828
        t.put_bytes('foo.conf', '[open_section\n')
 
2829
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2830
        self.assertRaises(errors.ParseConfigError, store.load)
 
2831
 
 
2832
    def test_load_permission_denied(self):
 
2833
        """Ensure we get warned when trying to load an inaccessible file."""
 
2834
        warnings = []
 
2835
        def warning(*args):
 
2836
            warnings.append(args[0] % args[1:])
 
2837
        self.overrideAttr(trace, 'warning', warning)
 
2838
 
 
2839
        t = self.get_transport()
 
2840
 
 
2841
        def get_bytes(relpath):
 
2842
            raise errors.PermissionDenied(relpath, "")
 
2843
        t.get_bytes = get_bytes
 
2844
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2845
        self.assertRaises(errors.PermissionDenied, store.load)
 
2846
        self.assertEquals(
 
2847
            warnings,
 
2848
            [u'Permission denied while trying to load configuration store %s.'
 
2849
             % store.external_url()])
 
2850
 
 
2851
 
 
2852
class TestIniConfigContent(tests.TestCaseWithTransport):
 
2853
    """Simulate loading a IniBasedConfig with content of various encodings.
 
2854
 
 
2855
    All files produced by bzr are in utf8 content.
 
2856
 
 
2857
    Users may modify them manually and end up with a file that can't be
 
2858
    loaded. We need to issue proper error messages in this case.
 
2859
    """
 
2860
 
 
2861
    invalid_utf8_char = '\xff'
 
2862
 
 
2863
    def test_load_utf8(self):
 
2864
        """Ensure we can load an utf8-encoded file."""
 
2865
        # From http://pad.lv/799212
 
2866
        unicode_user = u'b\N{Euro Sign}ar'
 
2867
        unicode_content = u'user=%s' % (unicode_user,)
 
2868
        utf8_content = unicode_content.encode('utf8')
 
2869
        # Store the raw content in the config file
 
2870
        with open('foo.conf', 'wb') as f:
 
2871
            f.write(utf8_content)
 
2872
        conf = config.IniBasedConfig(file_name='foo.conf')
 
2873
        self.assertEquals(unicode_user, conf.get_user_option('user'))
 
2874
 
 
2875
    def test_load_badly_encoded_content(self):
 
2876
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
 
2877
        with open('foo.conf', 'wb') as f:
 
2878
            f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
 
2879
        conf = config.IniBasedConfig(file_name='foo.conf')
 
2880
        self.assertRaises(errors.ConfigContentError, conf._get_parser)
 
2881
 
 
2882
    def test_load_erroneous_content(self):
 
2883
        """Ensure we display a proper error on content that can't be parsed."""
 
2884
        with open('foo.conf', 'wb') as f:
 
2885
            f.write('[open_section\n')
 
2886
        conf = config.IniBasedConfig(file_name='foo.conf')
 
2887
        self.assertRaises(errors.ParseConfigError, conf._get_parser)
 
2888
 
 
2889
 
 
2890
class TestMutableStore(TestStore):
 
2891
 
 
2892
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
 
2893
                 in config.test_store_builder_registry.iteritems()]
 
2894
 
 
2895
    def setUp(self):
 
2896
        super(TestMutableStore, self).setUp()
 
2897
        self.transport = self.get_transport()
 
2898
 
 
2899
    def has_store(self, store):
 
2900
        store_basename = urlutils.relative_url(self.transport.external_url(),
 
2901
                                               store.external_url())
 
2902
        return self.transport.has(store_basename)
 
2903
 
 
2904
    def test_save_empty_creates_no_file(self):
 
2905
        # FIXME: There should be a better way than relying on the test
 
2906
        # parametrization to identify branch.conf -- vila 2011-0526
 
2907
        if self.store_id in ('branch', 'remote_branch'):
 
2908
            raise tests.TestNotApplicable(
 
2909
                'branch.conf is *always* created when a branch is initialized')
 
2910
        store = self.get_store(self)
 
2911
        store.save()
 
2912
        self.assertEquals(False, self.has_store(store))
 
2913
 
 
2914
    def test_save_emptied_succeeds(self):
 
2915
        store = self.get_store(self)
 
2916
        store._load_from_string('foo=bar\n')
 
2917
        section = store.get_mutable_section(None)
 
2918
        section.remove('foo')
 
2919
        store.save()
 
2920
        self.assertEquals(True, self.has_store(store))
 
2921
        modified_store = self.get_store(self)
 
2922
        sections = list(modified_store.get_sections())
 
2923
        self.assertLength(0, sections)
 
2924
 
 
2925
    def test_save_with_content_succeeds(self):
 
2926
        # FIXME: There should be a better way than relying on the test
 
2927
        # parametrization to identify branch.conf -- vila 2011-0526
 
2928
        if self.store_id in ('branch', 'remote_branch'):
 
2929
            raise tests.TestNotApplicable(
 
2930
                'branch.conf is *always* created when a branch is initialized')
 
2931
        store = self.get_store(self)
 
2932
        store._load_from_string('foo=bar\n')
 
2933
        self.assertEquals(False, self.has_store(store))
 
2934
        store.save()
 
2935
        self.assertEquals(True, self.has_store(store))
 
2936
        modified_store = self.get_store(self)
 
2937
        sections = list(modified_store.get_sections())
 
2938
        self.assertLength(1, sections)
 
2939
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2940
 
 
2941
    def test_set_option_in_empty_store(self):
 
2942
        store = self.get_store(self)
 
2943
        section = store.get_mutable_section(None)
 
2944
        section.set('foo', 'bar')
 
2945
        store.save()
 
2946
        modified_store = self.get_store(self)
 
2947
        sections = list(modified_store.get_sections())
 
2948
        self.assertLength(1, sections)
 
2949
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2950
 
 
2951
    def test_set_option_in_default_section(self):
 
2952
        store = self.get_store(self)
 
2953
        store._load_from_string('')
 
2954
        section = store.get_mutable_section(None)
 
2955
        section.set('foo', 'bar')
 
2956
        store.save()
 
2957
        modified_store = self.get_store(self)
 
2958
        sections = list(modified_store.get_sections())
 
2959
        self.assertLength(1, sections)
 
2960
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2961
 
 
2962
    def test_set_option_in_named_section(self):
 
2963
        store = self.get_store(self)
 
2964
        store._load_from_string('')
 
2965
        section = store.get_mutable_section('baz')
 
2966
        section.set('foo', 'bar')
 
2967
        store.save()
 
2968
        modified_store = self.get_store(self)
 
2969
        sections = list(modified_store.get_sections())
 
2970
        self.assertLength(1, sections)
 
2971
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
2972
 
 
2973
    def test_load_hook(self):
 
2974
        # We first needs to ensure that the store exists
 
2975
        store = self.get_store(self)
 
2976
        section = store.get_mutable_section('baz')
 
2977
        section.set('foo', 'bar')
 
2978
        store.save()
 
2979
        # Now we can try to load it
 
2980
        store = self.get_store(self)
 
2981
        calls = []
 
2982
        def hook(*args):
 
2983
            calls.append(args)
 
2984
        config.ConfigHooks.install_named_hook('load', hook, None)
 
2985
        self.assertLength(0, calls)
 
2986
        store.load()
 
2987
        self.assertLength(1, calls)
 
2988
        self.assertEquals((store,), calls[0])
 
2989
 
 
2990
    def test_save_hook(self):
 
2991
        calls = []
 
2992
        def hook(*args):
 
2993
            calls.append(args)
 
2994
        config.ConfigHooks.install_named_hook('save', hook, None)
 
2995
        self.assertLength(0, calls)
 
2996
        store = self.get_store(self)
 
2997
        section = store.get_mutable_section('baz')
 
2998
        section.set('foo', 'bar')
 
2999
        store.save()
 
3000
        self.assertLength(1, calls)
 
3001
        self.assertEquals((store,), calls[0])
 
3002
 
 
3003
    def test_set_mark_dirty(self):
 
3004
        stack = config.MemoryStack('')
 
3005
        self.assertLength(0, stack.store.dirty_sections)
 
3006
        stack.set('foo', 'baz')
 
3007
        self.assertLength(1, stack.store.dirty_sections)
 
3008
        self.assertTrue(stack.store._need_saving())
 
3009
 
 
3010
    def test_remove_mark_dirty(self):
 
3011
        stack = config.MemoryStack('foo=bar')
 
3012
        self.assertLength(0, stack.store.dirty_sections)
 
3013
        stack.remove('foo')
 
3014
        self.assertLength(1, stack.store.dirty_sections)
 
3015
        self.assertTrue(stack.store._need_saving())
 
3016
 
 
3017
 
 
3018
class TestStoreSaveChanges(tests.TestCaseWithTransport):
 
3019
    """Tests that config changes are kept in memory and saved on-demand."""
 
3020
 
 
3021
    def setUp(self):
 
3022
        super(TestStoreSaveChanges, self).setUp()
 
3023
        self.transport = self.get_transport()
 
3024
        # Most of the tests involve two stores pointing to the same persistent
 
3025
        # storage to observe the effects of concurrent changes
 
3026
        self.st1 = config.TransportIniFileStore(self.transport, 'foo.conf')
 
3027
        self.st2 = config.TransportIniFileStore(self.transport, 'foo.conf')
 
3028
        self.warnings = []
 
3029
        def warning(*args):
 
3030
            self.warnings.append(args[0] % args[1:])
 
3031
        self.overrideAttr(trace, 'warning', warning)
 
3032
 
 
3033
    def has_store(self, store):
 
3034
        store_basename = urlutils.relative_url(self.transport.external_url(),
 
3035
                                               store.external_url())
 
3036
        return self.transport.has(store_basename)
 
3037
 
 
3038
    def get_stack(self, store):
 
3039
        # Any stack will do as long as it uses the right store, just a single
 
3040
        # no-name section is enough
 
3041
        return config.Stack([store.get_sections], store)
 
3042
 
 
3043
    def test_no_changes_no_save(self):
 
3044
        s = self.get_stack(self.st1)
 
3045
        s.store.save_changes()
 
3046
        self.assertEquals(False, self.has_store(self.st1))
 
3047
 
 
3048
    def test_unrelated_concurrent_update(self):
 
3049
        s1 = self.get_stack(self.st1)
 
3050
        s2 = self.get_stack(self.st2)
 
3051
        s1.set('foo', 'bar')
 
3052
        s2.set('baz', 'quux')
 
3053
        s1.store.save()
 
3054
        # Changes don't propagate magically
 
3055
        self.assertEquals(None, s1.get('baz'))
 
3056
        s2.store.save_changes()
 
3057
        self.assertEquals('quux', s2.get('baz'))
 
3058
        # Changes are acquired when saving
 
3059
        self.assertEquals('bar', s2.get('foo'))
 
3060
        # Since there is no overlap, no warnings are emitted
 
3061
        self.assertLength(0, self.warnings)
 
3062
 
 
3063
    def test_concurrent_update_modified(self):
 
3064
        s1 = self.get_stack(self.st1)
 
3065
        s2 = self.get_stack(self.st2)
 
3066
        s1.set('foo', 'bar')
 
3067
        s2.set('foo', 'baz')
 
3068
        s1.store.save()
 
3069
        # Last speaker wins
 
3070
        s2.store.save_changes()
 
3071
        self.assertEquals('baz', s2.get('foo'))
 
3072
        # But the user get a warning
 
3073
        self.assertLength(1, self.warnings)
 
3074
        warning = self.warnings[0]
 
3075
        self.assertStartsWith(warning, 'Option foo in section None')
 
3076
        self.assertEndsWith(warning, 'was changed from <CREATED> to bar.'
 
3077
                            ' The baz value will be saved.')
 
3078
 
 
3079
    def test_concurrent_deletion(self):
 
3080
        self.st1._load_from_string('foo=bar')
 
3081
        self.st1.save()
 
3082
        s1 = self.get_stack(self.st1)
 
3083
        s2 = self.get_stack(self.st2)
 
3084
        s1.remove('foo')
 
3085
        s2.remove('foo')
 
3086
        s1.store.save_changes()
 
3087
        # No warning yet
 
3088
        self.assertLength(0, self.warnings)
 
3089
        s2.store.save_changes()
 
3090
        # Now we get one
 
3091
        self.assertLength(1, self.warnings)
 
3092
        warning = self.warnings[0]
 
3093
        self.assertStartsWith(warning, 'Option foo in section None')
 
3094
        self.assertEndsWith(warning, 'was changed from bar to <CREATED>.'
 
3095
                            ' The <DELETED> value will be saved.')
 
3096
 
 
3097
 
 
3098
class TestQuotingIniFileStore(tests.TestCaseWithTransport):
 
3099
 
 
3100
    def get_store(self):
 
3101
        return config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
3102
 
 
3103
    def test_get_quoted_string(self):
 
3104
        store = self.get_store()
 
3105
        store._load_from_string('foo= " abc "')
 
3106
        stack = config.Stack([store.get_sections])
 
3107
        self.assertEquals(' abc ', stack.get('foo'))
 
3108
 
 
3109
    def test_set_quoted_string(self):
 
3110
        store = self.get_store()
 
3111
        stack = config.Stack([store.get_sections], store)
 
3112
        stack.set('foo', ' a b c ')
 
3113
        store.save()
 
3114
        self.assertFileEqual('foo = " a b c "' + os.linesep, 'foo.conf')
 
3115
 
 
3116
 
 
3117
class TestTransportIniFileStore(TestStore):
 
3118
 
 
3119
    def test_loading_unknown_file_fails(self):
 
3120
        store = config.TransportIniFileStore(self.get_transport(),
 
3121
            'I-do-not-exist')
 
3122
        self.assertRaises(errors.NoSuchFile, store.load)
 
3123
 
 
3124
    def test_invalid_content(self):
 
3125
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
3126
        self.assertEquals(False, store.is_loaded())
 
3127
        exc = self.assertRaises(
 
3128
            errors.ParseConfigError, store._load_from_string,
 
3129
            'this is invalid !')
 
3130
        self.assertEndsWith(exc.filename, 'foo.conf')
 
3131
        # And the load failed
 
3132
        self.assertEquals(False, store.is_loaded())
 
3133
 
 
3134
    def test_get_embedded_sections(self):
 
3135
        # A more complicated example (which also shows that section names and
 
3136
        # option names share the same name space...)
 
3137
        # FIXME: This should be fixed by forbidding dicts as values ?
 
3138
        # -- vila 2011-04-05
 
3139
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
3140
        store._load_from_string('''
 
3141
foo=bar
 
3142
l=1,2
 
3143
[DEFAULT]
 
3144
foo_in_DEFAULT=foo_DEFAULT
 
3145
[bar]
 
3146
foo_in_bar=barbar
 
3147
[baz]
 
3148
foo_in_baz=barbaz
 
3149
[[qux]]
 
3150
foo_in_qux=quux
 
3151
''')
 
3152
        sections = list(store.get_sections())
 
3153
        self.assertLength(4, sections)
 
3154
        # The default section has no name.
 
3155
        # List values are provided as strings and need to be explicitly
 
3156
        # converted by specifying from_unicode=list_from_store at option
 
3157
        # registration
 
3158
        self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
 
3159
                                  sections[0])
 
3160
        self.assertSectionContent(
 
3161
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
 
3162
        self.assertSectionContent(
 
3163
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
 
3164
        # sub sections are provided as embedded dicts.
 
3165
        self.assertSectionContent(
 
3166
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
 
3167
            sections[3])
 
3168
 
 
3169
 
 
3170
class TestLockableIniFileStore(TestStore):
 
3171
 
 
3172
    def test_create_store_in_created_dir(self):
 
3173
        self.assertPathDoesNotExist('dir')
 
3174
        t = self.get_transport('dir/subdir')
 
3175
        store = config.LockableIniFileStore(t, 'foo.conf')
 
3176
        store.get_mutable_section(None).set('foo', 'bar')
 
3177
        store.save()
 
3178
        self.assertPathExists('dir/subdir')
 
3179
 
 
3180
 
 
3181
class TestConcurrentStoreUpdates(TestStore):
 
3182
    """Test that Stores properly handle conccurent updates.
 
3183
 
 
3184
    New Store implementation may fail some of these tests but until such
 
3185
    implementations exist it's hard to properly filter them from the scenarios
 
3186
    applied here. If you encounter such a case, contact the bzr devs.
 
3187
    """
 
3188
 
 
3189
    scenarios = [(key, {'get_stack': builder}) for key, builder
 
3190
                 in config.test_stack_builder_registry.iteritems()]
 
3191
 
 
3192
    def setUp(self):
 
3193
        super(TestConcurrentStoreUpdates, self).setUp()
 
3194
        self.stack = self.get_stack(self)
 
3195
        if not isinstance(self.stack, config._CompatibleStack):
 
3196
            raise tests.TestNotApplicable(
 
3197
                '%s is not meant to be compatible with the old config design'
 
3198
                % (self.stack,))
 
3199
        self.stack.set('one', '1')
 
3200
        self.stack.set('two', '2')
 
3201
        # Flush the store
 
3202
        self.stack.store.save()
 
3203
 
 
3204
    def test_simple_read_access(self):
 
3205
        self.assertEquals('1', self.stack.get('one'))
 
3206
 
 
3207
    def test_simple_write_access(self):
 
3208
        self.stack.set('one', 'one')
 
3209
        self.assertEquals('one', self.stack.get('one'))
 
3210
 
 
3211
    def test_listen_to_the_last_speaker(self):
 
3212
        c1 = self.stack
 
3213
        c2 = self.get_stack(self)
 
3214
        c1.set('one', 'ONE')
 
3215
        c2.set('two', 'TWO')
 
3216
        self.assertEquals('ONE', c1.get('one'))
 
3217
        self.assertEquals('TWO', c2.get('two'))
 
3218
        # The second update respect the first one
 
3219
        self.assertEquals('ONE', c2.get('one'))
 
3220
 
 
3221
    def test_last_speaker_wins(self):
 
3222
        # If the same config is not shared, the same variable modified twice
 
3223
        # can only see a single result.
 
3224
        c1 = self.stack
 
3225
        c2 = self.get_stack(self)
 
3226
        c1.set('one', 'c1')
 
3227
        c2.set('one', 'c2')
 
3228
        self.assertEquals('c2', c2.get('one'))
 
3229
        # The first modification is still available until another refresh
 
3230
        # occur
 
3231
        self.assertEquals('c1', c1.get('one'))
 
3232
        c1.set('two', 'done')
 
3233
        self.assertEquals('c2', c1.get('one'))
 
3234
 
 
3235
    def test_writes_are_serialized(self):
 
3236
        c1 = self.stack
 
3237
        c2 = self.get_stack(self)
 
3238
 
 
3239
        # We spawn a thread that will pause *during* the config saving.
 
3240
        before_writing = threading.Event()
 
3241
        after_writing = threading.Event()
 
3242
        writing_done = threading.Event()
 
3243
        c1_save_without_locking_orig = c1.store.save_without_locking
 
3244
        def c1_save_without_locking():
 
3245
            before_writing.set()
 
3246
            c1_save_without_locking_orig()
 
3247
            # The lock is held. We wait for the main thread to decide when to
 
3248
            # continue
 
3249
            after_writing.wait()
 
3250
        c1.store.save_without_locking = c1_save_without_locking
 
3251
        def c1_set():
 
3252
            c1.set('one', 'c1')
 
3253
            writing_done.set()
 
3254
        t1 = threading.Thread(target=c1_set)
 
3255
        # Collect the thread after the test
 
3256
        self.addCleanup(t1.join)
 
3257
        # Be ready to unblock the thread if the test goes wrong
 
3258
        self.addCleanup(after_writing.set)
 
3259
        t1.start()
 
3260
        before_writing.wait()
 
3261
        self.assertRaises(errors.LockContention,
 
3262
                          c2.set, 'one', 'c2')
 
3263
        self.assertEquals('c1', c1.get('one'))
 
3264
        # Let the lock be released
 
3265
        after_writing.set()
 
3266
        writing_done.wait()
 
3267
        c2.set('one', 'c2')
 
3268
        self.assertEquals('c2', c2.get('one'))
 
3269
 
 
3270
    def test_read_while_writing(self):
 
3271
       c1 = self.stack
 
3272
       # We spawn a thread that will pause *during* the write
 
3273
       ready_to_write = threading.Event()
 
3274
       do_writing = threading.Event()
 
3275
       writing_done = threading.Event()
 
3276
       # We override the _save implementation so we know the store is locked
 
3277
       c1_save_without_locking_orig = c1.store.save_without_locking
 
3278
       def c1_save_without_locking():
 
3279
           ready_to_write.set()
 
3280
           # The lock is held. We wait for the main thread to decide when to
 
3281
           # continue
 
3282
           do_writing.wait()
 
3283
           c1_save_without_locking_orig()
 
3284
           writing_done.set()
 
3285
       c1.store.save_without_locking = c1_save_without_locking
 
3286
       def c1_set():
 
3287
           c1.set('one', 'c1')
 
3288
       t1 = threading.Thread(target=c1_set)
 
3289
       # Collect the thread after the test
 
3290
       self.addCleanup(t1.join)
 
3291
       # Be ready to unblock the thread if the test goes wrong
 
3292
       self.addCleanup(do_writing.set)
 
3293
       t1.start()
 
3294
       # Ensure the thread is ready to write
 
3295
       ready_to_write.wait()
 
3296
       self.assertEquals('c1', c1.get('one'))
 
3297
       # If we read during the write, we get the old value
 
3298
       c2 = self.get_stack(self)
 
3299
       self.assertEquals('1', c2.get('one'))
 
3300
       # Let the writing occur and ensure it occurred
 
3301
       do_writing.set()
 
3302
       writing_done.wait()
 
3303
       # Now we get the updated value
 
3304
       c3 = self.get_stack(self)
 
3305
       self.assertEquals('c1', c3.get('one'))
 
3306
 
 
3307
    # FIXME: It may be worth looking into removing the lock dir when it's not
 
3308
    # needed anymore and look at possible fallouts for concurrent lockers. This
 
3309
    # will matter if/when we use config files outside of bazaar directories
 
3310
    # (.bazaar or .bzr) -- vila 20110-04-111
 
3311
 
 
3312
 
 
3313
class TestSectionMatcher(TestStore):
 
3314
 
 
3315
    scenarios = [('location', {'matcher': config.LocationMatcher}),
 
3316
                 ('id', {'matcher': config.NameMatcher}),]
 
3317
 
 
3318
    def setUp(self):
 
3319
        super(TestSectionMatcher, self).setUp()
 
3320
        # Any simple store is good enough
 
3321
        self.get_store = config.test_store_builder_registry.get('configobj')
 
3322
 
 
3323
    def test_no_matches_for_empty_stores(self):
 
3324
        store = self.get_store(self)
 
3325
        store._load_from_string('')
 
3326
        matcher = self.matcher(store, '/bar')
 
3327
        self.assertEquals([], list(matcher.get_sections()))
 
3328
 
 
3329
    def test_build_doesnt_load_store(self):
 
3330
        store = self.get_store(self)
 
3331
        matcher = self.matcher(store, '/bar')
 
3332
        self.assertFalse(store.is_loaded())
 
3333
 
 
3334
 
 
3335
class TestLocationSection(tests.TestCase):
 
3336
 
 
3337
    def get_section(self, options, extra_path):
 
3338
        section = config.Section('foo', options)
 
3339
        return config.LocationSection(section, extra_path)
 
3340
 
 
3341
    def test_simple_option(self):
 
3342
        section = self.get_section({'foo': 'bar'}, '')
 
3343
        self.assertEquals('bar', section.get('foo'))
 
3344
 
 
3345
    def test_option_with_extra_path(self):
 
3346
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
 
3347
                                   'baz')
 
3348
        self.assertEquals('bar/baz', section.get('foo'))
 
3349
 
 
3350
    def test_invalid_policy(self):
 
3351
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
 
3352
                                   'baz')
 
3353
        # invalid policies are ignored
 
3354
        self.assertEquals('bar', section.get('foo'))
 
3355
 
 
3356
 
 
3357
class TestLocationMatcher(TestStore):
 
3358
 
 
3359
    def setUp(self):
 
3360
        super(TestLocationMatcher, self).setUp()
 
3361
        # Any simple store is good enough
 
3362
        self.get_store = config.test_store_builder_registry.get('configobj')
 
3363
 
 
3364
    def test_unrelated_section_excluded(self):
 
3365
        store = self.get_store(self)
 
3366
        store._load_from_string('''
 
3367
[/foo]
 
3368
section=/foo
 
3369
[/foo/baz]
 
3370
section=/foo/baz
 
3371
[/foo/bar]
 
3372
section=/foo/bar
 
3373
[/foo/bar/baz]
 
3374
section=/foo/bar/baz
 
3375
[/quux/quux]
 
3376
section=/quux/quux
 
3377
''')
 
3378
        self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
 
3379
                           '/quux/quux'],
 
3380
                          [section.id for _, section in store.get_sections()])
 
3381
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
 
3382
        sections = [section for _, section in matcher.get_sections()]
 
3383
        self.assertEquals(['/foo/bar', '/foo'],
 
3384
                          [section.id for section in sections])
 
3385
        self.assertEquals(['quux', 'bar/quux'],
 
3386
                          [section.extra_path for section in sections])
 
3387
 
 
3388
    def test_more_specific_sections_first(self):
 
3389
        store = self.get_store(self)
 
3390
        store._load_from_string('''
 
3391
[/foo]
 
3392
section=/foo
 
3393
[/foo/bar]
 
3394
section=/foo/bar
 
3395
''')
 
3396
        self.assertEquals(['/foo', '/foo/bar'],
 
3397
                          [section.id for _, section in store.get_sections()])
 
3398
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
 
3399
        sections = [section for _, section in matcher.get_sections()]
 
3400
        self.assertEquals(['/foo/bar', '/foo'],
 
3401
                          [section.id for section in sections])
 
3402
        self.assertEquals(['baz', 'bar/baz'],
 
3403
                          [section.extra_path for section in sections])
 
3404
 
 
3405
    def test_appendpath_in_no_name_section(self):
 
3406
        # It's a bit weird to allow appendpath in a no-name section, but
 
3407
        # someone may found a use for it
 
3408
        store = self.get_store(self)
 
3409
        store._load_from_string('''
 
3410
foo=bar
 
3411
foo:policy = appendpath
 
3412
''')
 
3413
        matcher = config.LocationMatcher(store, 'dir/subdir')
 
3414
        sections = list(matcher.get_sections())
 
3415
        self.assertLength(1, sections)
 
3416
        self.assertEquals('bar/dir/subdir', sections[0][1].get('foo'))
 
3417
 
 
3418
    def test_file_urls_are_normalized(self):
 
3419
        store = self.get_store(self)
 
3420
        if sys.platform == 'win32':
 
3421
            expected_url = 'file:///C:/dir/subdir'
 
3422
            expected_location = 'C:/dir/subdir'
 
3423
        else:
 
3424
            expected_url = 'file:///dir/subdir'
 
3425
            expected_location = '/dir/subdir'
 
3426
        matcher = config.LocationMatcher(store, expected_url)
 
3427
        self.assertEquals(expected_location, matcher.location)
 
3428
 
 
3429
 
 
3430
class TestStartingPathMatcher(TestStore):
 
3431
 
 
3432
    def setUp(self):
 
3433
        super(TestStartingPathMatcher, self).setUp()
 
3434
        # Any simple store is good enough
 
3435
        self.store = config.IniFileStore()
 
3436
 
 
3437
    def assertSectionIDs(self, expected, location, content):
 
3438
        self.store._load_from_string(content)
 
3439
        matcher = config.StartingPathMatcher(self.store, location)
 
3440
        sections = list(matcher.get_sections())
 
3441
        self.assertLength(len(expected), sections)
 
3442
        self.assertEqual(expected, [section.id for _, section in sections])
 
3443
        return sections
 
3444
 
 
3445
    def test_empty(self):
 
3446
        self.assertSectionIDs([], self.get_url(), '')
 
3447
 
 
3448
    def test_url_vs_local_paths(self):
 
3449
        # The matcher location is an url and the section names are local paths
 
3450
        sections = self.assertSectionIDs(['/foo/bar', '/foo'],
 
3451
                                         'file:///foo/bar/baz', '''\
 
3452
[/foo]
 
3453
[/foo/bar]
 
3454
''')
 
3455
 
 
3456
    def test_local_path_vs_url(self):
 
3457
        # The matcher location is a local path and the section names are urls
 
3458
        sections = self.assertSectionIDs(['file:///foo/bar', 'file:///foo'],
 
3459
                                         '/foo/bar/baz', '''\
 
3460
[file:///foo]
 
3461
[file:///foo/bar]
 
3462
''')
 
3463
 
 
3464
 
 
3465
    def test_no_name_section_included_when_present(self):
 
3466
        # Note that other tests will cover the case where the no-name section
 
3467
        # is empty and as such, not included.
 
3468
        sections = self.assertSectionIDs(['/foo/bar', '/foo', None],
 
3469
                                         '/foo/bar/baz', '''\
 
3470
option = defined so the no-name section exists
 
3471
[/foo]
 
3472
[/foo/bar]
 
3473
''')
 
3474
        self.assertEquals(['baz', 'bar/baz', '/foo/bar/baz'],
 
3475
                          [s.locals['relpath'] for _, s in sections])
 
3476
 
 
3477
    def test_order_reversed(self):
 
3478
        self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
 
3479
[/foo]
 
3480
[/foo/bar]
 
3481
''')
 
3482
 
 
3483
    def test_unrelated_section_excluded(self):
 
3484
        self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
 
3485
[/foo]
 
3486
[/foo/qux]
 
3487
[/foo/bar]
 
3488
''')
 
3489
 
 
3490
    def test_glob_included(self):
 
3491
        sections = self.assertSectionIDs(['/foo/*/baz', '/foo/b*', '/foo'],
 
3492
                                         '/foo/bar/baz', '''\
 
3493
[/foo]
 
3494
[/foo/qux]
 
3495
[/foo/b*]
 
3496
[/foo/*/baz]
 
3497
''')
 
3498
        # Note that 'baz' as a relpath for /foo/b* is not fully correct, but
 
3499
        # nothing really is... as far using {relpath} to append it to something
 
3500
        # else, this seems good enough though.
 
3501
        self.assertEquals(['', 'baz', 'bar/baz'],
 
3502
                          [s.locals['relpath'] for _, s in sections])
 
3503
 
 
3504
    def test_respect_order(self):
 
3505
        self.assertSectionIDs(['/foo', '/foo/b*', '/foo/*/baz'],
 
3506
                              '/foo/bar/baz', '''\
 
3507
[/foo/*/baz]
 
3508
[/foo/qux]
 
3509
[/foo/b*]
 
3510
[/foo]
 
3511
''')
 
3512
 
 
3513
 
 
3514
class TestNameMatcher(TestStore):
 
3515
 
 
3516
    def setUp(self):
 
3517
        super(TestNameMatcher, self).setUp()
 
3518
        self.matcher = config.NameMatcher
 
3519
        # Any simple store is good enough
 
3520
        self.get_store = config.test_store_builder_registry.get('configobj')
 
3521
 
 
3522
    def get_matching_sections(self, name):
 
3523
        store = self.get_store(self)
 
3524
        store._load_from_string('''
 
3525
[foo]
 
3526
option=foo
 
3527
[foo/baz]
 
3528
option=foo/baz
 
3529
[bar]
 
3530
option=bar
 
3531
''')
 
3532
        matcher = self.matcher(store, name)
 
3533
        return list(matcher.get_sections())
 
3534
 
 
3535
    def test_matching(self):
 
3536
        sections = self.get_matching_sections('foo')
 
3537
        self.assertLength(1, sections)
 
3538
        self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
 
3539
 
 
3540
    def test_not_matching(self):
 
3541
        sections = self.get_matching_sections('baz')
 
3542
        self.assertLength(0, sections)
 
3543
 
 
3544
 
 
3545
class TestBaseStackGet(tests.TestCase):
 
3546
 
 
3547
    def setUp(self):
 
3548
        super(TestBaseStackGet, self).setUp()
 
3549
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3550
 
 
3551
    def test_get_first_definition(self):
 
3552
        store1 = config.IniFileStore()
 
3553
        store1._load_from_string('foo=bar')
 
3554
        store2 = config.IniFileStore()
 
3555
        store2._load_from_string('foo=baz')
 
3556
        conf = config.Stack([store1.get_sections, store2.get_sections])
 
3557
        self.assertEquals('bar', conf.get('foo'))
 
3558
 
 
3559
    def test_get_with_registered_default_value(self):
 
3560
        config.option_registry.register(config.Option('foo', default='bar'))
 
3561
        conf_stack = config.Stack([])
 
3562
        self.assertEquals('bar', conf_stack.get('foo'))
 
3563
 
 
3564
    def test_get_without_registered_default_value(self):
 
3565
        config.option_registry.register(config.Option('foo'))
 
3566
        conf_stack = config.Stack([])
 
3567
        self.assertEquals(None, conf_stack.get('foo'))
 
3568
 
 
3569
    def test_get_without_default_value_for_not_registered(self):
 
3570
        conf_stack = config.Stack([])
 
3571
        self.assertEquals(None, conf_stack.get('foo'))
 
3572
 
 
3573
    def test_get_for_empty_section_callable(self):
 
3574
        conf_stack = config.Stack([lambda : []])
 
3575
        self.assertEquals(None, conf_stack.get('foo'))
 
3576
 
 
3577
    def test_get_for_broken_callable(self):
 
3578
        # Trying to use and invalid callable raises an exception on first use
 
3579
        conf_stack = config.Stack([object])
 
3580
        self.assertRaises(TypeError, conf_stack.get, 'foo')
 
3581
 
 
3582
 
 
3583
class TestStackWithSimpleStore(tests.TestCase):
 
3584
 
 
3585
    def setUp(self):
 
3586
        super(TestStackWithSimpleStore, self).setUp()
 
3587
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3588
        self.registry = config.option_registry
 
3589
 
 
3590
    def get_conf(self, content=None):
 
3591
        return config.MemoryStack(content)
 
3592
 
 
3593
    def test_override_value_from_env(self):
 
3594
        self.registry.register(
 
3595
            config.Option('foo', default='bar', override_from_env=['FOO']))
 
3596
        self.overrideEnv('FOO', 'quux')
 
3597
        # Env variable provides a default taking over the option one
 
3598
        conf = self.get_conf('foo=store')
 
3599
        self.assertEquals('quux', conf.get('foo'))
 
3600
 
 
3601
    def test_first_override_value_from_env_wins(self):
 
3602
        self.registry.register(
 
3603
            config.Option('foo', default='bar',
 
3604
                          override_from_env=['NO_VALUE', 'FOO', 'BAZ']))
 
3605
        self.overrideEnv('FOO', 'foo')
 
3606
        self.overrideEnv('BAZ', 'baz')
 
3607
        # The first env var set wins
 
3608
        conf = self.get_conf('foo=store')
 
3609
        self.assertEquals('foo', conf.get('foo'))
 
3610
 
 
3611
 
 
3612
class TestMemoryStack(tests.TestCase):
 
3613
 
 
3614
    def test_get(self):
 
3615
        conf = config.MemoryStack('foo=bar')
 
3616
        self.assertEquals('bar', conf.get('foo'))
 
3617
 
 
3618
    def test_set(self):
 
3619
        conf = config.MemoryStack('foo=bar')
 
3620
        conf.set('foo', 'baz')
 
3621
        self.assertEquals('baz', conf.get('foo'))
 
3622
 
 
3623
    def test_no_content(self):
 
3624
        conf = config.MemoryStack()
 
3625
        # No content means no loading
 
3626
        self.assertFalse(conf.store.is_loaded())
 
3627
        self.assertRaises(NotImplementedError, conf.get, 'foo')
 
3628
        # But a content can still be provided
 
3629
        conf.store._load_from_string('foo=bar')
 
3630
        self.assertEquals('bar', conf.get('foo'))
 
3631
 
 
3632
 
 
3633
class TestStackWithTransport(tests.TestCaseWithTransport):
 
3634
 
 
3635
    scenarios = [(key, {'get_stack': builder}) for key, builder
 
3636
                 in config.test_stack_builder_registry.iteritems()]
 
3637
 
 
3638
 
 
3639
class TestConcreteStacks(TestStackWithTransport):
 
3640
 
 
3641
    def test_build_stack(self):
 
3642
        # Just a smoke test to help debug builders
 
3643
        stack = self.get_stack(self)
 
3644
 
 
3645
 
 
3646
class TestStackGet(TestStackWithTransport):
 
3647
 
 
3648
    def setUp(self):
 
3649
        super(TestStackGet, self).setUp()
 
3650
        self.conf = self.get_stack(self)
 
3651
 
 
3652
    def test_get_for_empty_stack(self):
 
3653
        self.assertEquals(None, self.conf.get('foo'))
 
3654
 
 
3655
    def test_get_hook(self):
 
3656
        self.conf.set('foo', 'bar')
 
3657
        calls = []
 
3658
        def hook(*args):
 
3659
            calls.append(args)
 
3660
        config.ConfigHooks.install_named_hook('get', hook, None)
 
3661
        self.assertLength(0, calls)
 
3662
        value = self.conf.get('foo')
 
3663
        self.assertEquals('bar', value)
 
3664
        self.assertLength(1, calls)
 
3665
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
 
3666
 
 
3667
 
 
3668
class TestStackGetWithConverter(tests.TestCase):
 
3669
 
 
3670
    def setUp(self):
 
3671
        super(TestStackGetWithConverter, self).setUp()
 
3672
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3673
        self.registry = config.option_registry
 
3674
 
 
3675
    def get_conf(self, content=None):
 
3676
        return config.MemoryStack(content)
 
3677
 
 
3678
    def register_bool_option(self, name, default=None, default_from_env=None):
 
3679
        b = config.Option(name, help='A boolean.',
 
3680
                          default=default, default_from_env=default_from_env,
 
3681
                          from_unicode=config.bool_from_store)
 
3682
        self.registry.register(b)
 
3683
 
 
3684
    def test_get_default_bool_None(self):
 
3685
        self.register_bool_option('foo')
 
3686
        conf = self.get_conf('')
 
3687
        self.assertEquals(None, conf.get('foo'))
 
3688
 
 
3689
    def test_get_default_bool_True(self):
 
3690
        self.register_bool_option('foo', u'True')
 
3691
        conf = self.get_conf('')
 
3692
        self.assertEquals(True, conf.get('foo'))
 
3693
 
 
3694
    def test_get_default_bool_False(self):
 
3695
        self.register_bool_option('foo', False)
 
3696
        conf = self.get_conf('')
 
3697
        self.assertEquals(False, conf.get('foo'))
 
3698
 
 
3699
    def test_get_default_bool_False_as_string(self):
 
3700
        self.register_bool_option('foo', u'False')
 
3701
        conf = self.get_conf('')
 
3702
        self.assertEquals(False, conf.get('foo'))
 
3703
 
 
3704
    def test_get_default_bool_from_env_converted(self):
 
3705
        self.register_bool_option('foo', u'True', default_from_env=['FOO'])
 
3706
        self.overrideEnv('FOO', 'False')
 
3707
        conf = self.get_conf('')
 
3708
        self.assertEquals(False, conf.get('foo'))
 
3709
 
 
3710
    def test_get_default_bool_when_conversion_fails(self):
 
3711
        self.register_bool_option('foo', default='True')
 
3712
        conf = self.get_conf('foo=invalid boolean')
 
3713
        self.assertEquals(True, conf.get('foo'))
 
3714
 
 
3715
    def register_integer_option(self, name,
 
3716
                                default=None, default_from_env=None):
 
3717
        i = config.Option(name, help='An integer.',
 
3718
                          default=default, default_from_env=default_from_env,
 
3719
                          from_unicode=config.int_from_store)
 
3720
        self.registry.register(i)
 
3721
 
 
3722
    def test_get_default_integer_None(self):
 
3723
        self.register_integer_option('foo')
 
3724
        conf = self.get_conf('')
 
3725
        self.assertEquals(None, conf.get('foo'))
 
3726
 
 
3727
    def test_get_default_integer(self):
 
3728
        self.register_integer_option('foo', 42)
 
3729
        conf = self.get_conf('')
 
3730
        self.assertEquals(42, conf.get('foo'))
 
3731
 
 
3732
    def test_get_default_integer_as_string(self):
 
3733
        self.register_integer_option('foo', u'42')
 
3734
        conf = self.get_conf('')
 
3735
        self.assertEquals(42, conf.get('foo'))
 
3736
 
 
3737
    def test_get_default_integer_from_env(self):
 
3738
        self.register_integer_option('foo', default_from_env=['FOO'])
 
3739
        self.overrideEnv('FOO', '18')
 
3740
        conf = self.get_conf('')
 
3741
        self.assertEquals(18, conf.get('foo'))
 
3742
 
 
3743
    def test_get_default_integer_when_conversion_fails(self):
 
3744
        self.register_integer_option('foo', default='12')
 
3745
        conf = self.get_conf('foo=invalid integer')
 
3746
        self.assertEquals(12, conf.get('foo'))
 
3747
 
 
3748
    def register_list_option(self, name, default=None, default_from_env=None):
 
3749
        l = config.ListOption(name, help='A list.', default=default,
 
3750
                              default_from_env=default_from_env)
 
3751
        self.registry.register(l)
 
3752
 
 
3753
    def test_get_default_list_None(self):
 
3754
        self.register_list_option('foo')
 
3755
        conf = self.get_conf('')
 
3756
        self.assertEquals(None, conf.get('foo'))
 
3757
 
 
3758
    def test_get_default_list_empty(self):
 
3759
        self.register_list_option('foo', '')
 
3760
        conf = self.get_conf('')
 
3761
        self.assertEquals([], conf.get('foo'))
 
3762
 
 
3763
    def test_get_default_list_from_env(self):
 
3764
        self.register_list_option('foo', default_from_env=['FOO'])
 
3765
        self.overrideEnv('FOO', '')
 
3766
        conf = self.get_conf('')
 
3767
        self.assertEquals([], conf.get('foo'))
 
3768
 
 
3769
    def test_get_with_list_converter_no_item(self):
 
3770
        self.register_list_option('foo', None)
 
3771
        conf = self.get_conf('foo=,')
 
3772
        self.assertEquals([], conf.get('foo'))
 
3773
 
 
3774
    def test_get_with_list_converter_many_items(self):
 
3775
        self.register_list_option('foo', None)
 
3776
        conf = self.get_conf('foo=m,o,r,e')
 
3777
        self.assertEquals(['m', 'o', 'r', 'e'], conf.get('foo'))
 
3778
 
 
3779
    def test_get_with_list_converter_embedded_spaces_many_items(self):
 
3780
        self.register_list_option('foo', None)
 
3781
        conf = self.get_conf('foo=" bar", "baz "')
 
3782
        self.assertEquals([' bar', 'baz '], conf.get('foo'))
 
3783
 
 
3784
    def test_get_with_list_converter_stripped_spaces_many_items(self):
 
3785
        self.register_list_option('foo', None)
 
3786
        conf = self.get_conf('foo= bar ,  baz ')
 
3787
        self.assertEquals(['bar', 'baz'], conf.get('foo'))
 
3788
 
 
3789
 
 
3790
class TestIterOptionRefs(tests.TestCase):
 
3791
    """iter_option_refs is a bit unusual, document some cases."""
 
3792
 
 
3793
    def assertRefs(self, expected, string):
 
3794
        self.assertEquals(expected, list(config.iter_option_refs(string)))
 
3795
 
 
3796
    def test_empty(self):
 
3797
        self.assertRefs([(False, '')], '')
 
3798
 
 
3799
    def test_no_refs(self):
 
3800
        self.assertRefs([(False, 'foo bar')], 'foo bar')
 
3801
 
 
3802
    def test_single_ref(self):
 
3803
        self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
 
3804
 
 
3805
    def test_broken_ref(self):
 
3806
        self.assertRefs([(False, '{foo')], '{foo')
 
3807
 
 
3808
    def test_embedded_ref(self):
 
3809
        self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
 
3810
                        '{{foo}}')
 
3811
 
 
3812
    def test_two_refs(self):
 
3813
        self.assertRefs([(False, ''), (True, '{foo}'),
 
3814
                         (False, ''), (True, '{bar}'),
 
3815
                         (False, ''),],
 
3816
                        '{foo}{bar}')
 
3817
 
 
3818
    def test_newline_in_refs_are_not_matched(self):
 
3819
        self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
 
3820
 
 
3821
 
 
3822
class TestStackExpandOptions(tests.TestCaseWithTransport):
 
3823
 
 
3824
    def setUp(self):
 
3825
        super(TestStackExpandOptions, self).setUp()
 
3826
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3827
        self.registry = config.option_registry
 
3828
        self.conf = build_branch_stack(self)
 
3829
 
 
3830
    def assertExpansion(self, expected, string, env=None):
 
3831
        self.assertEquals(expected, self.conf.expand_options(string, env))
 
3832
 
 
3833
    def test_no_expansion(self):
 
3834
        self.assertExpansion('foo', 'foo')
 
3835
 
 
3836
    def test_expand_default_value(self):
 
3837
        self.conf.store._load_from_string('bar=baz')
 
3838
        self.registry.register(config.Option('foo', default=u'{bar}'))
 
3839
        self.assertEquals('baz', self.conf.get('foo', expand=True))
 
3840
 
 
3841
    def test_expand_default_from_env(self):
 
3842
        self.conf.store._load_from_string('bar=baz')
 
3843
        self.registry.register(config.Option('foo', default_from_env=['FOO']))
 
3844
        self.overrideEnv('FOO', '{bar}')
 
3845
        self.assertEquals('baz', self.conf.get('foo', expand=True))
 
3846
 
 
3847
    def test_expand_default_on_failed_conversion(self):
 
3848
        self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
 
3849
        self.registry.register(
 
3850
            config.Option('foo', default=u'{bar}',
 
3851
                          from_unicode=config.int_from_store))
 
3852
        self.assertEquals(42, self.conf.get('foo', expand=True))
 
3853
 
 
3854
    def test_env_adding_options(self):
 
3855
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
 
3856
 
 
3857
    def test_env_overriding_options(self):
 
3858
        self.conf.store._load_from_string('foo=baz')
 
3859
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
 
3860
 
 
3861
    def test_simple_ref(self):
 
3862
        self.conf.store._load_from_string('foo=xxx')
 
3863
        self.assertExpansion('xxx', '{foo}')
 
3864
 
 
3865
    def test_unknown_ref(self):
 
3866
        self.assertRaises(errors.ExpandingUnknownOption,
 
3867
                          self.conf.expand_options, '{foo}')
 
3868
 
 
3869
    def test_indirect_ref(self):
 
3870
        self.conf.store._load_from_string('''
 
3871
foo=xxx
 
3872
bar={foo}
 
3873
''')
 
3874
        self.assertExpansion('xxx', '{bar}')
 
3875
 
 
3876
    def test_embedded_ref(self):
 
3877
        self.conf.store._load_from_string('''
 
3878
foo=xxx
 
3879
bar=foo
 
3880
''')
 
3881
        self.assertExpansion('xxx', '{{bar}}')
 
3882
 
 
3883
    def test_simple_loop(self):
 
3884
        self.conf.store._load_from_string('foo={foo}')
 
3885
        self.assertRaises(errors.OptionExpansionLoop,
 
3886
                          self.conf.expand_options, '{foo}')
 
3887
 
 
3888
    def test_indirect_loop(self):
 
3889
        self.conf.store._load_from_string('''
 
3890
foo={bar}
 
3891
bar={baz}
 
3892
baz={foo}''')
 
3893
        e = self.assertRaises(errors.OptionExpansionLoop,
 
3894
                              self.conf.expand_options, '{foo}')
 
3895
        self.assertEquals('foo->bar->baz', e.refs)
 
3896
        self.assertEquals('{foo}', e.string)
 
3897
 
 
3898
    def test_list(self):
 
3899
        self.conf.store._load_from_string('''
 
3900
foo=start
 
3901
bar=middle
 
3902
baz=end
 
3903
list={foo},{bar},{baz}
 
3904
''')
 
3905
        self.registry.register(
 
3906
            config.ListOption('list'))
 
3907
        self.assertEquals(['start', 'middle', 'end'],
 
3908
                           self.conf.get('list', expand=True))
 
3909
 
 
3910
    def test_cascading_list(self):
 
3911
        self.conf.store._load_from_string('''
 
3912
foo=start,{bar}
 
3913
bar=middle,{baz}
 
3914
baz=end
 
3915
list={foo}
 
3916
''')
 
3917
        self.registry.register(
 
3918
            config.ListOption('list'))
 
3919
        self.assertEquals(['start', 'middle', 'end'],
 
3920
                           self.conf.get('list', expand=True))
 
3921
 
 
3922
    def test_pathologically_hidden_list(self):
 
3923
        self.conf.store._load_from_string('''
 
3924
foo=bin
 
3925
bar=go
 
3926
start={foo
 
3927
middle=},{
 
3928
end=bar}
 
3929
hidden={start}{middle}{end}
 
3930
''')
 
3931
        # What matters is what the registration says, the conversion happens
 
3932
        # only after all expansions have been performed
 
3933
        self.registry.register(config.ListOption('hidden'))
 
3934
        self.assertEquals(['bin', 'go'],
 
3935
                          self.conf.get('hidden', expand=True))
 
3936
 
 
3937
 
 
3938
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
 
3939
 
 
3940
    def setUp(self):
 
3941
        super(TestStackCrossSectionsExpand, self).setUp()
 
3942
 
 
3943
    def get_config(self, location, string):
 
3944
        if string is None:
 
3945
            string = ''
 
3946
        # Since we don't save the config we won't strictly require to inherit
 
3947
        # from TestCaseInTempDir, but an error occurs so quickly...
 
3948
        c = config.LocationStack(location)
 
3949
        c.store._load_from_string(string)
 
3950
        return c
 
3951
 
 
3952
    def test_dont_cross_unrelated_section(self):
 
3953
        c = self.get_config('/another/branch/path','''
 
3954
[/one/branch/path]
 
3955
foo = hello
 
3956
bar = {foo}/2
 
3957
 
 
3958
[/another/branch/path]
 
3959
bar = {foo}/2
 
3960
''')
 
3961
        self.assertRaises(errors.ExpandingUnknownOption,
 
3962
                          c.get, 'bar', expand=True)
 
3963
 
 
3964
    def test_cross_related_sections(self):
 
3965
        c = self.get_config('/project/branch/path','''
 
3966
[/project]
 
3967
foo = qu
 
3968
 
 
3969
[/project/branch/path]
 
3970
bar = {foo}ux
 
3971
''')
 
3972
        self.assertEquals('quux', c.get('bar', expand=True))
 
3973
 
 
3974
 
 
3975
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
 
3976
 
 
3977
    def test_cross_global_locations(self):
 
3978
        l_store = config.LocationStore()
 
3979
        l_store._load_from_string('''
 
3980
[/branch]
 
3981
lfoo = loc-foo
 
3982
lbar = {gbar}
 
3983
''')
 
3984
        l_store.save()
 
3985
        g_store = config.GlobalStore()
 
3986
        g_store._load_from_string('''
 
3987
[DEFAULT]
 
3988
gfoo = {lfoo}
 
3989
gbar = glob-bar
 
3990
''')
 
3991
        g_store.save()
 
3992
        stack = config.LocationStack('/branch')
 
3993
        self.assertEquals('glob-bar', stack.get('lbar', expand=True))
 
3994
        self.assertEquals('loc-foo', stack.get('gfoo', expand=True))
 
3995
 
 
3996
 
 
3997
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
 
3998
 
 
3999
    def test_expand_locals_empty(self):
 
4000
        l_store = config.LocationStore()
 
4001
        l_store._load_from_string('''
 
4002
[/home/user/project]
 
4003
base = {basename}
 
4004
rel = {relpath}
 
4005
''')
 
4006
        l_store.save()
 
4007
        stack = config.LocationStack('/home/user/project/')
 
4008
        self.assertEquals('', stack.get('base', expand=True))
 
4009
        self.assertEquals('', stack.get('rel', expand=True))
 
4010
 
 
4011
    def test_expand_basename_locally(self):
 
4012
        l_store = config.LocationStore()
 
4013
        l_store._load_from_string('''
 
4014
[/home/user/project]
 
4015
bfoo = {basename}
 
4016
''')
 
4017
        l_store.save()
 
4018
        stack = config.LocationStack('/home/user/project/branch')
 
4019
        self.assertEquals('branch', stack.get('bfoo', expand=True))
 
4020
 
 
4021
    def test_expand_basename_locally_longer_path(self):
 
4022
        l_store = config.LocationStore()
 
4023
        l_store._load_from_string('''
 
4024
[/home/user]
 
4025
bfoo = {basename}
 
4026
''')
 
4027
        l_store.save()
 
4028
        stack = config.LocationStack('/home/user/project/dir/branch')
 
4029
        self.assertEquals('branch', stack.get('bfoo', expand=True))
 
4030
 
 
4031
    def test_expand_relpath_locally(self):
 
4032
        l_store = config.LocationStore()
 
4033
        l_store._load_from_string('''
 
4034
[/home/user/project]
 
4035
lfoo = loc-foo/{relpath}
 
4036
''')
 
4037
        l_store.save()
 
4038
        stack = config.LocationStack('/home/user/project/branch')
 
4039
        self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
 
4040
 
 
4041
    def test_expand_relpath_unknonw_in_global(self):
 
4042
        g_store = config.GlobalStore()
 
4043
        g_store._load_from_string('''
 
4044
[DEFAULT]
 
4045
gfoo = {relpath}
 
4046
''')
 
4047
        g_store.save()
 
4048
        stack = config.LocationStack('/home/user/project/branch')
 
4049
        self.assertRaises(errors.ExpandingUnknownOption,
 
4050
                          stack.get, 'gfoo', expand=True)
 
4051
 
 
4052
    def test_expand_local_option_locally(self):
 
4053
        l_store = config.LocationStore()
 
4054
        l_store._load_from_string('''
 
4055
[/home/user/project]
 
4056
lfoo = loc-foo/{relpath}
 
4057
lbar = {gbar}
 
4058
''')
 
4059
        l_store.save()
 
4060
        g_store = config.GlobalStore()
 
4061
        g_store._load_from_string('''
 
4062
[DEFAULT]
 
4063
gfoo = {lfoo}
 
4064
gbar = glob-bar
 
4065
''')
 
4066
        g_store.save()
 
4067
        stack = config.LocationStack('/home/user/project/branch')
 
4068
        self.assertEquals('glob-bar', stack.get('lbar', expand=True))
 
4069
        self.assertEquals('loc-foo/branch', stack.get('gfoo', expand=True))
 
4070
 
 
4071
    def test_locals_dont_leak(self):
 
4072
        """Make sure we chose the right local in presence of several sections.
 
4073
        """
 
4074
        l_store = config.LocationStore()
 
4075
        l_store._load_from_string('''
 
4076
[/home/user]
 
4077
lfoo = loc-foo/{relpath}
 
4078
[/home/user/project]
 
4079
lfoo = loc-foo/{relpath}
 
4080
''')
 
4081
        l_store.save()
 
4082
        stack = config.LocationStack('/home/user/project/branch')
 
4083
        self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
 
4084
        stack = config.LocationStack('/home/user/bar/baz')
 
4085
        self.assertEquals('loc-foo/bar/baz', stack.get('lfoo', expand=True))
 
4086
 
 
4087
 
 
4088
 
 
4089
class TestStackSet(TestStackWithTransport):
 
4090
 
 
4091
    def test_simple_set(self):
 
4092
        conf = self.get_stack(self)
 
4093
        self.assertEquals(None, conf.get('foo'))
 
4094
        conf.set('foo', 'baz')
 
4095
        # Did we get it back ?
 
4096
        self.assertEquals('baz', conf.get('foo'))
 
4097
 
 
4098
    def test_set_creates_a_new_section(self):
 
4099
        conf = self.get_stack(self)
 
4100
        conf.set('foo', 'baz')
 
4101
        self.assertEquals, 'baz', conf.get('foo')
 
4102
 
 
4103
    def test_set_hook(self):
 
4104
        calls = []
 
4105
        def hook(*args):
 
4106
            calls.append(args)
 
4107
        config.ConfigHooks.install_named_hook('set', hook, None)
 
4108
        self.assertLength(0, calls)
 
4109
        conf = self.get_stack(self)
 
4110
        conf.set('foo', 'bar')
 
4111
        self.assertLength(1, calls)
 
4112
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
 
4113
 
 
4114
 
 
4115
class TestStackRemove(TestStackWithTransport):
 
4116
 
 
4117
    def test_remove_existing(self):
 
4118
        conf = self.get_stack(self)
 
4119
        conf.set('foo', 'bar')
 
4120
        self.assertEquals('bar', conf.get('foo'))
 
4121
        conf.remove('foo')
 
4122
        # Did we get it back ?
 
4123
        self.assertEquals(None, conf.get('foo'))
 
4124
 
 
4125
    def test_remove_unknown(self):
 
4126
        conf = self.get_stack(self)
 
4127
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
 
4128
 
 
4129
    def test_remove_hook(self):
 
4130
        calls = []
 
4131
        def hook(*args):
 
4132
            calls.append(args)
 
4133
        config.ConfigHooks.install_named_hook('remove', hook, None)
 
4134
        self.assertLength(0, calls)
 
4135
        conf = self.get_stack(self)
 
4136
        conf.set('foo', 'bar')
 
4137
        conf.remove('foo')
 
4138
        self.assertLength(1, calls)
 
4139
        self.assertEquals((conf, 'foo'), calls[0])
 
4140
 
 
4141
 
 
4142
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
 
4143
 
 
4144
    def setUp(self):
 
4145
        super(TestConfigGetOptions, self).setUp()
 
4146
        create_configs(self)
 
4147
 
 
4148
    def test_no_variable(self):
 
4149
        # Using branch should query branch, locations and bazaar
 
4150
        self.assertOptions([], self.branch_config)
 
4151
 
 
4152
    def test_option_in_bazaar(self):
 
4153
        self.bazaar_config.set_user_option('file', 'bazaar')
 
4154
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
 
4155
                           self.bazaar_config)
 
4156
 
 
4157
    def test_option_in_locations(self):
 
4158
        self.locations_config.set_user_option('file', 'locations')
 
4159
        self.assertOptions(
 
4160
            [('file', 'locations', self.tree.basedir, 'locations')],
 
4161
            self.locations_config)
 
4162
 
 
4163
    def test_option_in_branch(self):
 
4164
        self.branch_config.set_user_option('file', 'branch')
 
4165
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
 
4166
                           self.branch_config)
 
4167
 
 
4168
    def test_option_in_bazaar_and_branch(self):
 
4169
        self.bazaar_config.set_user_option('file', 'bazaar')
 
4170
        self.branch_config.set_user_option('file', 'branch')
 
4171
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
 
4172
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
4173
                           self.branch_config)
 
4174
 
 
4175
    def test_option_in_branch_and_locations(self):
 
4176
        # Hmm, locations override branch :-/
 
4177
        self.locations_config.set_user_option('file', 'locations')
 
4178
        self.branch_config.set_user_option('file', 'branch')
 
4179
        self.assertOptions(
 
4180
            [('file', 'locations', self.tree.basedir, 'locations'),
 
4181
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
4182
            self.branch_config)
 
4183
 
 
4184
    def test_option_in_bazaar_locations_and_branch(self):
 
4185
        self.bazaar_config.set_user_option('file', 'bazaar')
 
4186
        self.locations_config.set_user_option('file', 'locations')
 
4187
        self.branch_config.set_user_option('file', 'branch')
 
4188
        self.assertOptions(
 
4189
            [('file', 'locations', self.tree.basedir, 'locations'),
 
4190
             ('file', 'branch', 'DEFAULT', 'branch'),
 
4191
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
4192
            self.branch_config)
 
4193
 
 
4194
 
 
4195
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
 
4196
 
 
4197
    def setUp(self):
 
4198
        super(TestConfigRemoveOption, self).setUp()
 
4199
        create_configs_with_file_option(self)
 
4200
 
 
4201
    def test_remove_in_locations(self):
 
4202
        self.locations_config.remove_user_option('file', self.tree.basedir)
 
4203
        self.assertOptions(
 
4204
            [('file', 'branch', 'DEFAULT', 'branch'),
 
4205
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
4206
            self.branch_config)
 
4207
 
 
4208
    def test_remove_in_branch(self):
 
4209
        self.branch_config.remove_user_option('file')
 
4210
        self.assertOptions(
 
4211
            [('file', 'locations', self.tree.basedir, 'locations'),
 
4212
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
4213
            self.branch_config)
 
4214
 
 
4215
    def test_remove_in_bazaar(self):
 
4216
        self.bazaar_config.remove_user_option('file')
 
4217
        self.assertOptions(
 
4218
            [('file', 'locations', self.tree.basedir, 'locations'),
 
4219
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
4220
            self.branch_config)
 
4221
 
 
4222
 
 
4223
class TestConfigGetSections(tests.TestCaseWithTransport):
 
4224
 
 
4225
    def setUp(self):
 
4226
        super(TestConfigGetSections, self).setUp()
 
4227
        create_configs(self)
 
4228
 
 
4229
    def assertSectionNames(self, expected, conf, name=None):
 
4230
        """Check which sections are returned for a given config.
 
4231
 
 
4232
        If fallback configurations exist their sections can be included.
 
4233
 
 
4234
        :param expected: A list of section names.
 
4235
 
 
4236
        :param conf: The configuration that will be queried.
 
4237
 
 
4238
        :param name: An optional section name that will be passed to
 
4239
            get_sections().
 
4240
        """
 
4241
        sections = list(conf._get_sections(name))
 
4242
        self.assertLength(len(expected), sections)
 
4243
        self.assertEqual(expected, [name for name, _, _ in sections])
 
4244
 
 
4245
    def test_bazaar_default_section(self):
 
4246
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
 
4247
 
 
4248
    def test_locations_default_section(self):
 
4249
        # No sections are defined in an empty file
 
4250
        self.assertSectionNames([], self.locations_config)
 
4251
 
 
4252
    def test_locations_named_section(self):
 
4253
        self.locations_config.set_user_option('file', 'locations')
 
4254
        self.assertSectionNames([self.tree.basedir], self.locations_config)
 
4255
 
 
4256
    def test_locations_matching_sections(self):
 
4257
        loc_config = self.locations_config
 
4258
        loc_config.set_user_option('file', 'locations')
 
4259
        # We need to cheat a bit here to create an option in sections above and
 
4260
        # below the 'location' one.
 
4261
        parser = loc_config._get_parser()
 
4262
        # locations.cong deals with '/' ignoring native os.sep
 
4263
        location_names = self.tree.basedir.split('/')
 
4264
        parent = '/'.join(location_names[:-1])
 
4265
        child = '/'.join(location_names + ['child'])
 
4266
        parser[parent] = {}
 
4267
        parser[parent]['file'] = 'parent'
 
4268
        parser[child] = {}
 
4269
        parser[child]['file'] = 'child'
 
4270
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
 
4271
 
 
4272
    def test_branch_data_default_section(self):
 
4273
        self.assertSectionNames([None],
 
4274
                                self.branch_config._get_branch_data_config())
 
4275
 
 
4276
    def test_branch_default_sections(self):
 
4277
        # No sections are defined in an empty locations file
 
4278
        self.assertSectionNames([None, 'DEFAULT'],
 
4279
                                self.branch_config)
 
4280
        # Unless we define an option
 
4281
        self.branch_config._get_location_config().set_user_option(
 
4282
            'file', 'locations')
 
4283
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
 
4284
                                self.branch_config)
 
4285
 
 
4286
    def test_bazaar_named_section(self):
 
4287
        # We need to cheat as the API doesn't give direct access to sections
 
4288
        # other than DEFAULT.
 
4289
        self.bazaar_config.set_alias('bazaar', 'bzr')
 
4290
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
 
4291
 
 
4292
 
1474
4293
class TestAuthenticationConfigFile(tests.TestCase):
1475
4294
    """Test the authentication.conf file matching"""
1476
4295
 
1491
4310
        self.assertEquals({}, conf._get_config())
1492
4311
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1493
4312
 
 
4313
    def test_non_utf8_config(self):
 
4314
        conf = config.AuthenticationConfig(_file=StringIO(
 
4315
                'foo = bar\xff'))
 
4316
        self.assertRaises(errors.ConfigContentError, conf._get_config)
 
4317
 
1494
4318
    def test_missing_auth_section_header(self):
1495
4319
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1496
4320
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1754
4578
 
1755
4579
    def test_username_defaults_prompts(self):
1756
4580
        # 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)
 
4581
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
 
4582
        self._check_default_username_prompt(
 
4583
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
 
4584
        self._check_default_username_prompt(
 
4585
            u'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1762
4586
 
1763
4587
    def test_username_default_no_prompt(self):
1764
4588
        conf = config.AuthenticationConfig()
1770
4594
    def test_password_default_prompts(self):
1771
4595
        # HTTP prompts can't be tested here, see test_http.py
1772
4596
        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)
 
4597
            u'FTP %(user)s@%(host)s password: ', 'ftp')
 
4598
        self._check_default_password_prompt(
 
4599
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
 
4600
        self._check_default_password_prompt(
 
4601
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
1778
4602
        # SMTP port handling is a bit special (it's handled if embedded in the
1779
4603
        # host too)
1780
4604
        # FIXME: should we: forbid that, extend it to other schemes, leave
1781
4605
        # 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)
 
4606
        self._check_default_password_prompt(
 
4607
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
 
4608
        self._check_default_password_prompt(
 
4609
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
 
4610
        self._check_default_password_prompt(
 
4611
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
1789
4612
 
1790
4613
    def test_ssh_password_emits_warning(self):
1791
4614
        conf = config.AuthenticationConfig(_file=StringIO(
1971
4794
# test_user_prompted ?
1972
4795
class TestAuthenticationRing(tests.TestCaseWithTransport):
1973
4796
    pass
 
4797
 
 
4798
 
 
4799
class TestAutoUserId(tests.TestCase):
 
4800
    """Test inferring an automatic user name."""
 
4801
 
 
4802
    def test_auto_user_id(self):
 
4803
        """Automatic inference of user name.
 
4804
 
 
4805
        This is a bit hard to test in an isolated way, because it depends on
 
4806
        system functions that go direct to /etc or perhaps somewhere else.
 
4807
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
 
4808
        to be able to choose a user name with no configuration.
 
4809
        """
 
4810
        if sys.platform == 'win32':
 
4811
            raise tests.TestSkipped(
 
4812
                "User name inference not implemented on win32")
 
4813
        realname, address = config._auto_user_id()
 
4814
        if os.path.exists('/etc/mailname'):
 
4815
            self.assertIsNot(None, realname)
 
4816
            self.assertIsNot(None, address)
 
4817
        else:
 
4818
            self.assertEquals((None, None), (realname, address))
 
4819
 
 
4820
 
 
4821
class EmailOptionTests(tests.TestCase):
 
4822
 
 
4823
    def test_default_email_uses_BZR_EMAIL(self):
 
4824
        conf = config.MemoryStack('email=jelmer@debian.org')
 
4825
        # BZR_EMAIL takes precedence over EMAIL
 
4826
        self.overrideEnv('BZR_EMAIL', 'jelmer@samba.org')
 
4827
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
 
4828
        self.assertEquals('jelmer@samba.org', conf.get('email'))
 
4829
 
 
4830
    def test_default_email_uses_EMAIL(self):
 
4831
        conf = config.MemoryStack('')
 
4832
        self.overrideEnv('BZR_EMAIL', None)
 
4833
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
 
4834
        self.assertEquals('jelmer@apache.org', conf.get('email'))
 
4835
 
 
4836
    def test_BZR_EMAIL_overrides(self):
 
4837
        conf = config.MemoryStack('email=jelmer@debian.org')
 
4838
        self.overrideEnv('BZR_EMAIL', 'jelmer@apache.org')
 
4839
        self.assertEquals('jelmer@apache.org', conf.get('email'))
 
4840
        self.overrideEnv('BZR_EMAIL', None)
 
4841
        self.overrideEnv('EMAIL', 'jelmer@samba.org')
 
4842
        self.assertEquals('jelmer@debian.org', conf.get('email'))