/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: 2017-06-04 19:17:13 UTC
  • mfrom: (0.193.10 trunk)
  • mto: This revision was merged to the branch mainline in revision 6778.
  • Revision ID: jelmer@jelmer.uk-20170604191713-hau7dfsqsl035slm
Bundle the cvs plugin.

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