~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Jelmer Vernooij
  • Date: 2012-02-20 13:38:56 UTC
  • mto: (6437.23.12 2.5)
  • mto: This revision was merged to the branch mainline in revision 6473.
  • Revision ID: jelmer@samba.org-20120220133856-v6vh35o51n21v5ru
Cope with repository being missing in more cases.

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