/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-14 12:25:34 UTC
  • mto: (6282.6.42 hpss-get-inventories)
  • mto: This revision was merged to the branch mainline in revision 6371.
  • Revision ID: jelmer@samba.org-20111214122534-5ot01rv7miypacmf
More documentation.

Show diffs side-by-side

added added

removed removed

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