~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Patch Queue Manager
  • Date: 2016-04-21 04:10:52 UTC
  • mfrom: (6616.1.1 fix-en-user-guide)
  • Revision ID: pqm@pqm.ubuntu.com-20160421041052-clcye7ns1qcl2n7w
(richard-wilbur) Ensure build of English use guide always uses English text
 even when user's locale specifies a different language. (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

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