/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

UseĀ get_config_stack.

Show diffs side-by-side

added added

removed removed

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