~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Ross Lagerwall
  • Date: 2012-08-07 06:32:51 UTC
  • mto: (6437.63.5 2.5)
  • mto: This revision was merged to the branch mainline in revision 6558.
  • Revision ID: rosslagerwall@gmail.com-20120807063251-x9p03ghg2ws8oqjc
Add bzrlib/locale to .bzrignore

bzrlib/locale is generated with ./setup.py build_mo which is in turn called
by ./setup.py build

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
    def test_get_help_topic(self):
 
2373
        opt = config.Option('foo')
 
2374
        self.assertEquals('foo', opt.get_help_topic())
 
2375
 
 
2376
 
 
2377
class TestOptionConverterMixin(object):
 
2378
 
 
2379
    def assertConverted(self, expected, opt, value):
 
2380
        self.assertEquals(expected, opt.convert_from_unicode(None, value))
 
2381
 
 
2382
    def assertWarns(self, opt, value):
 
2383
        warnings = []
 
2384
        def warning(*args):
 
2385
            warnings.append(args[0] % args[1:])
 
2386
        self.overrideAttr(trace, 'warning', warning)
 
2387
        self.assertEquals(None, opt.convert_from_unicode(None, value))
 
2388
        self.assertLength(1, warnings)
 
2389
        self.assertEquals(
 
2390
            'Value "%s" is not valid for "%s"' % (value, opt.name),
 
2391
            warnings[0])
 
2392
 
 
2393
    def assertErrors(self, opt, value):
 
2394
        self.assertRaises(errors.ConfigOptionValueError,
 
2395
                          opt.convert_from_unicode, None, value)
 
2396
 
 
2397
    def assertConvertInvalid(self, opt, invalid_value):
 
2398
        opt.invalid = None
 
2399
        self.assertEquals(None, opt.convert_from_unicode(None, invalid_value))
 
2400
        opt.invalid = 'warning'
 
2401
        self.assertWarns(opt, invalid_value)
 
2402
        opt.invalid = 'error'
 
2403
        self.assertErrors(opt, invalid_value)
 
2404
 
 
2405
 
 
2406
class TestOptionWithBooleanConverter(tests.TestCase, TestOptionConverterMixin):
 
2407
 
 
2408
    def get_option(self):
 
2409
        return config.Option('foo', help='A boolean.',
 
2410
                             from_unicode=config.bool_from_store)
 
2411
 
 
2412
    def test_convert_invalid(self):
 
2413
        opt = self.get_option()
 
2414
        # A string that is not recognized as a boolean
 
2415
        self.assertConvertInvalid(opt, u'invalid-boolean')
 
2416
        # A list of strings is never recognized as a boolean
 
2417
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
 
2418
 
 
2419
    def test_convert_valid(self):
 
2420
        opt = self.get_option()
 
2421
        self.assertConverted(True, opt, u'True')
 
2422
        self.assertConverted(True, opt, u'1')
 
2423
        self.assertConverted(False, opt, u'False')
 
2424
 
 
2425
 
 
2426
class TestOptionWithIntegerConverter(tests.TestCase, TestOptionConverterMixin):
 
2427
 
 
2428
    def get_option(self):
 
2429
        return config.Option('foo', help='An integer.',
 
2430
                             from_unicode=config.int_from_store)
 
2431
 
 
2432
    def test_convert_invalid(self):
 
2433
        opt = self.get_option()
 
2434
        # A string that is not recognized as an integer
 
2435
        self.assertConvertInvalid(opt, u'forty-two')
 
2436
        # A list of strings is never recognized as an integer
 
2437
        self.assertConvertInvalid(opt, [u'a', u'list'])
 
2438
 
 
2439
    def test_convert_valid(self):
 
2440
        opt = self.get_option()
 
2441
        self.assertConverted(16, opt, u'16')
 
2442
 
 
2443
 
 
2444
class TestOptionWithSIUnitConverter(tests.TestCase, TestOptionConverterMixin):
 
2445
 
 
2446
    def get_option(self):
 
2447
        return config.Option('foo', help='An integer in SI units.',
 
2448
                             from_unicode=config.int_SI_from_store)
 
2449
 
 
2450
    def test_convert_invalid(self):
 
2451
        opt = self.get_option()
 
2452
        self.assertConvertInvalid(opt, u'not-a-unit')
 
2453
        self.assertConvertInvalid(opt, u'Gb') # Forgot the int
 
2454
        self.assertConvertInvalid(opt, u'1b') # Forgot the unit
 
2455
        self.assertConvertInvalid(opt, u'1GG')
 
2456
        self.assertConvertInvalid(opt, u'1Mbb')
 
2457
        self.assertConvertInvalid(opt, u'1MM')
 
2458
 
 
2459
    def test_convert_valid(self):
 
2460
        opt = self.get_option()
 
2461
        self.assertConverted(int(5e3), opt, u'5kb')
 
2462
        self.assertConverted(int(5e6), opt, u'5M')
 
2463
        self.assertConverted(int(5e6), opt, u'5MB')
 
2464
        self.assertConverted(int(5e9), opt, u'5g')
 
2465
        self.assertConverted(int(5e9), opt, u'5gB')
 
2466
        self.assertConverted(100, opt, u'100')
 
2467
 
 
2468
 
 
2469
class TestListOption(tests.TestCase, TestOptionConverterMixin):
 
2470
 
 
2471
    def get_option(self):
 
2472
        return config.ListOption('foo', help='A list.')
 
2473
 
 
2474
    def test_convert_invalid(self):
 
2475
        opt = self.get_option()
 
2476
        # We don't even try to convert a list into a list, we only expect
 
2477
        # strings
 
2478
        self.assertConvertInvalid(opt, [1])
 
2479
        # No string is invalid as all forms can be converted to a list
 
2480
 
 
2481
    def test_convert_valid(self):
 
2482
        opt = self.get_option()
 
2483
        # An empty string is an empty list
 
2484
        self.assertConverted([], opt, '') # Using a bare str() just in case
 
2485
        self.assertConverted([], opt, u'')
 
2486
        # A boolean
 
2487
        self.assertConverted([u'True'], opt, u'True')
 
2488
        # An integer
 
2489
        self.assertConverted([u'42'], opt, u'42')
 
2490
        # A single string
 
2491
        self.assertConverted([u'bar'], opt, u'bar')
 
2492
 
 
2493
 
 
2494
class TestOptionRegistry(tests.TestCase):
 
2495
 
 
2496
    def setUp(self):
 
2497
        super(TestOptionRegistry, self).setUp()
 
2498
        # Always start with an empty registry
 
2499
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
2500
        self.registry = config.option_registry
 
2501
 
 
2502
    def test_register(self):
 
2503
        opt = config.Option('foo')
 
2504
        self.registry.register(opt)
 
2505
        self.assertIs(opt, self.registry.get('foo'))
 
2506
 
 
2507
    def test_registered_help(self):
 
2508
        opt = config.Option('foo', help='A simple option')
 
2509
        self.registry.register(opt)
 
2510
        self.assertEquals('A simple option', self.registry.get_help('foo'))
 
2511
 
 
2512
    lazy_option = config.Option('lazy_foo', help='Lazy help')
 
2513
 
 
2514
    def test_register_lazy(self):
 
2515
        self.registry.register_lazy('lazy_foo', self.__module__,
 
2516
                                    'TestOptionRegistry.lazy_option')
 
2517
        self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
 
2518
 
 
2519
    def test_registered_lazy_help(self):
 
2520
        self.registry.register_lazy('lazy_foo', self.__module__,
 
2521
                                    'TestOptionRegistry.lazy_option')
 
2522
        self.assertEquals('Lazy help', self.registry.get_help('lazy_foo'))
 
2523
 
 
2524
 
 
2525
class TestRegisteredOptions(tests.TestCase):
 
2526
    """All registered options should verify some constraints."""
 
2527
 
 
2528
    scenarios = [(key, {'option_name': key, 'option': option}) for key, option
 
2529
                 in config.option_registry.iteritems()]
 
2530
 
 
2531
    def setUp(self):
 
2532
        super(TestRegisteredOptions, self).setUp()
 
2533
        self.registry = config.option_registry
 
2534
 
 
2535
    def test_proper_name(self):
 
2536
        # An option should be registered under its own name, this can't be
 
2537
        # checked at registration time for the lazy ones.
 
2538
        self.assertEquals(self.option_name, self.option.name)
 
2539
 
 
2540
    def test_help_is_set(self):
 
2541
        option_help = self.registry.get_help(self.option_name)
 
2542
        self.assertNotEquals(None, option_help)
 
2543
        # Come on, think about the user, he really wants to know what the
 
2544
        # option is about
 
2545
        self.assertIsNot(None, option_help)
 
2546
        self.assertNotEquals('', option_help)
 
2547
 
 
2548
 
 
2549
class TestSection(tests.TestCase):
 
2550
 
 
2551
    # FIXME: Parametrize so that all sections produced by Stores run these
 
2552
    # tests -- vila 2011-04-01
 
2553
 
 
2554
    def test_get_a_value(self):
 
2555
        a_dict = dict(foo='bar')
 
2556
        section = config.Section('myID', a_dict)
 
2557
        self.assertEquals('bar', section.get('foo'))
 
2558
 
 
2559
    def test_get_unknown_option(self):
 
2560
        a_dict = dict()
 
2561
        section = config.Section(None, a_dict)
 
2562
        self.assertEquals('out of thin air',
 
2563
                          section.get('foo', 'out of thin air'))
 
2564
 
 
2565
    def test_options_is_shared(self):
 
2566
        a_dict = dict()
 
2567
        section = config.Section(None, a_dict)
 
2568
        self.assertIs(a_dict, section.options)
 
2569
 
 
2570
 
 
2571
class TestMutableSection(tests.TestCase):
 
2572
 
 
2573
    scenarios = [('mutable',
 
2574
                  {'get_section':
 
2575
                       lambda opts: config.MutableSection('myID', opts)},),
 
2576
        ]
 
2577
 
 
2578
    def test_set(self):
 
2579
        a_dict = dict(foo='bar')
 
2580
        section = self.get_section(a_dict)
 
2581
        section.set('foo', 'new_value')
 
2582
        self.assertEquals('new_value', section.get('foo'))
 
2583
        # The change appears in the shared section
 
2584
        self.assertEquals('new_value', a_dict.get('foo'))
 
2585
        # We keep track of the change
 
2586
        self.assertTrue('foo' in section.orig)
 
2587
        self.assertEquals('bar', section.orig.get('foo'))
 
2588
 
 
2589
    def test_set_preserve_original_once(self):
 
2590
        a_dict = dict(foo='bar')
 
2591
        section = self.get_section(a_dict)
 
2592
        section.set('foo', 'first_value')
 
2593
        section.set('foo', 'second_value')
 
2594
        # We keep track of the original value
 
2595
        self.assertTrue('foo' in section.orig)
 
2596
        self.assertEquals('bar', section.orig.get('foo'))
 
2597
 
 
2598
    def test_remove(self):
 
2599
        a_dict = dict(foo='bar')
 
2600
        section = self.get_section(a_dict)
 
2601
        section.remove('foo')
 
2602
        # We get None for unknown options via the default value
 
2603
        self.assertEquals(None, section.get('foo'))
 
2604
        # Or we just get the default value
 
2605
        self.assertEquals('unknown', section.get('foo', 'unknown'))
 
2606
        self.assertFalse('foo' in section.options)
 
2607
        # We keep track of the deletion
 
2608
        self.assertTrue('foo' in section.orig)
 
2609
        self.assertEquals('bar', section.orig.get('foo'))
 
2610
 
 
2611
    def test_remove_new_option(self):
 
2612
        a_dict = dict()
 
2613
        section = self.get_section(a_dict)
 
2614
        section.set('foo', 'bar')
 
2615
        section.remove('foo')
 
2616
        self.assertFalse('foo' in section.options)
 
2617
        # The option didn't exist initially so it we need to keep track of it
 
2618
        # with a special value
 
2619
        self.assertTrue('foo' in section.orig)
 
2620
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
 
2621
 
 
2622
 
 
2623
class TestCommandLineStore(tests.TestCase):
 
2624
 
 
2625
    def setUp(self):
 
2626
        super(TestCommandLineStore, self).setUp()
 
2627
        self.store = config.CommandLineStore()
 
2628
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
2629
 
 
2630
    def get_section(self):
 
2631
        """Get the unique section for the command line overrides."""
 
2632
        sections = list(self.store.get_sections())
 
2633
        self.assertLength(1, sections)
 
2634
        store, section = sections[0]
 
2635
        self.assertEquals(self.store, store)
 
2636
        return section
 
2637
 
 
2638
    def test_no_override(self):
 
2639
        self.store._from_cmdline([])
 
2640
        section = self.get_section()
 
2641
        self.assertLength(0, list(section.iter_option_names()))
 
2642
 
 
2643
    def test_simple_override(self):
 
2644
        self.store._from_cmdline(['a=b'])
 
2645
        section = self.get_section()
 
2646
        self.assertEqual('b', section.get('a'))
 
2647
 
 
2648
    def test_list_override(self):
 
2649
        opt = config.ListOption('l')
 
2650
        config.option_registry.register(opt)
 
2651
        self.store._from_cmdline(['l=1,2,3'])
 
2652
        val = self.get_section().get('l')
 
2653
        self.assertEqual('1,2,3', val)
 
2654
        # Reminder: lists should be registered as such explicitely, otherwise
 
2655
        # the conversion needs to be done afterwards.
 
2656
        self.assertEqual(['1', '2', '3'],
 
2657
                         opt.convert_from_unicode(self.store, val))
 
2658
 
 
2659
    def test_multiple_overrides(self):
 
2660
        self.store._from_cmdline(['a=b', 'x=y'])
 
2661
        section = self.get_section()
 
2662
        self.assertEquals('b', section.get('a'))
 
2663
        self.assertEquals('y', section.get('x'))
 
2664
 
 
2665
    def test_wrong_syntax(self):
 
2666
        self.assertRaises(errors.BzrCommandError,
 
2667
                          self.store._from_cmdline, ['a=b', 'c'])
 
2668
 
 
2669
class TestStoreMinimalAPI(tests.TestCaseWithTransport):
 
2670
 
 
2671
    scenarios = [(key, {'get_store': builder}) for key, builder
 
2672
                 in config.test_store_builder_registry.iteritems()] + [
 
2673
        ('cmdline', {'get_store': lambda test: config.CommandLineStore()})]
 
2674
 
 
2675
    def test_id(self):
 
2676
        store = self.get_store(self)
 
2677
        if type(store) == config.TransportIniFileStore:
 
2678
            raise tests.TestNotApplicable(
 
2679
                "%s is not a concrete Store implementation"
 
2680
                " so it doesn't need an id" % (store.__class__.__name__,))
 
2681
        self.assertIsNot(None, store.id)
 
2682
 
 
2683
 
 
2684
class TestStore(tests.TestCaseWithTransport):
 
2685
 
 
2686
    def assertSectionContent(self, expected, (store, section)):
 
2687
        """Assert that some options have the proper values in a section."""
 
2688
        expected_name, expected_options = expected
 
2689
        self.assertEquals(expected_name, section.id)
 
2690
        self.assertEquals(
 
2691
            expected_options,
 
2692
            dict([(k, section.get(k)) for k in expected_options.keys()]))
 
2693
 
 
2694
 
 
2695
class TestReadonlyStore(TestStore):
 
2696
 
 
2697
    scenarios = [(key, {'get_store': builder}) for key, builder
 
2698
                 in config.test_store_builder_registry.iteritems()]
 
2699
 
 
2700
    def test_building_delays_load(self):
 
2701
        store = self.get_store(self)
 
2702
        self.assertEquals(False, store.is_loaded())
 
2703
        store._load_from_string('')
 
2704
        self.assertEquals(True, store.is_loaded())
 
2705
 
 
2706
    def test_get_no_sections_for_empty(self):
 
2707
        store = self.get_store(self)
 
2708
        store._load_from_string('')
 
2709
        self.assertEquals([], list(store.get_sections()))
 
2710
 
 
2711
    def test_get_default_section(self):
 
2712
        store = self.get_store(self)
 
2713
        store._load_from_string('foo=bar')
 
2714
        sections = list(store.get_sections())
 
2715
        self.assertLength(1, sections)
 
2716
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2717
 
 
2718
    def test_get_named_section(self):
 
2719
        store = self.get_store(self)
 
2720
        store._load_from_string('[baz]\nfoo=bar')
 
2721
        sections = list(store.get_sections())
 
2722
        self.assertLength(1, sections)
 
2723
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
2724
 
 
2725
    def test_load_from_string_fails_for_non_empty_store(self):
 
2726
        store = self.get_store(self)
 
2727
        store._load_from_string('foo=bar')
 
2728
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
 
2729
 
 
2730
 
 
2731
class TestStoreQuoting(TestStore):
 
2732
 
 
2733
    scenarios = [(key, {'get_store': builder}) for key, builder
 
2734
                 in config.test_store_builder_registry.iteritems()]
 
2735
 
 
2736
    def setUp(self):
 
2737
        super(TestStoreQuoting, self).setUp()
 
2738
        self.store = self.get_store(self)
 
2739
        # We need a loaded store but any content will do
 
2740
        self.store._load_from_string('')
 
2741
 
 
2742
    def assertIdempotent(self, s):
 
2743
        """Assert that quoting an unquoted string is a no-op and vice-versa.
 
2744
 
 
2745
        What matters here is that option values, as they appear in a store, can
 
2746
        be safely round-tripped out of the store and back.
 
2747
 
 
2748
        :param s: A string, quoted if required.
 
2749
        """
 
2750
        self.assertEquals(s, self.store.quote(self.store.unquote(s)))
 
2751
        self.assertEquals(s, self.store.unquote(self.store.quote(s)))
 
2752
 
 
2753
    def test_empty_string(self):
 
2754
        if isinstance(self.store, config.IniFileStore):
 
2755
            # configobj._quote doesn't handle empty values
 
2756
            self.assertRaises(AssertionError,
 
2757
                              self.assertIdempotent, '')
 
2758
        else:
 
2759
            self.assertIdempotent('')
 
2760
        # But quoted empty strings are ok
 
2761
        self.assertIdempotent('""')
 
2762
 
 
2763
    def test_embedded_spaces(self):
 
2764
        self.assertIdempotent('" a b c "')
 
2765
 
 
2766
    def test_embedded_commas(self):
 
2767
        self.assertIdempotent('" a , b c "')
 
2768
 
 
2769
    def test_simple_comma(self):
 
2770
        if isinstance(self.store, config.IniFileStore):
 
2771
            # configobj requires that lists are special-cased
 
2772
           self.assertRaises(AssertionError,
 
2773
                             self.assertIdempotent, ',')
 
2774
        else:
 
2775
            self.assertIdempotent(',')
 
2776
        # When a single comma is required, quoting is also required
 
2777
        self.assertIdempotent('","')
 
2778
 
 
2779
    def test_list(self):
 
2780
        if isinstance(self.store, config.IniFileStore):
 
2781
            # configobj requires that lists are special-cased
 
2782
            self.assertRaises(AssertionError,
 
2783
                              self.assertIdempotent, 'a,b')
 
2784
        else:
 
2785
            self.assertIdempotent('a,b')
 
2786
 
 
2787
 
 
2788
class TestDictFromStore(tests.TestCase):
 
2789
 
 
2790
    def test_unquote_not_string(self):
 
2791
        conf = config.MemoryStack('x=2\n[a_section]\na=1\n')
 
2792
        value = conf.get('a_section')
 
2793
        # Urgh, despite 'conf' asking for the no-name section, we get the
 
2794
        # content of another section as a dict o_O
 
2795
        self.assertEquals({'a': '1'}, value)
 
2796
        unquoted = conf.store.unquote(value)
 
2797
        # Which cannot be unquoted but shouldn't crash either (the use cases
 
2798
        # are getting the value or displaying it. In the later case, '%s' will
 
2799
        # do).
 
2800
        self.assertEquals({'a': '1'}, unquoted)
 
2801
        self.assertEquals("{u'a': u'1'}", '%s' % (unquoted,))
 
2802
 
 
2803
 
 
2804
class TestIniFileStoreContent(tests.TestCaseWithTransport):
 
2805
    """Simulate loading a config store with content of various encodings.
 
2806
 
 
2807
    All files produced by bzr are in utf8 content.
 
2808
 
 
2809
    Users may modify them manually and end up with a file that can't be
 
2810
    loaded. We need to issue proper error messages in this case.
 
2811
    """
 
2812
 
 
2813
    invalid_utf8_char = '\xff'
 
2814
 
 
2815
    def test_load_utf8(self):
 
2816
        """Ensure we can load an utf8-encoded file."""
 
2817
        t = self.get_transport()
 
2818
        # From http://pad.lv/799212
 
2819
        unicode_user = u'b\N{Euro Sign}ar'
 
2820
        unicode_content = u'user=%s' % (unicode_user,)
 
2821
        utf8_content = unicode_content.encode('utf8')
 
2822
        # Store the raw content in the config file
 
2823
        t.put_bytes('foo.conf', utf8_content)
 
2824
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2825
        store.load()
 
2826
        stack = config.Stack([store.get_sections], store)
 
2827
        self.assertEquals(unicode_user, stack.get('user'))
 
2828
 
 
2829
    def test_load_non_ascii(self):
 
2830
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
 
2831
        t = self.get_transport()
 
2832
        t.put_bytes('foo.conf', 'user=foo\n#%s\n' % (self.invalid_utf8_char,))
 
2833
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2834
        self.assertRaises(errors.ConfigContentError, store.load)
 
2835
 
 
2836
    def test_load_erroneous_content(self):
 
2837
        """Ensure we display a proper error on content that can't be parsed."""
 
2838
        t = self.get_transport()
 
2839
        t.put_bytes('foo.conf', '[open_section\n')
 
2840
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2841
        self.assertRaises(errors.ParseConfigError, store.load)
 
2842
 
 
2843
    def test_load_permission_denied(self):
 
2844
        """Ensure we get warned when trying to load an inaccessible file."""
 
2845
        warnings = []
 
2846
        def warning(*args):
 
2847
            warnings.append(args[0] % args[1:])
 
2848
        self.overrideAttr(trace, 'warning', warning)
 
2849
 
 
2850
        t = self.get_transport()
 
2851
 
 
2852
        def get_bytes(relpath):
 
2853
            raise errors.PermissionDenied(relpath, "")
 
2854
        t.get_bytes = get_bytes
 
2855
        store = config.TransportIniFileStore(t, 'foo.conf')
 
2856
        self.assertRaises(errors.PermissionDenied, store.load)
 
2857
        self.assertEquals(
 
2858
            warnings,
 
2859
            [u'Permission denied while trying to load configuration store %s.'
 
2860
             % store.external_url()])
 
2861
 
 
2862
 
 
2863
class TestIniConfigContent(tests.TestCaseWithTransport):
 
2864
    """Simulate loading a IniBasedConfig with content of various encodings.
 
2865
 
 
2866
    All files produced by bzr are in utf8 content.
 
2867
 
 
2868
    Users may modify them manually and end up with a file that can't be
 
2869
    loaded. We need to issue proper error messages in this case.
 
2870
    """
 
2871
 
 
2872
    invalid_utf8_char = '\xff'
 
2873
 
 
2874
    def test_load_utf8(self):
 
2875
        """Ensure we can load an utf8-encoded file."""
 
2876
        # From http://pad.lv/799212
 
2877
        unicode_user = u'b\N{Euro Sign}ar'
 
2878
        unicode_content = u'user=%s' % (unicode_user,)
 
2879
        utf8_content = unicode_content.encode('utf8')
 
2880
        # Store the raw content in the config file
 
2881
        with open('foo.conf', 'wb') as f:
 
2882
            f.write(utf8_content)
 
2883
        conf = config.IniBasedConfig(file_name='foo.conf')
 
2884
        self.assertEquals(unicode_user, conf.get_user_option('user'))
 
2885
 
 
2886
    def test_load_badly_encoded_content(self):
 
2887
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
 
2888
        with open('foo.conf', 'wb') as f:
 
2889
            f.write('user=foo\n#%s\n' % (self.invalid_utf8_char,))
 
2890
        conf = config.IniBasedConfig(file_name='foo.conf')
 
2891
        self.assertRaises(errors.ConfigContentError, conf._get_parser)
 
2892
 
 
2893
    def test_load_erroneous_content(self):
 
2894
        """Ensure we display a proper error on content that can't be parsed."""
 
2895
        with open('foo.conf', 'wb') as f:
 
2896
            f.write('[open_section\n')
 
2897
        conf = config.IniBasedConfig(file_name='foo.conf')
 
2898
        self.assertRaises(errors.ParseConfigError, conf._get_parser)
 
2899
 
 
2900
 
 
2901
class TestMutableStore(TestStore):
 
2902
 
 
2903
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
 
2904
                 in config.test_store_builder_registry.iteritems()]
 
2905
 
 
2906
    def setUp(self):
 
2907
        super(TestMutableStore, self).setUp()
 
2908
        self.transport = self.get_transport()
 
2909
 
 
2910
    def has_store(self, store):
 
2911
        store_basename = urlutils.relative_url(self.transport.external_url(),
 
2912
                                               store.external_url())
 
2913
        return self.transport.has(store_basename)
 
2914
 
 
2915
    def test_save_empty_creates_no_file(self):
 
2916
        # FIXME: There should be a better way than relying on the test
 
2917
        # parametrization to identify branch.conf -- vila 2011-0526
 
2918
        if self.store_id in ('branch', 'remote_branch'):
 
2919
            raise tests.TestNotApplicable(
 
2920
                'branch.conf is *always* created when a branch is initialized')
 
2921
        store = self.get_store(self)
 
2922
        store.save()
 
2923
        self.assertEquals(False, self.has_store(store))
 
2924
 
 
2925
    def test_save_emptied_succeeds(self):
 
2926
        store = self.get_store(self)
 
2927
        store._load_from_string('foo=bar\n')
 
2928
        section = store.get_mutable_section(None)
 
2929
        section.remove('foo')
 
2930
        store.save()
 
2931
        self.assertEquals(True, self.has_store(store))
 
2932
        modified_store = self.get_store(self)
 
2933
        sections = list(modified_store.get_sections())
 
2934
        self.assertLength(0, sections)
 
2935
 
 
2936
    def test_save_with_content_succeeds(self):
 
2937
        # FIXME: There should be a better way than relying on the test
 
2938
        # parametrization to identify branch.conf -- vila 2011-0526
 
2939
        if self.store_id in ('branch', 'remote_branch'):
 
2940
            raise tests.TestNotApplicable(
 
2941
                'branch.conf is *always* created when a branch is initialized')
 
2942
        store = self.get_store(self)
 
2943
        store._load_from_string('foo=bar\n')
 
2944
        self.assertEquals(False, self.has_store(store))
 
2945
        store.save()
 
2946
        self.assertEquals(True, self.has_store(store))
 
2947
        modified_store = self.get_store(self)
 
2948
        sections = list(modified_store.get_sections())
 
2949
        self.assertLength(1, sections)
 
2950
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2951
 
 
2952
    def test_set_option_in_empty_store(self):
 
2953
        store = self.get_store(self)
 
2954
        section = store.get_mutable_section(None)
 
2955
        section.set('foo', 'bar')
 
2956
        store.save()
 
2957
        modified_store = self.get_store(self)
 
2958
        sections = list(modified_store.get_sections())
 
2959
        self.assertLength(1, sections)
 
2960
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2961
 
 
2962
    def test_set_option_in_default_section(self):
 
2963
        store = self.get_store(self)
 
2964
        store._load_from_string('')
 
2965
        section = store.get_mutable_section(None)
 
2966
        section.set('foo', 'bar')
 
2967
        store.save()
 
2968
        modified_store = self.get_store(self)
 
2969
        sections = list(modified_store.get_sections())
 
2970
        self.assertLength(1, sections)
 
2971
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
 
2972
 
 
2973
    def test_set_option_in_named_section(self):
 
2974
        store = self.get_store(self)
 
2975
        store._load_from_string('')
 
2976
        section = store.get_mutable_section('baz')
 
2977
        section.set('foo', 'bar')
 
2978
        store.save()
 
2979
        modified_store = self.get_store(self)
 
2980
        sections = list(modified_store.get_sections())
 
2981
        self.assertLength(1, sections)
 
2982
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
 
2983
 
 
2984
    def test_load_hook(self):
 
2985
        # We first needs to ensure that the store exists
 
2986
        store = self.get_store(self)
 
2987
        section = store.get_mutable_section('baz')
 
2988
        section.set('foo', 'bar')
 
2989
        store.save()
 
2990
        # Now we can try to load it
 
2991
        store = self.get_store(self)
 
2992
        calls = []
 
2993
        def hook(*args):
 
2994
            calls.append(args)
 
2995
        config.ConfigHooks.install_named_hook('load', hook, None)
 
2996
        self.assertLength(0, calls)
 
2997
        store.load()
 
2998
        self.assertLength(1, calls)
 
2999
        self.assertEquals((store,), calls[0])
 
3000
 
 
3001
    def test_save_hook(self):
 
3002
        calls = []
 
3003
        def hook(*args):
 
3004
            calls.append(args)
 
3005
        config.ConfigHooks.install_named_hook('save', hook, None)
 
3006
        self.assertLength(0, calls)
 
3007
        store = self.get_store(self)
 
3008
        section = store.get_mutable_section('baz')
 
3009
        section.set('foo', 'bar')
 
3010
        store.save()
 
3011
        self.assertLength(1, calls)
 
3012
        self.assertEquals((store,), calls[0])
 
3013
 
 
3014
    def test_set_mark_dirty(self):
 
3015
        stack = config.MemoryStack('')
 
3016
        self.assertLength(0, stack.store.dirty_sections)
 
3017
        stack.set('foo', 'baz')
 
3018
        self.assertLength(1, stack.store.dirty_sections)
 
3019
        self.assertTrue(stack.store._need_saving())
 
3020
 
 
3021
    def test_remove_mark_dirty(self):
 
3022
        stack = config.MemoryStack('foo=bar')
 
3023
        self.assertLength(0, stack.store.dirty_sections)
 
3024
        stack.remove('foo')
 
3025
        self.assertLength(1, stack.store.dirty_sections)
 
3026
        self.assertTrue(stack.store._need_saving())
 
3027
 
 
3028
 
 
3029
class TestStoreSaveChanges(tests.TestCaseWithTransport):
 
3030
    """Tests that config changes are kept in memory and saved on-demand."""
 
3031
 
 
3032
    def setUp(self):
 
3033
        super(TestStoreSaveChanges, self).setUp()
 
3034
        self.transport = self.get_transport()
 
3035
        # Most of the tests involve two stores pointing to the same persistent
 
3036
        # storage to observe the effects of concurrent changes
 
3037
        self.st1 = config.TransportIniFileStore(self.transport, 'foo.conf')
 
3038
        self.st2 = config.TransportIniFileStore(self.transport, 'foo.conf')
 
3039
        self.warnings = []
 
3040
        def warning(*args):
 
3041
            self.warnings.append(args[0] % args[1:])
 
3042
        self.overrideAttr(trace, 'warning', warning)
 
3043
 
 
3044
    def has_store(self, store):
 
3045
        store_basename = urlutils.relative_url(self.transport.external_url(),
 
3046
                                               store.external_url())
 
3047
        return self.transport.has(store_basename)
 
3048
 
 
3049
    def get_stack(self, store):
 
3050
        # Any stack will do as long as it uses the right store, just a single
 
3051
        # no-name section is enough
 
3052
        return config.Stack([store.get_sections], store)
 
3053
 
 
3054
    def test_no_changes_no_save(self):
 
3055
        s = self.get_stack(self.st1)
 
3056
        s.store.save_changes()
 
3057
        self.assertEquals(False, self.has_store(self.st1))
 
3058
 
 
3059
    def test_unrelated_concurrent_update(self):
 
3060
        s1 = self.get_stack(self.st1)
 
3061
        s2 = self.get_stack(self.st2)
 
3062
        s1.set('foo', 'bar')
 
3063
        s2.set('baz', 'quux')
 
3064
        s1.store.save()
 
3065
        # Changes don't propagate magically
 
3066
        self.assertEquals(None, s1.get('baz'))
 
3067
        s2.store.save_changes()
 
3068
        self.assertEquals('quux', s2.get('baz'))
 
3069
        # Changes are acquired when saving
 
3070
        self.assertEquals('bar', s2.get('foo'))
 
3071
        # Since there is no overlap, no warnings are emitted
 
3072
        self.assertLength(0, self.warnings)
 
3073
 
 
3074
    def test_concurrent_update_modified(self):
 
3075
        s1 = self.get_stack(self.st1)
 
3076
        s2 = self.get_stack(self.st2)
 
3077
        s1.set('foo', 'bar')
 
3078
        s2.set('foo', 'baz')
 
3079
        s1.store.save()
 
3080
        # Last speaker wins
 
3081
        s2.store.save_changes()
 
3082
        self.assertEquals('baz', s2.get('foo'))
 
3083
        # But the user get a warning
 
3084
        self.assertLength(1, self.warnings)
 
3085
        warning = self.warnings[0]
 
3086
        self.assertStartsWith(warning, 'Option foo in section None')
 
3087
        self.assertEndsWith(warning, 'was changed from <CREATED> to bar.'
 
3088
                            ' The baz value will be saved.')
 
3089
 
 
3090
    def test_concurrent_deletion(self):
 
3091
        self.st1._load_from_string('foo=bar')
 
3092
        self.st1.save()
 
3093
        s1 = self.get_stack(self.st1)
 
3094
        s2 = self.get_stack(self.st2)
 
3095
        s1.remove('foo')
 
3096
        s2.remove('foo')
 
3097
        s1.store.save_changes()
 
3098
        # No warning yet
 
3099
        self.assertLength(0, self.warnings)
 
3100
        s2.store.save_changes()
 
3101
        # Now we get one
 
3102
        self.assertLength(1, self.warnings)
 
3103
        warning = self.warnings[0]
 
3104
        self.assertStartsWith(warning, 'Option foo in section None')
 
3105
        self.assertEndsWith(warning, 'was changed from bar to <CREATED>.'
 
3106
                            ' The <DELETED> value will be saved.')
 
3107
 
 
3108
 
 
3109
class TestQuotingIniFileStore(tests.TestCaseWithTransport):
 
3110
 
 
3111
    def get_store(self):
 
3112
        return config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
3113
 
 
3114
    def test_get_quoted_string(self):
 
3115
        store = self.get_store()
 
3116
        store._load_from_string('foo= " abc "')
 
3117
        stack = config.Stack([store.get_sections])
 
3118
        self.assertEquals(' abc ', stack.get('foo'))
 
3119
 
 
3120
    def test_set_quoted_string(self):
 
3121
        store = self.get_store()
 
3122
        stack = config.Stack([store.get_sections], store)
 
3123
        stack.set('foo', ' a b c ')
 
3124
        store.save()
 
3125
        self.assertFileEqual('foo = " a b c "' + os.linesep, 'foo.conf')
 
3126
 
 
3127
 
 
3128
class TestTransportIniFileStore(TestStore):
 
3129
 
 
3130
    def test_loading_unknown_file_fails(self):
 
3131
        store = config.TransportIniFileStore(self.get_transport(),
 
3132
            'I-do-not-exist')
 
3133
        self.assertRaises(errors.NoSuchFile, store.load)
 
3134
 
 
3135
    def test_invalid_content(self):
 
3136
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
3137
        self.assertEquals(False, store.is_loaded())
 
3138
        exc = self.assertRaises(
 
3139
            errors.ParseConfigError, store._load_from_string,
 
3140
            'this is invalid !')
 
3141
        self.assertEndsWith(exc.filename, 'foo.conf')
 
3142
        # And the load failed
 
3143
        self.assertEquals(False, store.is_loaded())
 
3144
 
 
3145
    def test_get_embedded_sections(self):
 
3146
        # A more complicated example (which also shows that section names and
 
3147
        # option names share the same name space...)
 
3148
        # FIXME: This should be fixed by forbidding dicts as values ?
 
3149
        # -- vila 2011-04-05
 
3150
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
 
3151
        store._load_from_string('''
 
3152
foo=bar
 
3153
l=1,2
 
3154
[DEFAULT]
 
3155
foo_in_DEFAULT=foo_DEFAULT
 
3156
[bar]
 
3157
foo_in_bar=barbar
 
3158
[baz]
 
3159
foo_in_baz=barbaz
 
3160
[[qux]]
 
3161
foo_in_qux=quux
 
3162
''')
 
3163
        sections = list(store.get_sections())
 
3164
        self.assertLength(4, sections)
 
3165
        # The default section has no name.
 
3166
        # List values are provided as strings and need to be explicitly
 
3167
        # converted by specifying from_unicode=list_from_store at option
 
3168
        # registration
 
3169
        self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
 
3170
                                  sections[0])
 
3171
        self.assertSectionContent(
 
3172
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
 
3173
        self.assertSectionContent(
 
3174
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
 
3175
        # sub sections are provided as embedded dicts.
 
3176
        self.assertSectionContent(
 
3177
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
 
3178
            sections[3])
 
3179
 
 
3180
 
 
3181
class TestLockableIniFileStore(TestStore):
 
3182
 
 
3183
    def test_create_store_in_created_dir(self):
 
3184
        self.assertPathDoesNotExist('dir')
 
3185
        t = self.get_transport('dir/subdir')
 
3186
        store = config.LockableIniFileStore(t, 'foo.conf')
 
3187
        store.get_mutable_section(None).set('foo', 'bar')
 
3188
        store.save()
 
3189
        self.assertPathExists('dir/subdir')
 
3190
 
 
3191
 
 
3192
class TestConcurrentStoreUpdates(TestStore):
 
3193
    """Test that Stores properly handle conccurent updates.
 
3194
 
 
3195
    New Store implementation may fail some of these tests but until such
 
3196
    implementations exist it's hard to properly filter them from the scenarios
 
3197
    applied here. If you encounter such a case, contact the bzr devs.
 
3198
    """
 
3199
 
 
3200
    scenarios = [(key, {'get_stack': builder}) for key, builder
 
3201
                 in config.test_stack_builder_registry.iteritems()]
 
3202
 
 
3203
    def setUp(self):
 
3204
        super(TestConcurrentStoreUpdates, self).setUp()
 
3205
        self.stack = self.get_stack(self)
 
3206
        if not isinstance(self.stack, config._CompatibleStack):
 
3207
            raise tests.TestNotApplicable(
 
3208
                '%s is not meant to be compatible with the old config design'
 
3209
                % (self.stack,))
 
3210
        self.stack.set('one', '1')
 
3211
        self.stack.set('two', '2')
 
3212
        # Flush the store
 
3213
        self.stack.store.save()
 
3214
 
 
3215
    def test_simple_read_access(self):
 
3216
        self.assertEquals('1', self.stack.get('one'))
 
3217
 
 
3218
    def test_simple_write_access(self):
 
3219
        self.stack.set('one', 'one')
 
3220
        self.assertEquals('one', self.stack.get('one'))
 
3221
 
 
3222
    def test_listen_to_the_last_speaker(self):
 
3223
        c1 = self.stack
 
3224
        c2 = self.get_stack(self)
 
3225
        c1.set('one', 'ONE')
 
3226
        c2.set('two', 'TWO')
 
3227
        self.assertEquals('ONE', c1.get('one'))
 
3228
        self.assertEquals('TWO', c2.get('two'))
 
3229
        # The second update respect the first one
 
3230
        self.assertEquals('ONE', c2.get('one'))
 
3231
 
 
3232
    def test_last_speaker_wins(self):
 
3233
        # If the same config is not shared, the same variable modified twice
 
3234
        # can only see a single result.
 
3235
        c1 = self.stack
 
3236
        c2 = self.get_stack(self)
 
3237
        c1.set('one', 'c1')
 
3238
        c2.set('one', 'c2')
 
3239
        self.assertEquals('c2', c2.get('one'))
 
3240
        # The first modification is still available until another refresh
 
3241
        # occur
 
3242
        self.assertEquals('c1', c1.get('one'))
 
3243
        c1.set('two', 'done')
 
3244
        self.assertEquals('c2', c1.get('one'))
 
3245
 
 
3246
    def test_writes_are_serialized(self):
 
3247
        c1 = self.stack
 
3248
        c2 = self.get_stack(self)
 
3249
 
 
3250
        # We spawn a thread that will pause *during* the config saving.
 
3251
        before_writing = threading.Event()
 
3252
        after_writing = threading.Event()
 
3253
        writing_done = threading.Event()
 
3254
        c1_save_without_locking_orig = c1.store.save_without_locking
 
3255
        def c1_save_without_locking():
 
3256
            before_writing.set()
 
3257
            c1_save_without_locking_orig()
 
3258
            # The lock is held. We wait for the main thread to decide when to
 
3259
            # continue
 
3260
            after_writing.wait()
 
3261
        c1.store.save_without_locking = c1_save_without_locking
 
3262
        def c1_set():
 
3263
            c1.set('one', 'c1')
 
3264
            writing_done.set()
 
3265
        t1 = threading.Thread(target=c1_set)
 
3266
        # Collect the thread after the test
 
3267
        self.addCleanup(t1.join)
 
3268
        # Be ready to unblock the thread if the test goes wrong
 
3269
        self.addCleanup(after_writing.set)
 
3270
        t1.start()
 
3271
        before_writing.wait()
 
3272
        self.assertRaises(errors.LockContention,
 
3273
                          c2.set, 'one', 'c2')
 
3274
        self.assertEquals('c1', c1.get('one'))
 
3275
        # Let the lock be released
 
3276
        after_writing.set()
 
3277
        writing_done.wait()
 
3278
        c2.set('one', 'c2')
 
3279
        self.assertEquals('c2', c2.get('one'))
 
3280
 
 
3281
    def test_read_while_writing(self):
 
3282
       c1 = self.stack
 
3283
       # We spawn a thread that will pause *during* the write
 
3284
       ready_to_write = threading.Event()
 
3285
       do_writing = threading.Event()
 
3286
       writing_done = threading.Event()
 
3287
       # We override the _save implementation so we know the store is locked
 
3288
       c1_save_without_locking_orig = c1.store.save_without_locking
 
3289
       def c1_save_without_locking():
 
3290
           ready_to_write.set()
 
3291
           # The lock is held. We wait for the main thread to decide when to
 
3292
           # continue
 
3293
           do_writing.wait()
 
3294
           c1_save_without_locking_orig()
 
3295
           writing_done.set()
 
3296
       c1.store.save_without_locking = c1_save_without_locking
 
3297
       def c1_set():
 
3298
           c1.set('one', 'c1')
 
3299
       t1 = threading.Thread(target=c1_set)
 
3300
       # Collect the thread after the test
 
3301
       self.addCleanup(t1.join)
 
3302
       # Be ready to unblock the thread if the test goes wrong
 
3303
       self.addCleanup(do_writing.set)
 
3304
       t1.start()
 
3305
       # Ensure the thread is ready to write
 
3306
       ready_to_write.wait()
 
3307
       self.assertEquals('c1', c1.get('one'))
 
3308
       # If we read during the write, we get the old value
 
3309
       c2 = self.get_stack(self)
 
3310
       self.assertEquals('1', c2.get('one'))
 
3311
       # Let the writing occur and ensure it occurred
 
3312
       do_writing.set()
 
3313
       writing_done.wait()
 
3314
       # Now we get the updated value
 
3315
       c3 = self.get_stack(self)
 
3316
       self.assertEquals('c1', c3.get('one'))
 
3317
 
 
3318
    # FIXME: It may be worth looking into removing the lock dir when it's not
 
3319
    # needed anymore and look at possible fallouts for concurrent lockers. This
 
3320
    # will matter if/when we use config files outside of bazaar directories
 
3321
    # (.bazaar or .bzr) -- vila 20110-04-111
 
3322
 
 
3323
 
 
3324
class TestSectionMatcher(TestStore):
 
3325
 
 
3326
    scenarios = [('location', {'matcher': config.LocationMatcher}),
 
3327
                 ('id', {'matcher': config.NameMatcher}),]
 
3328
 
 
3329
    def setUp(self):
 
3330
        super(TestSectionMatcher, self).setUp()
 
3331
        # Any simple store is good enough
 
3332
        self.get_store = config.test_store_builder_registry.get('configobj')
 
3333
 
 
3334
    def test_no_matches_for_empty_stores(self):
 
3335
        store = self.get_store(self)
 
3336
        store._load_from_string('')
 
3337
        matcher = self.matcher(store, '/bar')
 
3338
        self.assertEquals([], list(matcher.get_sections()))
 
3339
 
 
3340
    def test_build_doesnt_load_store(self):
 
3341
        store = self.get_store(self)
 
3342
        matcher = self.matcher(store, '/bar')
 
3343
        self.assertFalse(store.is_loaded())
 
3344
 
 
3345
 
 
3346
class TestLocationSection(tests.TestCase):
 
3347
 
 
3348
    def get_section(self, options, extra_path):
 
3349
        section = config.Section('foo', options)
 
3350
        return config.LocationSection(section, extra_path)
 
3351
 
 
3352
    def test_simple_option(self):
 
3353
        section = self.get_section({'foo': 'bar'}, '')
 
3354
        self.assertEquals('bar', section.get('foo'))
 
3355
 
 
3356
    def test_option_with_extra_path(self):
 
3357
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
 
3358
                                   'baz')
 
3359
        self.assertEquals('bar/baz', section.get('foo'))
 
3360
 
 
3361
    def test_invalid_policy(self):
 
3362
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
 
3363
                                   'baz')
 
3364
        # invalid policies are ignored
 
3365
        self.assertEquals('bar', section.get('foo'))
 
3366
 
 
3367
 
 
3368
class TestLocationMatcher(TestStore):
 
3369
 
 
3370
    def setUp(self):
 
3371
        super(TestLocationMatcher, self).setUp()
 
3372
        # Any simple store is good enough
 
3373
        self.get_store = config.test_store_builder_registry.get('configobj')
 
3374
 
 
3375
    def test_unrelated_section_excluded(self):
 
3376
        store = self.get_store(self)
 
3377
        store._load_from_string('''
 
3378
[/foo]
 
3379
section=/foo
 
3380
[/foo/baz]
 
3381
section=/foo/baz
 
3382
[/foo/bar]
 
3383
section=/foo/bar
 
3384
[/foo/bar/baz]
 
3385
section=/foo/bar/baz
 
3386
[/quux/quux]
 
3387
section=/quux/quux
 
3388
''')
 
3389
        self.assertEquals(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
 
3390
                           '/quux/quux'],
 
3391
                          [section.id for _, section in store.get_sections()])
 
3392
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
 
3393
        sections = [section for _, section in matcher.get_sections()]
 
3394
        self.assertEquals(['/foo/bar', '/foo'],
 
3395
                          [section.id for section in sections])
 
3396
        self.assertEquals(['quux', 'bar/quux'],
 
3397
                          [section.extra_path for section in sections])
 
3398
 
 
3399
    def test_more_specific_sections_first(self):
 
3400
        store = self.get_store(self)
 
3401
        store._load_from_string('''
 
3402
[/foo]
 
3403
section=/foo
 
3404
[/foo/bar]
 
3405
section=/foo/bar
 
3406
''')
 
3407
        self.assertEquals(['/foo', '/foo/bar'],
 
3408
                          [section.id for _, section in store.get_sections()])
 
3409
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
 
3410
        sections = [section for _, section in matcher.get_sections()]
 
3411
        self.assertEquals(['/foo/bar', '/foo'],
 
3412
                          [section.id for section in sections])
 
3413
        self.assertEquals(['baz', 'bar/baz'],
 
3414
                          [section.extra_path for section in sections])
 
3415
 
 
3416
    def test_appendpath_in_no_name_section(self):
 
3417
        # It's a bit weird to allow appendpath in a no-name section, but
 
3418
        # someone may found a use for it
 
3419
        store = self.get_store(self)
 
3420
        store._load_from_string('''
 
3421
foo=bar
 
3422
foo:policy = appendpath
 
3423
''')
 
3424
        matcher = config.LocationMatcher(store, 'dir/subdir')
 
3425
        sections = list(matcher.get_sections())
 
3426
        self.assertLength(1, sections)
 
3427
        self.assertEquals('bar/dir/subdir', sections[0][1].get('foo'))
 
3428
 
 
3429
    def test_file_urls_are_normalized(self):
 
3430
        store = self.get_store(self)
 
3431
        if sys.platform == 'win32':
 
3432
            expected_url = 'file:///C:/dir/subdir'
 
3433
            expected_location = 'C:/dir/subdir'
 
3434
        else:
 
3435
            expected_url = 'file:///dir/subdir'
 
3436
            expected_location = '/dir/subdir'
 
3437
        matcher = config.LocationMatcher(store, expected_url)
 
3438
        self.assertEquals(expected_location, matcher.location)
 
3439
 
 
3440
 
 
3441
class TestStartingPathMatcher(TestStore):
 
3442
 
 
3443
    def setUp(self):
 
3444
        super(TestStartingPathMatcher, self).setUp()
 
3445
        # Any simple store is good enough
 
3446
        self.store = config.IniFileStore()
 
3447
 
 
3448
    def assertSectionIDs(self, expected, location, content):
 
3449
        self.store._load_from_string(content)
 
3450
        matcher = config.StartingPathMatcher(self.store, location)
 
3451
        sections = list(matcher.get_sections())
 
3452
        self.assertLength(len(expected), sections)
 
3453
        self.assertEqual(expected, [section.id for _, section in sections])
 
3454
        return sections
 
3455
 
 
3456
    def test_empty(self):
 
3457
        self.assertSectionIDs([], self.get_url(), '')
 
3458
 
 
3459
    def test_url_vs_local_paths(self):
 
3460
        # The matcher location is an url and the section names are local paths
 
3461
        sections = self.assertSectionIDs(['/foo/bar', '/foo'],
 
3462
                                         'file:///foo/bar/baz', '''\
 
3463
[/foo]
 
3464
[/foo/bar]
 
3465
''')
 
3466
 
 
3467
    def test_local_path_vs_url(self):
 
3468
        # The matcher location is a local path and the section names are urls
 
3469
        sections = self.assertSectionIDs(['file:///foo/bar', 'file:///foo'],
 
3470
                                         '/foo/bar/baz', '''\
 
3471
[file:///foo]
 
3472
[file:///foo/bar]
 
3473
''')
 
3474
 
 
3475
 
 
3476
    def test_no_name_section_included_when_present(self):
 
3477
        # Note that other tests will cover the case where the no-name section
 
3478
        # is empty and as such, not included.
 
3479
        sections = self.assertSectionIDs(['/foo/bar', '/foo', None],
 
3480
                                         '/foo/bar/baz', '''\
 
3481
option = defined so the no-name section exists
 
3482
[/foo]
 
3483
[/foo/bar]
 
3484
''')
 
3485
        self.assertEquals(['baz', 'bar/baz', '/foo/bar/baz'],
 
3486
                          [s.locals['relpath'] for _, s in sections])
 
3487
 
 
3488
    def test_order_reversed(self):
 
3489
        self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
 
3490
[/foo]
 
3491
[/foo/bar]
 
3492
''')
 
3493
 
 
3494
    def test_unrelated_section_excluded(self):
 
3495
        self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', '''\
 
3496
[/foo]
 
3497
[/foo/qux]
 
3498
[/foo/bar]
 
3499
''')
 
3500
 
 
3501
    def test_glob_included(self):
 
3502
        sections = self.assertSectionIDs(['/foo/*/baz', '/foo/b*', '/foo'],
 
3503
                                         '/foo/bar/baz', '''\
 
3504
[/foo]
 
3505
[/foo/qux]
 
3506
[/foo/b*]
 
3507
[/foo/*/baz]
 
3508
''')
 
3509
        # Note that 'baz' as a relpath for /foo/b* is not fully correct, but
 
3510
        # nothing really is... as far using {relpath} to append it to something
 
3511
        # else, this seems good enough though.
 
3512
        self.assertEquals(['', 'baz', 'bar/baz'],
 
3513
                          [s.locals['relpath'] for _, s in sections])
 
3514
 
 
3515
    def test_respect_order(self):
 
3516
        self.assertSectionIDs(['/foo', '/foo/b*', '/foo/*/baz'],
 
3517
                              '/foo/bar/baz', '''\
 
3518
[/foo/*/baz]
 
3519
[/foo/qux]
 
3520
[/foo/b*]
 
3521
[/foo]
 
3522
''')
 
3523
 
 
3524
 
 
3525
class TestNameMatcher(TestStore):
 
3526
 
 
3527
    def setUp(self):
 
3528
        super(TestNameMatcher, self).setUp()
 
3529
        self.matcher = config.NameMatcher
 
3530
        # Any simple store is good enough
 
3531
        self.get_store = config.test_store_builder_registry.get('configobj')
 
3532
 
 
3533
    def get_matching_sections(self, name):
 
3534
        store = self.get_store(self)
 
3535
        store._load_from_string('''
 
3536
[foo]
 
3537
option=foo
 
3538
[foo/baz]
 
3539
option=foo/baz
 
3540
[bar]
 
3541
option=bar
 
3542
''')
 
3543
        matcher = self.matcher(store, name)
 
3544
        return list(matcher.get_sections())
 
3545
 
 
3546
    def test_matching(self):
 
3547
        sections = self.get_matching_sections('foo')
 
3548
        self.assertLength(1, sections)
 
3549
        self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
 
3550
 
 
3551
    def test_not_matching(self):
 
3552
        sections = self.get_matching_sections('baz')
 
3553
        self.assertLength(0, sections)
 
3554
 
 
3555
 
 
3556
class TestBaseStackGet(tests.TestCase):
 
3557
 
 
3558
    def setUp(self):
 
3559
        super(TestBaseStackGet, self).setUp()
 
3560
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3561
 
 
3562
    def test_get_first_definition(self):
 
3563
        store1 = config.IniFileStore()
 
3564
        store1._load_from_string('foo=bar')
 
3565
        store2 = config.IniFileStore()
 
3566
        store2._load_from_string('foo=baz')
 
3567
        conf = config.Stack([store1.get_sections, store2.get_sections])
 
3568
        self.assertEquals('bar', conf.get('foo'))
 
3569
 
 
3570
    def test_get_with_registered_default_value(self):
 
3571
        config.option_registry.register(config.Option('foo', default='bar'))
 
3572
        conf_stack = config.Stack([])
 
3573
        self.assertEquals('bar', conf_stack.get('foo'))
 
3574
 
 
3575
    def test_get_without_registered_default_value(self):
 
3576
        config.option_registry.register(config.Option('foo'))
 
3577
        conf_stack = config.Stack([])
 
3578
        self.assertEquals(None, conf_stack.get('foo'))
 
3579
 
 
3580
    def test_get_without_default_value_for_not_registered(self):
 
3581
        conf_stack = config.Stack([])
 
3582
        self.assertEquals(None, conf_stack.get('foo'))
 
3583
 
 
3584
    def test_get_for_empty_section_callable(self):
 
3585
        conf_stack = config.Stack([lambda : []])
 
3586
        self.assertEquals(None, conf_stack.get('foo'))
 
3587
 
 
3588
    def test_get_for_broken_callable(self):
 
3589
        # Trying to use and invalid callable raises an exception on first use
 
3590
        conf_stack = config.Stack([object])
 
3591
        self.assertRaises(TypeError, conf_stack.get, 'foo')
 
3592
 
 
3593
 
 
3594
class TestStackWithSimpleStore(tests.TestCase):
 
3595
 
 
3596
    def setUp(self):
 
3597
        super(TestStackWithSimpleStore, self).setUp()
 
3598
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3599
        self.registry = config.option_registry
 
3600
 
 
3601
    def get_conf(self, content=None):
 
3602
        return config.MemoryStack(content)
 
3603
 
 
3604
    def test_override_value_from_env(self):
 
3605
        self.registry.register(
 
3606
            config.Option('foo', default='bar', override_from_env=['FOO']))
 
3607
        self.overrideEnv('FOO', 'quux')
 
3608
        # Env variable provides a default taking over the option one
 
3609
        conf = self.get_conf('foo=store')
 
3610
        self.assertEquals('quux', conf.get('foo'))
 
3611
 
 
3612
    def test_first_override_value_from_env_wins(self):
 
3613
        self.registry.register(
 
3614
            config.Option('foo', default='bar',
 
3615
                          override_from_env=['NO_VALUE', 'FOO', 'BAZ']))
 
3616
        self.overrideEnv('FOO', 'foo')
 
3617
        self.overrideEnv('BAZ', 'baz')
 
3618
        # The first env var set wins
 
3619
        conf = self.get_conf('foo=store')
 
3620
        self.assertEquals('foo', conf.get('foo'))
 
3621
 
 
3622
 
 
3623
class TestMemoryStack(tests.TestCase):
 
3624
 
 
3625
    def test_get(self):
 
3626
        conf = config.MemoryStack('foo=bar')
 
3627
        self.assertEquals('bar', conf.get('foo'))
 
3628
 
 
3629
    def test_set(self):
 
3630
        conf = config.MemoryStack('foo=bar')
 
3631
        conf.set('foo', 'baz')
 
3632
        self.assertEquals('baz', conf.get('foo'))
 
3633
 
 
3634
    def test_no_content(self):
 
3635
        conf = config.MemoryStack()
 
3636
        # No content means no loading
 
3637
        self.assertFalse(conf.store.is_loaded())
 
3638
        self.assertRaises(NotImplementedError, conf.get, 'foo')
 
3639
        # But a content can still be provided
 
3640
        conf.store._load_from_string('foo=bar')
 
3641
        self.assertEquals('bar', conf.get('foo'))
 
3642
 
 
3643
 
 
3644
class TestStackWithTransport(tests.TestCaseWithTransport):
 
3645
 
 
3646
    scenarios = [(key, {'get_stack': builder}) for key, builder
 
3647
                 in config.test_stack_builder_registry.iteritems()]
 
3648
 
 
3649
 
 
3650
class TestConcreteStacks(TestStackWithTransport):
 
3651
 
 
3652
    def test_build_stack(self):
 
3653
        # Just a smoke test to help debug builders
 
3654
        stack = self.get_stack(self)
 
3655
 
 
3656
 
 
3657
class TestStackGet(TestStackWithTransport):
 
3658
 
 
3659
    def setUp(self):
 
3660
        super(TestStackGet, self).setUp()
 
3661
        self.conf = self.get_stack(self)
 
3662
 
 
3663
    def test_get_for_empty_stack(self):
 
3664
        self.assertEquals(None, self.conf.get('foo'))
 
3665
 
 
3666
    def test_get_hook(self):
 
3667
        self.conf.set('foo', 'bar')
 
3668
        calls = []
 
3669
        def hook(*args):
 
3670
            calls.append(args)
 
3671
        config.ConfigHooks.install_named_hook('get', hook, None)
 
3672
        self.assertLength(0, calls)
 
3673
        value = self.conf.get('foo')
 
3674
        self.assertEquals('bar', value)
 
3675
        self.assertLength(1, calls)
 
3676
        self.assertEquals((self.conf, 'foo', 'bar'), calls[0])
 
3677
 
 
3678
 
 
3679
class TestStackGetWithConverter(tests.TestCase):
 
3680
 
 
3681
    def setUp(self):
 
3682
        super(TestStackGetWithConverter, self).setUp()
 
3683
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3684
        self.registry = config.option_registry
 
3685
 
 
3686
    def get_conf(self, content=None):
 
3687
        return config.MemoryStack(content)
 
3688
 
 
3689
    def register_bool_option(self, name, default=None, default_from_env=None):
 
3690
        b = config.Option(name, help='A boolean.',
 
3691
                          default=default, default_from_env=default_from_env,
 
3692
                          from_unicode=config.bool_from_store)
 
3693
        self.registry.register(b)
 
3694
 
 
3695
    def test_get_default_bool_None(self):
 
3696
        self.register_bool_option('foo')
 
3697
        conf = self.get_conf('')
 
3698
        self.assertEquals(None, conf.get('foo'))
 
3699
 
 
3700
    def test_get_default_bool_True(self):
 
3701
        self.register_bool_option('foo', u'True')
 
3702
        conf = self.get_conf('')
 
3703
        self.assertEquals(True, conf.get('foo'))
 
3704
 
 
3705
    def test_get_default_bool_False(self):
 
3706
        self.register_bool_option('foo', False)
 
3707
        conf = self.get_conf('')
 
3708
        self.assertEquals(False, conf.get('foo'))
 
3709
 
 
3710
    def test_get_default_bool_False_as_string(self):
 
3711
        self.register_bool_option('foo', u'False')
 
3712
        conf = self.get_conf('')
 
3713
        self.assertEquals(False, conf.get('foo'))
 
3714
 
 
3715
    def test_get_default_bool_from_env_converted(self):
 
3716
        self.register_bool_option('foo', u'True', default_from_env=['FOO'])
 
3717
        self.overrideEnv('FOO', 'False')
 
3718
        conf = self.get_conf('')
 
3719
        self.assertEquals(False, conf.get('foo'))
 
3720
 
 
3721
    def test_get_default_bool_when_conversion_fails(self):
 
3722
        self.register_bool_option('foo', default='True')
 
3723
        conf = self.get_conf('foo=invalid boolean')
 
3724
        self.assertEquals(True, conf.get('foo'))
 
3725
 
 
3726
    def register_integer_option(self, name,
 
3727
                                default=None, default_from_env=None):
 
3728
        i = config.Option(name, help='An integer.',
 
3729
                          default=default, default_from_env=default_from_env,
 
3730
                          from_unicode=config.int_from_store)
 
3731
        self.registry.register(i)
 
3732
 
 
3733
    def test_get_default_integer_None(self):
 
3734
        self.register_integer_option('foo')
 
3735
        conf = self.get_conf('')
 
3736
        self.assertEquals(None, conf.get('foo'))
 
3737
 
 
3738
    def test_get_default_integer(self):
 
3739
        self.register_integer_option('foo', 42)
 
3740
        conf = self.get_conf('')
 
3741
        self.assertEquals(42, conf.get('foo'))
 
3742
 
 
3743
    def test_get_default_integer_as_string(self):
 
3744
        self.register_integer_option('foo', u'42')
 
3745
        conf = self.get_conf('')
 
3746
        self.assertEquals(42, conf.get('foo'))
 
3747
 
 
3748
    def test_get_default_integer_from_env(self):
 
3749
        self.register_integer_option('foo', default_from_env=['FOO'])
 
3750
        self.overrideEnv('FOO', '18')
 
3751
        conf = self.get_conf('')
 
3752
        self.assertEquals(18, conf.get('foo'))
 
3753
 
 
3754
    def test_get_default_integer_when_conversion_fails(self):
 
3755
        self.register_integer_option('foo', default='12')
 
3756
        conf = self.get_conf('foo=invalid integer')
 
3757
        self.assertEquals(12, conf.get('foo'))
 
3758
 
 
3759
    def register_list_option(self, name, default=None, default_from_env=None):
 
3760
        l = config.ListOption(name, help='A list.', default=default,
 
3761
                              default_from_env=default_from_env)
 
3762
        self.registry.register(l)
 
3763
 
 
3764
    def test_get_default_list_None(self):
 
3765
        self.register_list_option('foo')
 
3766
        conf = self.get_conf('')
 
3767
        self.assertEquals(None, conf.get('foo'))
 
3768
 
 
3769
    def test_get_default_list_empty(self):
 
3770
        self.register_list_option('foo', '')
 
3771
        conf = self.get_conf('')
 
3772
        self.assertEquals([], conf.get('foo'))
 
3773
 
 
3774
    def test_get_default_list_from_env(self):
 
3775
        self.register_list_option('foo', default_from_env=['FOO'])
 
3776
        self.overrideEnv('FOO', '')
 
3777
        conf = self.get_conf('')
 
3778
        self.assertEquals([], conf.get('foo'))
 
3779
 
 
3780
    def test_get_with_list_converter_no_item(self):
 
3781
        self.register_list_option('foo', None)
 
3782
        conf = self.get_conf('foo=,')
 
3783
        self.assertEquals([], conf.get('foo'))
 
3784
 
 
3785
    def test_get_with_list_converter_many_items(self):
 
3786
        self.register_list_option('foo', None)
 
3787
        conf = self.get_conf('foo=m,o,r,e')
 
3788
        self.assertEquals(['m', 'o', 'r', 'e'], conf.get('foo'))
 
3789
 
 
3790
    def test_get_with_list_converter_embedded_spaces_many_items(self):
 
3791
        self.register_list_option('foo', None)
 
3792
        conf = self.get_conf('foo=" bar", "baz "')
 
3793
        self.assertEquals([' bar', 'baz '], conf.get('foo'))
 
3794
 
 
3795
    def test_get_with_list_converter_stripped_spaces_many_items(self):
 
3796
        self.register_list_option('foo', None)
 
3797
        conf = self.get_conf('foo= bar ,  baz ')
 
3798
        self.assertEquals(['bar', 'baz'], conf.get('foo'))
 
3799
 
 
3800
 
 
3801
class TestIterOptionRefs(tests.TestCase):
 
3802
    """iter_option_refs is a bit unusual, document some cases."""
 
3803
 
 
3804
    def assertRefs(self, expected, string):
 
3805
        self.assertEquals(expected, list(config.iter_option_refs(string)))
 
3806
 
 
3807
    def test_empty(self):
 
3808
        self.assertRefs([(False, '')], '')
 
3809
 
 
3810
    def test_no_refs(self):
 
3811
        self.assertRefs([(False, 'foo bar')], 'foo bar')
 
3812
 
 
3813
    def test_single_ref(self):
 
3814
        self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
 
3815
 
 
3816
    def test_broken_ref(self):
 
3817
        self.assertRefs([(False, '{foo')], '{foo')
 
3818
 
 
3819
    def test_embedded_ref(self):
 
3820
        self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
 
3821
                        '{{foo}}')
 
3822
 
 
3823
    def test_two_refs(self):
 
3824
        self.assertRefs([(False, ''), (True, '{foo}'),
 
3825
                         (False, ''), (True, '{bar}'),
 
3826
                         (False, ''),],
 
3827
                        '{foo}{bar}')
 
3828
 
 
3829
    def test_newline_in_refs_are_not_matched(self):
 
3830
        self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
 
3831
 
 
3832
 
 
3833
class TestStackExpandOptions(tests.TestCaseWithTransport):
 
3834
 
 
3835
    def setUp(self):
 
3836
        super(TestStackExpandOptions, self).setUp()
 
3837
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
 
3838
        self.registry = config.option_registry
 
3839
        self.conf = build_branch_stack(self)
 
3840
 
 
3841
    def assertExpansion(self, expected, string, env=None):
 
3842
        self.assertEquals(expected, self.conf.expand_options(string, env))
 
3843
 
 
3844
    def test_no_expansion(self):
 
3845
        self.assertExpansion('foo', 'foo')
 
3846
 
 
3847
    def test_expand_default_value(self):
 
3848
        self.conf.store._load_from_string('bar=baz')
 
3849
        self.registry.register(config.Option('foo', default=u'{bar}'))
 
3850
        self.assertEquals('baz', self.conf.get('foo', expand=True))
 
3851
 
 
3852
    def test_expand_default_from_env(self):
 
3853
        self.conf.store._load_from_string('bar=baz')
 
3854
        self.registry.register(config.Option('foo', default_from_env=['FOO']))
 
3855
        self.overrideEnv('FOO', '{bar}')
 
3856
        self.assertEquals('baz', self.conf.get('foo', expand=True))
 
3857
 
 
3858
    def test_expand_default_on_failed_conversion(self):
 
3859
        self.conf.store._load_from_string('baz=bogus\nbar=42\nfoo={baz}')
 
3860
        self.registry.register(
 
3861
            config.Option('foo', default=u'{bar}',
 
3862
                          from_unicode=config.int_from_store))
 
3863
        self.assertEquals(42, self.conf.get('foo', expand=True))
 
3864
 
 
3865
    def test_env_adding_options(self):
 
3866
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
 
3867
 
 
3868
    def test_env_overriding_options(self):
 
3869
        self.conf.store._load_from_string('foo=baz')
 
3870
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
 
3871
 
 
3872
    def test_simple_ref(self):
 
3873
        self.conf.store._load_from_string('foo=xxx')
 
3874
        self.assertExpansion('xxx', '{foo}')
 
3875
 
 
3876
    def test_unknown_ref(self):
 
3877
        self.assertRaises(errors.ExpandingUnknownOption,
 
3878
                          self.conf.expand_options, '{foo}')
 
3879
 
 
3880
    def test_indirect_ref(self):
 
3881
        self.conf.store._load_from_string('''
 
3882
foo=xxx
 
3883
bar={foo}
 
3884
''')
 
3885
        self.assertExpansion('xxx', '{bar}')
 
3886
 
 
3887
    def test_embedded_ref(self):
 
3888
        self.conf.store._load_from_string('''
 
3889
foo=xxx
 
3890
bar=foo
 
3891
''')
 
3892
        self.assertExpansion('xxx', '{{bar}}')
 
3893
 
 
3894
    def test_simple_loop(self):
 
3895
        self.conf.store._load_from_string('foo={foo}')
 
3896
        self.assertRaises(errors.OptionExpansionLoop,
 
3897
                          self.conf.expand_options, '{foo}')
 
3898
 
 
3899
    def test_indirect_loop(self):
 
3900
        self.conf.store._load_from_string('''
 
3901
foo={bar}
 
3902
bar={baz}
 
3903
baz={foo}''')
 
3904
        e = self.assertRaises(errors.OptionExpansionLoop,
 
3905
                              self.conf.expand_options, '{foo}')
 
3906
        self.assertEquals('foo->bar->baz', e.refs)
 
3907
        self.assertEquals('{foo}', e.string)
 
3908
 
 
3909
    def test_list(self):
 
3910
        self.conf.store._load_from_string('''
 
3911
foo=start
 
3912
bar=middle
 
3913
baz=end
 
3914
list={foo},{bar},{baz}
 
3915
''')
 
3916
        self.registry.register(
 
3917
            config.ListOption('list'))
 
3918
        self.assertEquals(['start', 'middle', 'end'],
 
3919
                           self.conf.get('list', expand=True))
 
3920
 
 
3921
    def test_cascading_list(self):
 
3922
        self.conf.store._load_from_string('''
 
3923
foo=start,{bar}
 
3924
bar=middle,{baz}
 
3925
baz=end
 
3926
list={foo}
 
3927
''')
 
3928
        self.registry.register(
 
3929
            config.ListOption('list'))
 
3930
        self.assertEquals(['start', 'middle', 'end'],
 
3931
                           self.conf.get('list', expand=True))
 
3932
 
 
3933
    def test_pathologically_hidden_list(self):
 
3934
        self.conf.store._load_from_string('''
 
3935
foo=bin
 
3936
bar=go
 
3937
start={foo
 
3938
middle=},{
 
3939
end=bar}
 
3940
hidden={start}{middle}{end}
 
3941
''')
 
3942
        # What matters is what the registration says, the conversion happens
 
3943
        # only after all expansions have been performed
 
3944
        self.registry.register(config.ListOption('hidden'))
 
3945
        self.assertEquals(['bin', 'go'],
 
3946
                          self.conf.get('hidden', expand=True))
 
3947
 
 
3948
 
 
3949
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
 
3950
 
 
3951
    def setUp(self):
 
3952
        super(TestStackCrossSectionsExpand, self).setUp()
 
3953
 
 
3954
    def get_config(self, location, string):
 
3955
        if string is None:
 
3956
            string = ''
 
3957
        # Since we don't save the config we won't strictly require to inherit
 
3958
        # from TestCaseInTempDir, but an error occurs so quickly...
 
3959
        c = config.LocationStack(location)
 
3960
        c.store._load_from_string(string)
 
3961
        return c
 
3962
 
 
3963
    def test_dont_cross_unrelated_section(self):
 
3964
        c = self.get_config('/another/branch/path','''
 
3965
[/one/branch/path]
 
3966
foo = hello
 
3967
bar = {foo}/2
 
3968
 
 
3969
[/another/branch/path]
 
3970
bar = {foo}/2
 
3971
''')
 
3972
        self.assertRaises(errors.ExpandingUnknownOption,
 
3973
                          c.get, 'bar', expand=True)
 
3974
 
 
3975
    def test_cross_related_sections(self):
 
3976
        c = self.get_config('/project/branch/path','''
 
3977
[/project]
 
3978
foo = qu
 
3979
 
 
3980
[/project/branch/path]
 
3981
bar = {foo}ux
 
3982
''')
 
3983
        self.assertEquals('quux', c.get('bar', expand=True))
 
3984
 
 
3985
 
 
3986
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
 
3987
 
 
3988
    def test_cross_global_locations(self):
 
3989
        l_store = config.LocationStore()
 
3990
        l_store._load_from_string('''
 
3991
[/branch]
 
3992
lfoo = loc-foo
 
3993
lbar = {gbar}
 
3994
''')
 
3995
        l_store.save()
 
3996
        g_store = config.GlobalStore()
 
3997
        g_store._load_from_string('''
 
3998
[DEFAULT]
 
3999
gfoo = {lfoo}
 
4000
gbar = glob-bar
 
4001
''')
 
4002
        g_store.save()
 
4003
        stack = config.LocationStack('/branch')
 
4004
        self.assertEquals('glob-bar', stack.get('lbar', expand=True))
 
4005
        self.assertEquals('loc-foo', stack.get('gfoo', expand=True))
 
4006
 
 
4007
 
 
4008
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
 
4009
 
 
4010
    def test_expand_locals_empty(self):
 
4011
        l_store = config.LocationStore()
 
4012
        l_store._load_from_string('''
 
4013
[/home/user/project]
 
4014
base = {basename}
 
4015
rel = {relpath}
 
4016
''')
 
4017
        l_store.save()
 
4018
        stack = config.LocationStack('/home/user/project/')
 
4019
        self.assertEquals('', stack.get('base', expand=True))
 
4020
        self.assertEquals('', stack.get('rel', expand=True))
 
4021
 
 
4022
    def test_expand_basename_locally(self):
 
4023
        l_store = config.LocationStore()
 
4024
        l_store._load_from_string('''
 
4025
[/home/user/project]
 
4026
bfoo = {basename}
 
4027
''')
 
4028
        l_store.save()
 
4029
        stack = config.LocationStack('/home/user/project/branch')
 
4030
        self.assertEquals('branch', stack.get('bfoo', expand=True))
 
4031
 
 
4032
    def test_expand_basename_locally_longer_path(self):
 
4033
        l_store = config.LocationStore()
 
4034
        l_store._load_from_string('''
 
4035
[/home/user]
 
4036
bfoo = {basename}
 
4037
''')
 
4038
        l_store.save()
 
4039
        stack = config.LocationStack('/home/user/project/dir/branch')
 
4040
        self.assertEquals('branch', stack.get('bfoo', expand=True))
 
4041
 
 
4042
    def test_expand_relpath_locally(self):
 
4043
        l_store = config.LocationStore()
 
4044
        l_store._load_from_string('''
 
4045
[/home/user/project]
 
4046
lfoo = loc-foo/{relpath}
 
4047
''')
 
4048
        l_store.save()
 
4049
        stack = config.LocationStack('/home/user/project/branch')
 
4050
        self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
 
4051
 
 
4052
    def test_expand_relpath_unknonw_in_global(self):
 
4053
        g_store = config.GlobalStore()
 
4054
        g_store._load_from_string('''
 
4055
[DEFAULT]
 
4056
gfoo = {relpath}
 
4057
''')
 
4058
        g_store.save()
 
4059
        stack = config.LocationStack('/home/user/project/branch')
 
4060
        self.assertRaises(errors.ExpandingUnknownOption,
 
4061
                          stack.get, 'gfoo', expand=True)
 
4062
 
 
4063
    def test_expand_local_option_locally(self):
 
4064
        l_store = config.LocationStore()
 
4065
        l_store._load_from_string('''
 
4066
[/home/user/project]
 
4067
lfoo = loc-foo/{relpath}
 
4068
lbar = {gbar}
 
4069
''')
 
4070
        l_store.save()
 
4071
        g_store = config.GlobalStore()
 
4072
        g_store._load_from_string('''
 
4073
[DEFAULT]
 
4074
gfoo = {lfoo}
 
4075
gbar = glob-bar
 
4076
''')
 
4077
        g_store.save()
 
4078
        stack = config.LocationStack('/home/user/project/branch')
 
4079
        self.assertEquals('glob-bar', stack.get('lbar', expand=True))
 
4080
        self.assertEquals('loc-foo/branch', stack.get('gfoo', expand=True))
 
4081
 
 
4082
    def test_locals_dont_leak(self):
 
4083
        """Make sure we chose the right local in presence of several sections.
 
4084
        """
 
4085
        l_store = config.LocationStore()
 
4086
        l_store._load_from_string('''
 
4087
[/home/user]
 
4088
lfoo = loc-foo/{relpath}
 
4089
[/home/user/project]
 
4090
lfoo = loc-foo/{relpath}
 
4091
''')
 
4092
        l_store.save()
 
4093
        stack = config.LocationStack('/home/user/project/branch')
 
4094
        self.assertEquals('loc-foo/branch', stack.get('lfoo', expand=True))
 
4095
        stack = config.LocationStack('/home/user/bar/baz')
 
4096
        self.assertEquals('loc-foo/bar/baz', stack.get('lfoo', expand=True))
 
4097
 
 
4098
 
 
4099
 
 
4100
class TestStackSet(TestStackWithTransport):
 
4101
 
 
4102
    def test_simple_set(self):
 
4103
        conf = self.get_stack(self)
 
4104
        self.assertEquals(None, conf.get('foo'))
 
4105
        conf.set('foo', 'baz')
 
4106
        # Did we get it back ?
 
4107
        self.assertEquals('baz', conf.get('foo'))
 
4108
 
 
4109
    def test_set_creates_a_new_section(self):
 
4110
        conf = self.get_stack(self)
 
4111
        conf.set('foo', 'baz')
 
4112
        self.assertEquals, 'baz', conf.get('foo')
 
4113
 
 
4114
    def test_set_hook(self):
 
4115
        calls = []
 
4116
        def hook(*args):
 
4117
            calls.append(args)
 
4118
        config.ConfigHooks.install_named_hook('set', hook, None)
 
4119
        self.assertLength(0, calls)
 
4120
        conf = self.get_stack(self)
 
4121
        conf.set('foo', 'bar')
 
4122
        self.assertLength(1, calls)
 
4123
        self.assertEquals((conf, 'foo', 'bar'), calls[0])
 
4124
 
 
4125
 
 
4126
class TestStackRemove(TestStackWithTransport):
 
4127
 
 
4128
    def test_remove_existing(self):
 
4129
        conf = self.get_stack(self)
 
4130
        conf.set('foo', 'bar')
 
4131
        self.assertEquals('bar', conf.get('foo'))
 
4132
        conf.remove('foo')
 
4133
        # Did we get it back ?
 
4134
        self.assertEquals(None, conf.get('foo'))
 
4135
 
 
4136
    def test_remove_unknown(self):
 
4137
        conf = self.get_stack(self)
 
4138
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
 
4139
 
 
4140
    def test_remove_hook(self):
 
4141
        calls = []
 
4142
        def hook(*args):
 
4143
            calls.append(args)
 
4144
        config.ConfigHooks.install_named_hook('remove', hook, None)
 
4145
        self.assertLength(0, calls)
 
4146
        conf = self.get_stack(self)
 
4147
        conf.set('foo', 'bar')
 
4148
        conf.remove('foo')
 
4149
        self.assertLength(1, calls)
 
4150
        self.assertEquals((conf, 'foo'), calls[0])
 
4151
 
 
4152
 
 
4153
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
 
4154
 
 
4155
    def setUp(self):
 
4156
        super(TestConfigGetOptions, self).setUp()
 
4157
        create_configs(self)
 
4158
 
 
4159
    def test_no_variable(self):
 
4160
        # Using branch should query branch, locations and bazaar
 
4161
        self.assertOptions([], self.branch_config)
 
4162
 
 
4163
    def test_option_in_bazaar(self):
 
4164
        self.bazaar_config.set_user_option('file', 'bazaar')
 
4165
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
 
4166
                           self.bazaar_config)
 
4167
 
 
4168
    def test_option_in_locations(self):
 
4169
        self.locations_config.set_user_option('file', 'locations')
 
4170
        self.assertOptions(
 
4171
            [('file', 'locations', self.tree.basedir, 'locations')],
 
4172
            self.locations_config)
 
4173
 
 
4174
    def test_option_in_branch(self):
 
4175
        self.branch_config.set_user_option('file', 'branch')
 
4176
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
 
4177
                           self.branch_config)
 
4178
 
 
4179
    def test_option_in_bazaar_and_branch(self):
 
4180
        self.bazaar_config.set_user_option('file', 'bazaar')
 
4181
        self.branch_config.set_user_option('file', 'branch')
 
4182
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
 
4183
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
4184
                           self.branch_config)
 
4185
 
 
4186
    def test_option_in_branch_and_locations(self):
 
4187
        # Hmm, locations override branch :-/
 
4188
        self.locations_config.set_user_option('file', 'locations')
 
4189
        self.branch_config.set_user_option('file', 'branch')
 
4190
        self.assertOptions(
 
4191
            [('file', 'locations', self.tree.basedir, 'locations'),
 
4192
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
4193
            self.branch_config)
 
4194
 
 
4195
    def test_option_in_bazaar_locations_and_branch(self):
 
4196
        self.bazaar_config.set_user_option('file', 'bazaar')
 
4197
        self.locations_config.set_user_option('file', 'locations')
 
4198
        self.branch_config.set_user_option('file', 'branch')
 
4199
        self.assertOptions(
 
4200
            [('file', 'locations', self.tree.basedir, 'locations'),
 
4201
             ('file', 'branch', 'DEFAULT', 'branch'),
 
4202
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
4203
            self.branch_config)
 
4204
 
 
4205
 
 
4206
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
 
4207
 
 
4208
    def setUp(self):
 
4209
        super(TestConfigRemoveOption, self).setUp()
 
4210
        create_configs_with_file_option(self)
 
4211
 
 
4212
    def test_remove_in_locations(self):
 
4213
        self.locations_config.remove_user_option('file', self.tree.basedir)
 
4214
        self.assertOptions(
 
4215
            [('file', 'branch', 'DEFAULT', 'branch'),
 
4216
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
4217
            self.branch_config)
 
4218
 
 
4219
    def test_remove_in_branch(self):
 
4220
        self.branch_config.remove_user_option('file')
 
4221
        self.assertOptions(
 
4222
            [('file', 'locations', self.tree.basedir, 'locations'),
 
4223
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
 
4224
            self.branch_config)
 
4225
 
 
4226
    def test_remove_in_bazaar(self):
 
4227
        self.bazaar_config.remove_user_option('file')
 
4228
        self.assertOptions(
 
4229
            [('file', 'locations', self.tree.basedir, 'locations'),
 
4230
             ('file', 'branch', 'DEFAULT', 'branch'),],
 
4231
            self.branch_config)
 
4232
 
 
4233
 
 
4234
class TestConfigGetSections(tests.TestCaseWithTransport):
 
4235
 
 
4236
    def setUp(self):
 
4237
        super(TestConfigGetSections, self).setUp()
 
4238
        create_configs(self)
 
4239
 
 
4240
    def assertSectionNames(self, expected, conf, name=None):
 
4241
        """Check which sections are returned for a given config.
 
4242
 
 
4243
        If fallback configurations exist their sections can be included.
 
4244
 
 
4245
        :param expected: A list of section names.
 
4246
 
 
4247
        :param conf: The configuration that will be queried.
 
4248
 
 
4249
        :param name: An optional section name that will be passed to
 
4250
            get_sections().
 
4251
        """
 
4252
        sections = list(conf._get_sections(name))
 
4253
        self.assertLength(len(expected), sections)
 
4254
        self.assertEqual(expected, [name for name, _, _ in sections])
 
4255
 
 
4256
    def test_bazaar_default_section(self):
 
4257
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
 
4258
 
 
4259
    def test_locations_default_section(self):
 
4260
        # No sections are defined in an empty file
 
4261
        self.assertSectionNames([], self.locations_config)
 
4262
 
 
4263
    def test_locations_named_section(self):
 
4264
        self.locations_config.set_user_option('file', 'locations')
 
4265
        self.assertSectionNames([self.tree.basedir], self.locations_config)
 
4266
 
 
4267
    def test_locations_matching_sections(self):
 
4268
        loc_config = self.locations_config
 
4269
        loc_config.set_user_option('file', 'locations')
 
4270
        # We need to cheat a bit here to create an option in sections above and
 
4271
        # below the 'location' one.
 
4272
        parser = loc_config._get_parser()
 
4273
        # locations.cong deals with '/' ignoring native os.sep
 
4274
        location_names = self.tree.basedir.split('/')
 
4275
        parent = '/'.join(location_names[:-1])
 
4276
        child = '/'.join(location_names + ['child'])
 
4277
        parser[parent] = {}
 
4278
        parser[parent]['file'] = 'parent'
 
4279
        parser[child] = {}
 
4280
        parser[child]['file'] = 'child'
 
4281
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
 
4282
 
 
4283
    def test_branch_data_default_section(self):
 
4284
        self.assertSectionNames([None],
 
4285
                                self.branch_config._get_branch_data_config())
 
4286
 
 
4287
    def test_branch_default_sections(self):
 
4288
        # No sections are defined in an empty locations file
 
4289
        self.assertSectionNames([None, 'DEFAULT'],
 
4290
                                self.branch_config)
 
4291
        # Unless we define an option
 
4292
        self.branch_config._get_location_config().set_user_option(
 
4293
            'file', 'locations')
 
4294
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
 
4295
                                self.branch_config)
 
4296
 
 
4297
    def test_bazaar_named_section(self):
 
4298
        # We need to cheat as the API doesn't give direct access to sections
 
4299
        # other than DEFAULT.
 
4300
        self.bazaar_config.set_alias('bazaar', 'bzr')
 
4301
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
 
4302
 
 
4303
 
1315
4304
class TestAuthenticationConfigFile(tests.TestCase):
1316
4305
    """Test the authentication.conf file matching"""
1317
4306
 
1332
4321
        self.assertEquals({}, conf._get_config())
1333
4322
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1334
4323
 
 
4324
    def test_non_utf8_config(self):
 
4325
        conf = config.AuthenticationConfig(_file=StringIO(
 
4326
                'foo = bar\xff'))
 
4327
        self.assertRaises(errors.ConfigContentError, conf._get_config)
 
4328
 
1335
4329
    def test_missing_auth_section_header(self):
1336
4330
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1337
4331
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1595
4589
 
1596
4590
    def test_username_defaults_prompts(self):
1597
4591
        # 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)
 
4592
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
 
4593
        self._check_default_username_prompt(
 
4594
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
 
4595
        self._check_default_username_prompt(
 
4596
            u'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1603
4597
 
1604
4598
    def test_username_default_no_prompt(self):
1605
4599
        conf = config.AuthenticationConfig()
1611
4605
    def test_password_default_prompts(self):
1612
4606
        # HTTP prompts can't be tested here, see test_http.py
1613
4607
        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)
 
4608
            u'FTP %(user)s@%(host)s password: ', 'ftp')
 
4609
        self._check_default_password_prompt(
 
4610
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
 
4611
        self._check_default_password_prompt(
 
4612
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
1619
4613
        # SMTP port handling is a bit special (it's handled if embedded in the
1620
4614
        # host too)
1621
4615
        # FIXME: should we: forbid that, extend it to other schemes, leave
1622
4616
        # 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)
 
4617
        self._check_default_password_prompt(
 
4618
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
 
4619
        self._check_default_password_prompt(
 
4620
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
 
4621
        self._check_default_password_prompt(
 
4622
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
1630
4623
 
1631
4624
    def test_ssh_password_emits_warning(self):
1632
4625
        conf = config.AuthenticationConfig(_file=StringIO(
1812
4805
# test_user_prompted ?
1813
4806
class TestAuthenticationRing(tests.TestCaseWithTransport):
1814
4807
    pass
 
4808
 
 
4809
 
 
4810
class TestAutoUserId(tests.TestCase):
 
4811
    """Test inferring an automatic user name."""
 
4812
 
 
4813
    def test_auto_user_id(self):
 
4814
        """Automatic inference of user name.
 
4815
 
 
4816
        This is a bit hard to test in an isolated way, because it depends on
 
4817
        system functions that go direct to /etc or perhaps somewhere else.
 
4818
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
 
4819
        to be able to choose a user name with no configuration.
 
4820
        """
 
4821
        if sys.platform == 'win32':
 
4822
            raise tests.TestSkipped(
 
4823
                "User name inference not implemented on win32")
 
4824
        realname, address = config._auto_user_id()
 
4825
        if os.path.exists('/etc/mailname'):
 
4826
            self.assertIsNot(None, realname)
 
4827
            self.assertIsNot(None, address)
 
4828
        else:
 
4829
            self.assertEquals((None, None), (realname, address))
 
4830
 
 
4831
 
 
4832
class EmailOptionTests(tests.TestCase):
 
4833
 
 
4834
    def test_default_email_uses_BZR_EMAIL(self):
 
4835
        conf = config.MemoryStack('email=jelmer@debian.org')
 
4836
        # BZR_EMAIL takes precedence over EMAIL
 
4837
        self.overrideEnv('BZR_EMAIL', 'jelmer@samba.org')
 
4838
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
 
4839
        self.assertEquals('jelmer@samba.org', conf.get('email'))
 
4840
 
 
4841
    def test_default_email_uses_EMAIL(self):
 
4842
        conf = config.MemoryStack('')
 
4843
        self.overrideEnv('BZR_EMAIL', None)
 
4844
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
 
4845
        self.assertEquals('jelmer@apache.org', conf.get('email'))
 
4846
 
 
4847
    def test_BZR_EMAIL_overrides(self):
 
4848
        conf = config.MemoryStack('email=jelmer@debian.org')
 
4849
        self.overrideEnv('BZR_EMAIL', 'jelmer@apache.org')
 
4850
        self.assertEquals('jelmer@apache.org', conf.get('email'))
 
4851
        self.overrideEnv('BZR_EMAIL', None)
 
4852
        self.overrideEnv('EMAIL', 'jelmer@samba.org')
 
4853
        self.assertEquals('jelmer@debian.org', conf.get('email'))