~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Vincent Ladeuil
  • Date: 2012-03-13 16:42:20 UTC
  • mto: This revision was merged to the branch mainline in revision 6512.
  • Revision ID: v.ladeuil+lp@free.fr-20120313164220-atkou2zprhlspmwg
Mention that a given config option cannot be safely handled via both APIs at the same time.

Show diffs side-by-side

added added

removed removed

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