~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: John Arbash Meinel
  • Date: 2010-01-13 16:23:07 UTC
  • mto: (4634.119.7 2.0)
  • mto: This revision was merged to the branch mainline in revision 4959.
  • Revision ID: john@arbash-meinel.com-20100113162307-0bs82td16gzih827
Update the MANIFEST.in file.

Show diffs side-by-side

added added

removed removed

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