/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/tests/test_config.py

  • Committer: Jelmer Vernooij
  • Date: 2018-05-09 23:53:11 UTC
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180509235311-k1zk8mwcb09b8vm0
Update TODO.

Show diffs side-by-side

added added

removed removed

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