~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: John Arbash Meinel
  • Date: 2008-05-06 14:34:57 UTC
  • mto: This revision was merged to the branch mainline in revision 3438.
  • Revision ID: john@arbash-meinel.com-20080506143457-mytwmwshmz1bu1uf
minor doc clarification for decentralized with shared-mainline

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 by Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
17
17
 
18
18
"""Tests for finding and reading the bzr config file[s]."""
19
19
# import system imports here
20
 
from bzrlib.util.configobj.configobj import ConfigObj, ConfigObjError
21
20
from cStringIO import StringIO
22
21
import os
23
22
import sys
24
23
 
25
24
#import bzrlib specific imports here
26
 
import bzrlib.config as config
27
 
import bzrlib.errors as errors
28
 
from bzrlib.tests import TestCase, TestCaseInTempDir
 
25
from bzrlib import (
 
26
    branch,
 
27
    bzrdir,
 
28
    config,
 
29
    errors,
 
30
    osutils,
 
31
    mail_client,
 
32
    ui,
 
33
    urlutils,
 
34
    tests,
 
35
    trace,
 
36
    transport,
 
37
    )
 
38
from bzrlib.util.configobj import configobj
29
39
 
30
40
 
31
41
sample_long_alias="log -r-15..-1 --line"
32
 
sample_config_text = ("[DEFAULT]\n"
33
 
                      u"email=Erik B\u00e5gfors <erik@bagfors.nu>\n"
34
 
                      "editor=vim\n"
35
 
                      "gpg_signing_command=gnome-gpg\n"
36
 
                      "log_format=short\n"
37
 
                      "user_global_option=something\n"
38
 
                      "[ALIASES]\n"
39
 
                      "h=help\n"
40
 
                      "ll=" + sample_long_alias + "\n")
41
 
 
42
 
 
43
 
sample_always_signatures = ("[DEFAULT]\n"
44
 
                            "check_signatures=ignore\n"
45
 
                            "create_signatures=always")
46
 
 
47
 
 
48
 
sample_ignore_signatures = ("[DEFAULT]\n"
49
 
                            "check_signatures=require\n"
50
 
                            "create_signatures=never")
51
 
 
52
 
 
53
 
sample_maybe_signatures = ("[DEFAULT]\n"
54
 
                            "check_signatures=ignore\n"
55
 
                            "create_signatures=when-required")
56
 
 
57
 
 
58
 
sample_branches_text = ("[http://www.example.com]\n"
59
 
                        "# Top level policy\n"
60
 
                        "email=Robert Collins <robertc@example.org>\n"
61
 
                        "[http://www.example.com/useglobal]\n"
62
 
                        "# different project, forces global lookup\n"
63
 
                        "recurse=false\n"
64
 
                        "[/b/]\n"
65
 
                        "check_signatures=require\n"
66
 
                        "# test trailing / matching with no children\n"
67
 
                        "[/a/]\n"
68
 
                        "check_signatures=check-available\n"
69
 
                        "gpg_signing_command=false\n"
70
 
                        "user_local_option=local\n"
71
 
                        "# test trailing / matching\n"
72
 
                        "[/a/*]\n"
73
 
                        "#subdirs will match but not the parent\n"
74
 
                        "recurse=False\n"
75
 
                        "[/a/c]\n"
76
 
                        "check_signatures=ignore\n"
77
 
                        "post_commit=bzrlib.tests.test_config.post_commit\n"
78
 
                        "#testing explicit beats globs\n")
79
 
 
 
42
sample_config_text = u"""
 
43
[DEFAULT]
 
44
email=Erik B\u00e5gfors <erik@bagfors.nu>
 
45
editor=vim
 
46
gpg_signing_command=gnome-gpg
 
47
log_format=short
 
48
user_global_option=something
 
49
[ALIASES]
 
50
h=help
 
51
ll=""" + sample_long_alias + "\n"
 
52
 
 
53
 
 
54
sample_always_signatures = """
 
55
[DEFAULT]
 
56
check_signatures=ignore
 
57
create_signatures=always
 
58
"""
 
59
 
 
60
sample_ignore_signatures = """
 
61
[DEFAULT]
 
62
check_signatures=require
 
63
create_signatures=never
 
64
"""
 
65
 
 
66
sample_maybe_signatures = """
 
67
[DEFAULT]
 
68
check_signatures=ignore
 
69
create_signatures=when-required
 
70
"""
 
71
 
 
72
sample_branches_text = """
 
73
[http://www.example.com]
 
74
# Top level policy
 
75
email=Robert Collins <robertc@example.org>
 
76
normal_option = normal
 
77
appendpath_option = append
 
78
appendpath_option:policy = appendpath
 
79
norecurse_option = norecurse
 
80
norecurse_option:policy = norecurse
 
81
[http://www.example.com/ignoreparent]
 
82
# different project: ignore parent dir config
 
83
ignore_parents=true
 
84
[http://www.example.com/norecurse]
 
85
# configuration items that only apply to this dir
 
86
recurse=false
 
87
normal_option = norecurse
 
88
[http://www.example.com/dir]
 
89
appendpath_option = normal
 
90
[/b/]
 
91
check_signatures=require
 
92
# test trailing / matching with no children
 
93
[/a/]
 
94
check_signatures=check-available
 
95
gpg_signing_command=false
 
96
user_local_option=local
 
97
# test trailing / matching
 
98
[/a/*]
 
99
#subdirs will match but not the parent
 
100
[/a/c]
 
101
check_signatures=ignore
 
102
post_commit=bzrlib.tests.test_config.post_commit
 
103
#testing explicit beats globs
 
104
"""
80
105
 
81
106
 
82
107
class InstrumentedConfigObj(object):
96
121
    def __setitem__(self, key, value):
97
122
        self._calls.append(('__setitem__', key, value))
98
123
 
 
124
    def __delitem__(self, key):
 
125
        self._calls.append(('__delitem__', key))
 
126
 
 
127
    def keys(self):
 
128
        self._calls.append(('keys',))
 
129
        return []
 
130
 
99
131
    def write(self, arg):
100
132
        self._calls.append(('write',))
101
133
 
 
134
    def as_bool(self, value):
 
135
        self._calls.append(('as_bool', value))
 
136
        return False
 
137
 
 
138
    def get_value(self, section, name):
 
139
        self._calls.append(('get_value', section, name))
 
140
        return None
 
141
 
102
142
 
103
143
class FakeBranch(object):
104
144
 
105
 
    def __init__(self):
106
 
        self.base = "http://example.com/branches/demo"
107
 
        self.control_files = FakeControlFiles()
 
145
    def __init__(self, base=None, user_id=None):
 
146
        if base is None:
 
147
            self.base = "http://example.com/branches/demo"
 
148
        else:
 
149
            self.base = base
 
150
        self.control_files = FakeControlFiles(user_id=user_id)
 
151
 
 
152
    def lock_write(self):
 
153
        pass
 
154
 
 
155
    def unlock(self):
 
156
        pass
108
157
 
109
158
 
110
159
class FakeControlFiles(object):
111
160
 
112
 
    def __init__(self):
113
 
        self.email = 'Robert Collins <robertc@example.net>\n'
 
161
    def __init__(self, user_id=None):
 
162
        self.files = {}
 
163
        if user_id:
 
164
            self.files['email'] = user_id
 
165
        self._transport = self
114
166
 
115
167
    def get_utf8(self, filename):
116
 
        if filename != 'email':
117
 
            raise NotImplementedError
118
 
        if self.email is not None:
119
 
            return StringIO(self.email)
120
 
        raise errors.NoSuchFile(filename)
 
168
        # from LockableFiles
 
169
        raise AssertionError("get_utf8 should no longer be used")
 
170
 
 
171
    def get(self, filename):
 
172
        # from Transport
 
173
        try:
 
174
            return StringIO(self.files[filename])
 
175
        except KeyError:
 
176
            raise errors.NoSuchFile(filename)
 
177
 
 
178
    def get_bytes(self, filename):
 
179
        # from Transport
 
180
        try:
 
181
            return self.files[filename]
 
182
        except KeyError:
 
183
            raise errors.NoSuchFile(filename)
 
184
 
 
185
    def put(self, filename, fileobj):
 
186
        self.files[filename] = fileobj.read()
 
187
 
 
188
    def put_file(self, filename, fileobj):
 
189
        return self.put(filename, fileobj)
121
190
 
122
191
 
123
192
class InstrumentedConfig(config.Config):
124
193
    """An instrumented config that supplies stubs for template methods."""
125
 
    
 
194
 
126
195
    def __init__(self):
127
196
        super(InstrumentedConfig, self).__init__()
128
197
        self._calls = []
144
213
active = True
145
214
nonactive = False
146
215
"""
147
 
class TestConfigObj(TestCase):
 
216
 
 
217
 
 
218
class TestConfigObj(tests.TestCase):
 
219
 
148
220
    def test_get_bool(self):
149
 
        from bzrlib.config import ConfigObj
150
 
        co = ConfigObj(StringIO(bool_config))
 
221
        co = config.ConfigObj(StringIO(bool_config))
151
222
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
152
223
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
153
224
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
154
225
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
155
226
 
156
 
 
157
 
class TestConfig(TestCase):
 
227
    def test_hash_sign_in_value(self):
 
228
        """
 
229
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
 
230
        treated as comments when read in again. (#86838)
 
231
        """
 
232
        co = config.ConfigObj()
 
233
        co['test'] = 'foo#bar'
 
234
        lines = co.write()
 
235
        self.assertEqual(lines, ['test = "foo#bar"'])
 
236
        co2 = config.ConfigObj(lines)
 
237
        self.assertEqual(co2['test'], 'foo#bar')
 
238
 
 
239
 
 
240
erroneous_config = """[section] # line 1
 
241
good=good # line 2
 
242
[section] # line 3
 
243
whocares=notme # line 4
 
244
"""
 
245
 
 
246
 
 
247
class TestConfigObjErrors(tests.TestCase):
 
248
 
 
249
    def test_duplicate_section_name_error_line(self):
 
250
        try:
 
251
            co = configobj.ConfigObj(StringIO(erroneous_config),
 
252
                                     raise_errors=True)
 
253
        except config.configobj.DuplicateError, e:
 
254
            self.assertEqual(3, e.line_number)
 
255
        else:
 
256
            self.fail('Error in config file not detected')
 
257
 
 
258
 
 
259
class TestConfig(tests.TestCase):
158
260
 
159
261
    def test_constructs(self):
160
262
        config.Config()
161
 
 
 
263
 
162
264
    def test_no_default_editor(self):
163
265
        self.assertRaises(NotImplementedError, config.Config().get_editor)
164
266
 
210
312
        self.assertEqual('long', my_config.log_format())
211
313
 
212
314
 
213
 
class TestConfigPath(TestCase):
 
315
class TestConfigPath(tests.TestCase):
214
316
 
215
317
    def setUp(self):
216
318
        super(TestConfigPath, self).setUp()
217
 
        self.old_home = os.environ.get('HOME', None)
218
 
        self.old_appdata = os.environ.get('APPDATA', None)
219
319
        os.environ['HOME'] = '/home/bogus'
220
 
        os.environ['APPDATA'] = \
221
 
            r'C:\Documents and Settings\bogus\Application Data'
 
320
        if sys.platform == 'win32':
 
321
            os.environ['BZR_HOME'] = \
 
322
                r'C:\Documents and Settings\bogus\Application Data'
 
323
            self.bzr_home = \
 
324
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
 
325
        else:
 
326
            self.bzr_home = '/home/bogus/.bazaar'
222
327
 
223
 
    def tearDown(self):
224
 
        if self.old_home is None:
225
 
            del os.environ['HOME']
226
 
        else:
227
 
            os.environ['HOME'] = self.old_home
228
 
        if self.old_appdata is None:
229
 
            del os.environ['APPDATA']
230
 
        else:
231
 
            os.environ['APPDATA'] = self.old_appdata
232
 
        super(TestConfigPath, self).tearDown()
233
 
    
234
328
    def test_config_dir(self):
235
 
        if sys.platform == 'win32':
236
 
            self.assertEqual(config.config_dir(), 
237
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0')
238
 
        else:
239
 
            self.assertEqual(config.config_dir(), '/home/bogus/.bazaar')
 
329
        self.assertEqual(config.config_dir(), self.bzr_home)
240
330
 
241
331
    def test_config_filename(self):
242
 
        if sys.platform == 'win32':
243
 
            self.assertEqual(config.config_filename(), 
244
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/bazaar.conf')
245
 
        else:
246
 
            self.assertEqual(config.config_filename(),
247
 
                             '/home/bogus/.bazaar/bazaar.conf')
 
332
        self.assertEqual(config.config_filename(),
 
333
                         self.bzr_home + '/bazaar.conf')
248
334
 
249
335
    def test_branches_config_filename(self):
250
 
        if sys.platform == 'win32':
251
 
            self.assertEqual(config.branches_config_filename(), 
252
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/branches.conf')
253
 
        else:
254
 
            self.assertEqual(config.branches_config_filename(),
255
 
                             '/home/bogus/.bazaar/branches.conf')
256
 
 
257
 
class TestIniConfig(TestCase):
 
336
        self.assertEqual(config.branches_config_filename(),
 
337
                         self.bzr_home + '/branches.conf')
 
338
 
 
339
    def test_locations_config_filename(self):
 
340
        self.assertEqual(config.locations_config_filename(),
 
341
                         self.bzr_home + '/locations.conf')
 
342
 
 
343
    def test_authentication_config_filename(self):
 
344
        self.assertEqual(config.authentication_config_filename(),
 
345
                         self.bzr_home + '/authentication.conf')
 
346
 
 
347
 
 
348
class TestIniConfig(tests.TestCase):
258
349
 
259
350
    def test_contructs(self):
260
351
        my_config = config.IniBasedConfig("nothing")
264
355
        my_config = config.IniBasedConfig(None)
265
356
        self.failUnless(
266
357
            isinstance(my_config._get_parser(file=config_file),
267
 
                        ConfigObj))
 
358
                        configobj.ConfigObj))
268
359
 
269
360
    def test_cached(self):
270
361
        config_file = StringIO(sample_config_text.encode('utf-8'))
273
364
        self.failUnless(my_config._get_parser() is parser)
274
365
 
275
366
 
276
 
class TestGetConfig(TestCase):
 
367
class TestGetConfig(tests.TestCase):
277
368
 
278
369
    def test_constructs(self):
279
370
        my_config = config.GlobalConfig()
280
371
 
281
372
    def test_calls_read_filenames(self):
282
 
        # replace the class that is constructured, to check its parameters
 
373
        # replace the class that is constructed, to check its parameters
283
374
        oldparserclass = config.ConfigObj
284
375
        config.ConfigObj = InstrumentedConfigObj
285
376
        my_config = config.GlobalConfig()
292
383
                                          'utf-8')])
293
384
 
294
385
 
295
 
class TestBranchConfig(TestCaseInTempDir):
 
386
class TestBranchConfig(tests.TestCaseWithTransport):
296
387
 
297
388
    def test_constructs(self):
298
389
        branch = FakeBranch()
306
397
        self.assertEqual(branch.base, location_config.location)
307
398
        self.failUnless(location_config is my_config._get_location_config())
308
399
 
309
 
 
310
 
class TestGlobalConfigItems(TestCase):
 
400
    def test_get_config(self):
 
401
        """The Branch.get_config method works properly"""
 
402
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
 
403
        my_config = b.get_config()
 
404
        self.assertIs(my_config.get_user_option('wacky'), None)
 
405
        my_config.set_user_option('wacky', 'unlikely')
 
406
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
 
407
 
 
408
        # Ensure we get the same thing if we start again
 
409
        b2 = branch.Branch.open('.')
 
410
        my_config2 = b2.get_config()
 
411
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
 
412
 
 
413
    def test_has_explicit_nickname(self):
 
414
        b = self.make_branch('.')
 
415
        self.assertFalse(b.get_config().has_explicit_nickname())
 
416
        b.nick = 'foo'
 
417
        self.assertTrue(b.get_config().has_explicit_nickname())
 
418
 
 
419
    def test_config_url(self):
 
420
        """The Branch.get_config will use section that uses a local url"""
 
421
        branch = self.make_branch('branch')
 
422
        self.assertEqual('branch', branch.nick)
 
423
 
 
424
        locations = config.locations_config_filename()
 
425
        config.ensure_config_dir_exists()
 
426
        local_url = urlutils.local_path_to_url('branch')
 
427
        open(locations, 'wb').write('[%s]\nnickname = foobar' 
 
428
                                    % (local_url,))
 
429
        self.assertEqual('foobar', branch.nick)
 
430
 
 
431
    def test_config_local_path(self):
 
432
        """The Branch.get_config will use a local system path"""
 
433
        branch = self.make_branch('branch')
 
434
        self.assertEqual('branch', branch.nick)
 
435
 
 
436
        locations = config.locations_config_filename()
 
437
        config.ensure_config_dir_exists()
 
438
        open(locations, 'wb').write('[%s/branch]\nnickname = barry' 
 
439
                                    % (osutils.getcwd().encode('utf8'),))
 
440
        self.assertEqual('barry', branch.nick)
 
441
 
 
442
    def test_config_creates_local(self):
 
443
        """Creating a new entry in config uses a local path."""
 
444
        branch = self.make_branch('branch', format='knit')
 
445
        branch.set_push_location('http://foobar')
 
446
        locations = config.locations_config_filename()
 
447
        local_path = osutils.getcwd().encode('utf8')
 
448
        # Surprisingly ConfigObj doesn't create a trailing newline
 
449
        self.check_file_contents(locations,
 
450
                                 '[%s/branch]\n'
 
451
                                 'push_location = http://foobar\n'
 
452
                                 'push_location:policy = norecurse\n'
 
453
                                 % (local_path,))
 
454
 
 
455
    def test_autonick_urlencoded(self):
 
456
        b = self.make_branch('!repo')
 
457
        self.assertEqual('!repo', b.get_config().get_nickname())
 
458
 
 
459
    def test_warn_if_masked(self):
 
460
        _warning = trace.warning
 
461
        warnings = []
 
462
        def warning(*args):
 
463
            warnings.append(args[0] % args[1:])
 
464
 
 
465
        def set_option(store, warn_masked=True):
 
466
            warnings[:] = []
 
467
            conf.set_user_option('example_option', repr(store), store=store,
 
468
                                 warn_masked=warn_masked)
 
469
        def assertWarning(warning):
 
470
            if warning is None:
 
471
                self.assertEqual(0, len(warnings))
 
472
            else:
 
473
                self.assertEqual(1, len(warnings))
 
474
                self.assertEqual(warning, warnings[0])
 
475
        trace.warning = warning
 
476
        try:
 
477
            branch = self.make_branch('.')
 
478
            conf = branch.get_config()
 
479
            set_option(config.STORE_GLOBAL)
 
480
            assertWarning(None)
 
481
            set_option(config.STORE_BRANCH)
 
482
            assertWarning(None)
 
483
            set_option(config.STORE_GLOBAL)
 
484
            assertWarning('Value "4" is masked by "3" from branch.conf')
 
485
            set_option(config.STORE_GLOBAL, warn_masked=False)
 
486
            assertWarning(None)
 
487
            set_option(config.STORE_LOCATION)
 
488
            assertWarning(None)
 
489
            set_option(config.STORE_BRANCH)
 
490
            assertWarning('Value "3" is masked by "0" from locations.conf')
 
491
            set_option(config.STORE_BRANCH, warn_masked=False)
 
492
            assertWarning(None)
 
493
        finally:
 
494
            trace.warning = _warning
 
495
 
 
496
 
 
497
class TestGlobalConfigItems(tests.TestCase):
311
498
 
312
499
    def test_user_id(self):
313
500
        config_file = StringIO(sample_config_text.encode('utf-8'))
387
574
        my_config = self._get_sample_config()
388
575
        self.assertEqual("something",
389
576
                         my_config.get_user_option('user_global_option'))
390
 
        
 
577
 
391
578
    def test_post_commit_default(self):
392
579
        my_config = self._get_sample_config()
393
580
        self.assertEqual(None, my_config.post_commit())
409
596
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
410
597
 
411
598
 
412
 
class TestLocationConfig(TestCaseInTempDir):
 
599
class TestLocationConfig(tests.TestCaseInTempDir):
413
600
 
414
601
    def test_constructs(self):
415
602
        my_config = config.LocationConfig('http://example.com')
419
606
        # This is testing the correct file names are provided.
420
607
        # TODO: consolidate with the test for GlobalConfigs filename checks.
421
608
        #
422
 
        # replace the class that is constructured, to check its parameters
 
609
        # replace the class that is constructed, to check its parameters
423
610
        oldparserclass = config.ConfigObj
424
611
        config.ConfigObj = InstrumentedConfigObj
425
 
        my_config = config.LocationConfig('http://www.example.com')
426
612
        try:
 
613
            my_config = config.LocationConfig('http://www.example.com')
427
614
            parser = my_config._get_parser()
428
615
        finally:
429
616
            config.ConfigObj = oldparserclass
430
617
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
431
618
        self.assertEqual(parser._calls,
432
 
                         [('__init__', config.branches_config_filename(),
 
619
                         [('__init__', config.locations_config_filename(),
433
620
                           'utf-8')])
 
621
        config.ensure_config_dir_exists()
 
622
        #os.mkdir(config.config_dir())
 
623
        f = file(config.branches_config_filename(), 'wb')
 
624
        f.write('')
 
625
        f.close()
 
626
        oldparserclass = config.ConfigObj
 
627
        config.ConfigObj = InstrumentedConfigObj
 
628
        try:
 
629
            my_config = config.LocationConfig('http://www.example.com')
 
630
            parser = my_config._get_parser()
 
631
        finally:
 
632
            config.ConfigObj = oldparserclass
434
633
 
435
634
    def test_get_global_config(self):
436
 
        my_config = config.LocationConfig('http://example.com')
 
635
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
437
636
        global_config = my_config._get_global_config()
438
637
        self.failUnless(isinstance(global_config, config.GlobalConfig))
439
638
        self.failUnless(global_config is my_config._get_global_config())
440
639
 
441
 
    def test__get_section_no_match(self):
442
 
        self.get_location_config('/')
443
 
        self.assertEqual(None, self.my_config._get_section())
444
 
        
445
 
    def test__get_section_exact(self):
446
 
        self.get_location_config('http://www.example.com')
447
 
        self.assertEqual('http://www.example.com',
448
 
                         self.my_config._get_section())
449
 
   
450
 
    def test__get_section_suffix_does_not(self):
451
 
        self.get_location_config('http://www.example.com-com')
452
 
        self.assertEqual(None, self.my_config._get_section())
453
 
 
454
 
    def test__get_section_subdir_recursive(self):
455
 
        self.get_location_config('http://www.example.com/com')
456
 
        self.assertEqual('http://www.example.com',
457
 
                         self.my_config._get_section())
458
 
 
459
 
    def test__get_section_subdir_matches(self):
460
 
        self.get_location_config('http://www.example.com/useglobal')
461
 
        self.assertEqual('http://www.example.com/useglobal',
462
 
                         self.my_config._get_section())
463
 
 
464
 
    def test__get_section_subdir_nonrecursive(self):
465
 
        self.get_location_config(
466
 
            'http://www.example.com/useglobal/childbranch')
467
 
        self.assertEqual('http://www.example.com',
468
 
                         self.my_config._get_section())
469
 
 
470
 
    def test__get_section_subdir_trailing_slash(self):
471
 
        self.get_location_config('/b')
472
 
        self.assertEqual('/b/', self.my_config._get_section())
473
 
 
474
 
    def test__get_section_subdir_child(self):
475
 
        self.get_location_config('/a/foo')
476
 
        self.assertEqual('/a/*', self.my_config._get_section())
477
 
 
478
 
    def test__get_section_subdir_child_child(self):
479
 
        self.get_location_config('/a/foo/bar')
480
 
        self.assertEqual('/a/', self.my_config._get_section())
481
 
 
482
 
    def test__get_section_trailing_slash_with_children(self):
483
 
        self.get_location_config('/a/')
484
 
        self.assertEqual('/a/', self.my_config._get_section())
485
 
 
486
 
    def test__get_section_explicit_over_glob(self):
487
 
        self.get_location_config('/a/c')
488
 
        self.assertEqual('/a/c', self.my_config._get_section())
489
 
 
 
640
    def test__get_matching_sections_no_match(self):
 
641
        self.get_branch_config('/')
 
642
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
643
 
 
644
    def test__get_matching_sections_exact(self):
 
645
        self.get_branch_config('http://www.example.com')
 
646
        self.assertEqual([('http://www.example.com', '')],
 
647
                         self.my_location_config._get_matching_sections())
 
648
 
 
649
    def test__get_matching_sections_suffix_does_not(self):
 
650
        self.get_branch_config('http://www.example.com-com')
 
651
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
652
 
 
653
    def test__get_matching_sections_subdir_recursive(self):
 
654
        self.get_branch_config('http://www.example.com/com')
 
655
        self.assertEqual([('http://www.example.com', 'com')],
 
656
                         self.my_location_config._get_matching_sections())
 
657
 
 
658
    def test__get_matching_sections_ignoreparent(self):
 
659
        self.get_branch_config('http://www.example.com/ignoreparent')
 
660
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
 
661
                         self.my_location_config._get_matching_sections())
 
662
 
 
663
    def test__get_matching_sections_ignoreparent_subdir(self):
 
664
        self.get_branch_config(
 
665
            'http://www.example.com/ignoreparent/childbranch')
 
666
        self.assertEqual([('http://www.example.com/ignoreparent',
 
667
                           'childbranch')],
 
668
                         self.my_location_config._get_matching_sections())
 
669
 
 
670
    def test__get_matching_sections_subdir_trailing_slash(self):
 
671
        self.get_branch_config('/b')
 
672
        self.assertEqual([('/b/', '')],
 
673
                         self.my_location_config._get_matching_sections())
 
674
 
 
675
    def test__get_matching_sections_subdir_child(self):
 
676
        self.get_branch_config('/a/foo')
 
677
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
 
678
                         self.my_location_config._get_matching_sections())
 
679
 
 
680
    def test__get_matching_sections_subdir_child_child(self):
 
681
        self.get_branch_config('/a/foo/bar')
 
682
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
 
683
                         self.my_location_config._get_matching_sections())
 
684
 
 
685
    def test__get_matching_sections_trailing_slash_with_children(self):
 
686
        self.get_branch_config('/a/')
 
687
        self.assertEqual([('/a/', '')],
 
688
                         self.my_location_config._get_matching_sections())
 
689
 
 
690
    def test__get_matching_sections_explicit_over_glob(self):
 
691
        # XXX: 2006-09-08 jamesh
 
692
        # This test only passes because ord('c') > ord('*').  If there
 
693
        # was a config section for '/a/?', it would get precedence
 
694
        # over '/a/c'.
 
695
        self.get_branch_config('/a/c')
 
696
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
 
697
                         self.my_location_config._get_matching_sections())
 
698
 
 
699
    def test__get_option_policy_normal(self):
 
700
        self.get_branch_config('http://www.example.com')
 
701
        self.assertEqual(
 
702
            self.my_location_config._get_config_policy(
 
703
            'http://www.example.com', 'normal_option'),
 
704
            config.POLICY_NONE)
 
705
 
 
706
    def test__get_option_policy_norecurse(self):
 
707
        self.get_branch_config('http://www.example.com')
 
708
        self.assertEqual(
 
709
            self.my_location_config._get_option_policy(
 
710
            'http://www.example.com', 'norecurse_option'),
 
711
            config.POLICY_NORECURSE)
 
712
        # Test old recurse=False setting:
 
713
        self.assertEqual(
 
714
            self.my_location_config._get_option_policy(
 
715
            'http://www.example.com/norecurse', 'normal_option'),
 
716
            config.POLICY_NORECURSE)
 
717
 
 
718
    def test__get_option_policy_normal(self):
 
719
        self.get_branch_config('http://www.example.com')
 
720
        self.assertEqual(
 
721
            self.my_location_config._get_option_policy(
 
722
            'http://www.example.com', 'appendpath_option'),
 
723
            config.POLICY_APPENDPATH)
490
724
 
491
725
    def test_location_without_username(self):
492
 
        self.get_location_config('http://www.example.com/useglobal')
 
726
        self.get_branch_config('http://www.example.com/ignoreparent')
493
727
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
494
728
                         self.my_config.username())
495
729
 
496
730
    def test_location_not_listed(self):
497
731
        """Test that the global username is used when no location matches"""
498
 
        self.get_location_config('/home/robertc/sources')
 
732
        self.get_branch_config('/home/robertc/sources')
499
733
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
500
734
                         self.my_config.username())
501
735
 
502
736
    def test_overriding_location(self):
503
 
        self.get_location_config('http://www.example.com/foo')
 
737
        self.get_branch_config('http://www.example.com/foo')
504
738
        self.assertEqual('Robert Collins <robertc@example.org>',
505
739
                         self.my_config.username())
506
740
 
507
741
    def test_signatures_not_set(self):
508
 
        self.get_location_config('http://www.example.com',
 
742
        self.get_branch_config('http://www.example.com',
509
743
                                 global_config=sample_ignore_signatures)
510
744
        self.assertEqual(config.CHECK_ALWAYS,
511
745
                         self.my_config.signature_checking())
513
747
                         self.my_config.signing_policy())
514
748
 
515
749
    def test_signatures_never(self):
516
 
        self.get_location_config('/a/c')
 
750
        self.get_branch_config('/a/c')
517
751
        self.assertEqual(config.CHECK_NEVER,
518
752
                         self.my_config.signature_checking())
519
 
        
 
753
 
520
754
    def test_signatures_when_available(self):
521
 
        self.get_location_config('/a/', global_config=sample_ignore_signatures)
 
755
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
522
756
        self.assertEqual(config.CHECK_IF_POSSIBLE,
523
757
                         self.my_config.signature_checking())
524
 
        
 
758
 
525
759
    def test_signatures_always(self):
526
 
        self.get_location_config('/b')
 
760
        self.get_branch_config('/b')
527
761
        self.assertEqual(config.CHECK_ALWAYS,
528
762
                         self.my_config.signature_checking())
529
 
        
 
763
 
530
764
    def test_gpg_signing_command(self):
531
 
        self.get_location_config('/b')
 
765
        self.get_branch_config('/b')
532
766
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
533
767
 
534
768
    def test_gpg_signing_command_missing(self):
535
 
        self.get_location_config('/a')
 
769
        self.get_branch_config('/a')
536
770
        self.assertEqual("false", self.my_config.gpg_signing_command())
537
771
 
538
772
    def test_get_user_option_global(self):
539
 
        self.get_location_config('/a')
 
773
        self.get_branch_config('/a')
540
774
        self.assertEqual('something',
541
775
                         self.my_config.get_user_option('user_global_option'))
542
776
 
543
777
    def test_get_user_option_local(self):
544
 
        self.get_location_config('/a')
 
778
        self.get_branch_config('/a')
545
779
        self.assertEqual('local',
546
780
                         self.my_config.get_user_option('user_local_option'))
547
 
        
 
781
 
 
782
    def test_get_user_option_appendpath(self):
 
783
        # returned as is for the base path:
 
784
        self.get_branch_config('http://www.example.com')
 
785
        self.assertEqual('append',
 
786
                         self.my_config.get_user_option('appendpath_option'))
 
787
        # Extra path components get appended:
 
788
        self.get_branch_config('http://www.example.com/a/b/c')
 
789
        self.assertEqual('append/a/b/c',
 
790
                         self.my_config.get_user_option('appendpath_option'))
 
791
        # Overriden for http://www.example.com/dir, where it is a
 
792
        # normal option:
 
793
        self.get_branch_config('http://www.example.com/dir/a/b/c')
 
794
        self.assertEqual('normal',
 
795
                         self.my_config.get_user_option('appendpath_option'))
 
796
 
 
797
    def test_get_user_option_norecurse(self):
 
798
        self.get_branch_config('http://www.example.com')
 
799
        self.assertEqual('norecurse',
 
800
                         self.my_config.get_user_option('norecurse_option'))
 
801
        self.get_branch_config('http://www.example.com/dir')
 
802
        self.assertEqual(None,
 
803
                         self.my_config.get_user_option('norecurse_option'))
 
804
        # http://www.example.com/norecurse is a recurse=False section
 
805
        # that redefines normal_option.  Subdirectories do not pick up
 
806
        # this redefinition.
 
807
        self.get_branch_config('http://www.example.com/norecurse')
 
808
        self.assertEqual('norecurse',
 
809
                         self.my_config.get_user_option('normal_option'))
 
810
        self.get_branch_config('http://www.example.com/norecurse/subdir')
 
811
        self.assertEqual('normal',
 
812
                         self.my_config.get_user_option('normal_option'))
 
813
 
 
814
    def test_set_user_option_norecurse(self):
 
815
        self.get_branch_config('http://www.example.com')
 
816
        self.my_config.set_user_option('foo', 'bar',
 
817
                                       store=config.STORE_LOCATION_NORECURSE)
 
818
        self.assertEqual(
 
819
            self.my_location_config._get_option_policy(
 
820
            'http://www.example.com', 'foo'),
 
821
            config.POLICY_NORECURSE)
 
822
 
 
823
    def test_set_user_option_appendpath(self):
 
824
        self.get_branch_config('http://www.example.com')
 
825
        self.my_config.set_user_option('foo', 'bar',
 
826
                                       store=config.STORE_LOCATION_APPENDPATH)
 
827
        self.assertEqual(
 
828
            self.my_location_config._get_option_policy(
 
829
            'http://www.example.com', 'foo'),
 
830
            config.POLICY_APPENDPATH)
 
831
 
 
832
    def test_set_user_option_change_policy(self):
 
833
        self.get_branch_config('http://www.example.com')
 
834
        self.my_config.set_user_option('norecurse_option', 'normal',
 
835
                                       store=config.STORE_LOCATION)
 
836
        self.assertEqual(
 
837
            self.my_location_config._get_option_policy(
 
838
            'http://www.example.com', 'norecurse_option'),
 
839
            config.POLICY_NONE)
 
840
 
 
841
    def test_set_user_option_recurse_false_section(self):
 
842
        # The following section has recurse=False set.  The test is to
 
843
        # make sure that a normal option can be added to the section,
 
844
        # converting recurse=False to the norecurse policy.
 
845
        self.get_branch_config('http://www.example.com/norecurse')
 
846
        self.callDeprecated(['The recurse option is deprecated as of 0.14.  '
 
847
                             'The section "http://www.example.com/norecurse" '
 
848
                             'has been converted to use policies.'],
 
849
                            self.my_config.set_user_option,
 
850
                            'foo', 'bar', store=config.STORE_LOCATION)
 
851
        self.assertEqual(
 
852
            self.my_location_config._get_option_policy(
 
853
            'http://www.example.com/norecurse', 'foo'),
 
854
            config.POLICY_NONE)
 
855
        # The previously existing option is still norecurse:
 
856
        self.assertEqual(
 
857
            self.my_location_config._get_option_policy(
 
858
            'http://www.example.com/norecurse', 'normal_option'),
 
859
            config.POLICY_NORECURSE)
 
860
 
548
861
    def test_post_commit_default(self):
549
 
        self.get_location_config('/a/c')
 
862
        self.get_branch_config('/a/c')
550
863
        self.assertEqual('bzrlib.tests.test_config.post_commit',
551
864
                         self.my_config.post_commit())
552
865
 
553
 
    def get_location_config(self, location, global_config=None):
 
866
    def get_branch_config(self, location, global_config=None):
554
867
        if global_config is None:
555
868
            global_file = StringIO(sample_config_text.encode('utf-8'))
556
869
        else:
557
870
            global_file = StringIO(global_config.encode('utf-8'))
558
871
        branches_file = StringIO(sample_branches_text.encode('utf-8'))
559
 
        self.my_config = config.LocationConfig(location)
560
 
        self.my_config._get_parser(branches_file)
 
872
        self.my_config = config.BranchConfig(FakeBranch(location))
 
873
        # Force location config to use specified file
 
874
        self.my_location_config = self.my_config._get_location_config()
 
875
        self.my_location_config._get_parser(branches_file)
 
876
        # Force global config to use specified file
561
877
        self.my_config._get_global_config()._get_parser(global_file)
562
878
 
563
879
    def test_set_user_setting_sets_and_saves(self):
564
 
        self.get_location_config('/a/c')
 
880
        self.get_branch_config('/a/c')
565
881
        record = InstrumentedConfigObj("foo")
566
 
        self.my_config._parser = record
 
882
        self.my_location_config._parser = record
567
883
 
568
884
        real_mkdir = os.mkdir
569
885
        self.created = False
574
890
 
575
891
        os.mkdir = checked_mkdir
576
892
        try:
577
 
            self.my_config.set_user_option('foo', 'bar')
 
893
            self.callDeprecated(['The recurse option is deprecated as of '
 
894
                                 '0.14.  The section "/a/c" has been '
 
895
                                 'converted to use policies.'],
 
896
                                self.my_config.set_user_option,
 
897
                                'foo', 'bar', store=config.STORE_LOCATION)
578
898
        finally:
579
899
            os.mkdir = real_mkdir
580
900
 
584
904
                          ('__setitem__', '/a/c', {}),
585
905
                          ('__getitem__', '/a/c'),
586
906
                          ('__setitem__', 'foo', 'bar'),
 
907
                          ('__getitem__', '/a/c'),
 
908
                          ('as_bool', 'recurse'),
 
909
                          ('__getitem__', '/a/c'),
 
910
                          ('__delitem__', 'recurse'),
 
911
                          ('__getitem__', '/a/c'),
 
912
                          ('keys',),
 
913
                          ('__getitem__', '/a/c'),
 
914
                          ('__contains__', 'foo:policy'),
587
915
                          ('write',)],
588
916
                         record._calls[1:])
589
917
 
590
 
 
591
 
class TestBranchConfigItems(TestCase):
 
918
    def test_set_user_setting_sets_and_saves2(self):
 
919
        self.get_branch_config('/a/c')
 
920
        self.assertIs(self.my_config.get_user_option('foo'), None)
 
921
        self.my_config.set_user_option('foo', 'bar')
 
922
        self.assertEqual(
 
923
            self.my_config.branch.control_files.files['branch.conf'],
 
924
            'foo = bar\n')
 
925
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
 
926
        self.my_config.set_user_option('foo', 'baz',
 
927
                                       store=config.STORE_LOCATION)
 
928
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
 
929
        self.my_config.set_user_option('foo', 'qux')
 
930
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
 
931
 
 
932
    def test_get_bzr_remote_path(self):
 
933
        my_config = config.LocationConfig('/a/c')
 
934
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
 
935
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
 
936
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
 
937
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
938
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
 
939
 
 
940
 
 
941
precedence_global = 'option = global'
 
942
precedence_branch = 'option = branch'
 
943
precedence_location = """
 
944
[http://]
 
945
recurse = true
 
946
option = recurse
 
947
[http://example.com/specific]
 
948
option = exact
 
949
"""
 
950
 
 
951
 
 
952
class TestBranchConfigItems(tests.TestCaseInTempDir):
 
953
 
 
954
    def get_branch_config(self, global_config=None, location=None,
 
955
                          location_config=None, branch_data_config=None):
 
956
        my_config = config.BranchConfig(FakeBranch(location))
 
957
        if global_config is not None:
 
958
            global_file = StringIO(global_config.encode('utf-8'))
 
959
            my_config._get_global_config()._get_parser(global_file)
 
960
        self.my_location_config = my_config._get_location_config()
 
961
        if location_config is not None:
 
962
            location_file = StringIO(location_config.encode('utf-8'))
 
963
            self.my_location_config._get_parser(location_file)
 
964
        if branch_data_config is not None:
 
965
            my_config.branch.control_files.files['branch.conf'] = \
 
966
                branch_data_config
 
967
        return my_config
592
968
 
593
969
    def test_user_id(self):
594
 
        branch = FakeBranch()
 
970
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
595
971
        my_config = config.BranchConfig(branch)
596
972
        self.assertEqual("Robert Collins <robertc@example.net>",
597
 
                         my_config._get_user_id())
598
 
        branch.control_files.email = "John"
599
 
        self.assertEqual("John", my_config._get_user_id())
 
973
                         my_config.username())
 
974
        my_config.branch.control_files.files['email'] = "John"
 
975
        my_config.set_user_option('email',
 
976
                                  "Robert Collins <robertc@example.org>")
 
977
        self.assertEqual("John", my_config.username())
 
978
        del my_config.branch.control_files.files['email']
 
979
        self.assertEqual("Robert Collins <robertc@example.org>",
 
980
                         my_config.username())
600
981
 
601
982
    def test_not_set_in_branch(self):
602
 
        branch = FakeBranch()
603
 
        my_config = config.BranchConfig(branch)
604
 
        branch.control_files.email = None
605
 
        config_file = StringIO(sample_config_text.encode('utf-8'))
606
 
        (my_config._get_location_config().
607
 
            _get_global_config()._get_parser(config_file))
 
983
        my_config = self.get_branch_config(sample_config_text)
608
984
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
609
985
                         my_config._get_user_id())
610
 
        branch.control_files.email = "John"
 
986
        my_config.branch.control_files.files['email'] = "John"
611
987
        self.assertEqual("John", my_config._get_user_id())
612
988
 
613
 
    def test_BZREMAIL_OVERRIDES(self):
614
 
        os.environ['BZREMAIL'] = "Robert Collins <robertc@example.org>"
 
989
    def test_BZR_EMAIL_OVERRIDES(self):
 
990
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
615
991
        branch = FakeBranch()
616
992
        my_config = config.BranchConfig(branch)
617
993
        self.assertEqual("Robert Collins <robertc@example.org>",
618
994
                         my_config.username())
619
 
    
 
995
 
620
996
    def test_signatures_forced(self):
621
 
        branch = FakeBranch()
622
 
        my_config = config.BranchConfig(branch)
623
 
        config_file = StringIO(sample_always_signatures)
624
 
        (my_config._get_location_config().
625
 
            _get_global_config()._get_parser(config_file))
 
997
        my_config = self.get_branch_config(
 
998
            global_config=sample_always_signatures)
 
999
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
1000
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
 
1001
        self.assertTrue(my_config.signature_needed())
 
1002
 
 
1003
    def test_signatures_forced_branch(self):
 
1004
        my_config = self.get_branch_config(
 
1005
            global_config=sample_ignore_signatures,
 
1006
            branch_data_config=sample_always_signatures)
626
1007
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
627
1008
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
628
1009
        self.assertTrue(my_config.signature_needed())
629
1010
 
630
1011
    def test_gpg_signing_command(self):
631
 
        branch = FakeBranch()
632
 
        my_config = config.BranchConfig(branch)
 
1012
        my_config = self.get_branch_config(
 
1013
            # branch data cannot set gpg_signing_command
 
1014
            branch_data_config="gpg_signing_command=pgp")
633
1015
        config_file = StringIO(sample_config_text.encode('utf-8'))
634
 
        (my_config._get_location_config().
635
 
            _get_global_config()._get_parser(config_file))
 
1016
        my_config._get_global_config()._get_parser(config_file)
636
1017
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
637
1018
 
638
1019
    def test_get_user_option_global(self):
639
1020
        branch = FakeBranch()
640
1021
        my_config = config.BranchConfig(branch)
641
1022
        config_file = StringIO(sample_config_text.encode('utf-8'))
642
 
        (my_config._get_location_config().
643
 
            _get_global_config()._get_parser(config_file))
 
1023
        (my_config._get_global_config()._get_parser(config_file))
644
1024
        self.assertEqual('something',
645
1025
                         my_config.get_user_option('user_global_option'))
646
1026
 
647
1027
    def test_post_commit_default(self):
648
1028
        branch = FakeBranch()
649
 
        branch.base='/a/c'
650
 
        my_config = config.BranchConfig(branch)
651
 
        config_file = StringIO(sample_config_text.encode('utf-8'))
652
 
        (my_config._get_location_config().
653
 
            _get_global_config()._get_parser(config_file))
654
 
        branch_file = StringIO(sample_branches_text)
655
 
        my_config._get_location_config()._get_parser(branch_file)
656
 
        self.assertEqual('bzrlib.tests.test_config.post_commit',
657
 
                         my_config.post_commit())
658
 
 
659
 
 
660
 
class TestMailAddressExtraction(TestCase):
 
1029
        my_config = self.get_branch_config(sample_config_text, '/a/c',
 
1030
                                           sample_branches_text)
 
1031
        self.assertEqual(my_config.branch.base, '/a/c')
 
1032
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
1033
                         my_config.post_commit())
 
1034
        my_config.set_user_option('post_commit', 'rmtree_root')
 
1035
        # post-commit is ignored when bresent in branch data
 
1036
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
1037
                         my_config.post_commit())
 
1038
        my_config.set_user_option('post_commit', 'rmtree_root',
 
1039
                                  store=config.STORE_LOCATION)
 
1040
        self.assertEqual('rmtree_root', my_config.post_commit())
 
1041
 
 
1042
    def test_config_precedence(self):
 
1043
        my_config = self.get_branch_config(global_config=precedence_global)
 
1044
        self.assertEqual(my_config.get_user_option('option'), 'global')
 
1045
        my_config = self.get_branch_config(global_config=precedence_global,
 
1046
                                      branch_data_config=precedence_branch)
 
1047
        self.assertEqual(my_config.get_user_option('option'), 'branch')
 
1048
        my_config = self.get_branch_config(global_config=precedence_global,
 
1049
                                      branch_data_config=precedence_branch,
 
1050
                                      location_config=precedence_location)
 
1051
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
 
1052
        my_config = self.get_branch_config(global_config=precedence_global,
 
1053
                                      branch_data_config=precedence_branch,
 
1054
                                      location_config=precedence_location,
 
1055
                                      location='http://example.com/specific')
 
1056
        self.assertEqual(my_config.get_user_option('option'), 'exact')
 
1057
 
 
1058
    def test_get_mail_client(self):
 
1059
        config = self.get_branch_config()
 
1060
        client = config.get_mail_client()
 
1061
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1062
 
 
1063
        # Specific clients
 
1064
        config.set_user_option('mail_client', 'evolution')
 
1065
        client = config.get_mail_client()
 
1066
        self.assertIsInstance(client, mail_client.Evolution)
 
1067
 
 
1068
        config.set_user_option('mail_client', 'kmail')
 
1069
        client = config.get_mail_client()
 
1070
        self.assertIsInstance(client, mail_client.KMail)
 
1071
 
 
1072
        config.set_user_option('mail_client', 'mutt')
 
1073
        client = config.get_mail_client()
 
1074
        self.assertIsInstance(client, mail_client.Mutt)
 
1075
 
 
1076
        config.set_user_option('mail_client', 'thunderbird')
 
1077
        client = config.get_mail_client()
 
1078
        self.assertIsInstance(client, mail_client.Thunderbird)
 
1079
 
 
1080
        # Generic options
 
1081
        config.set_user_option('mail_client', 'default')
 
1082
        client = config.get_mail_client()
 
1083
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1084
 
 
1085
        config.set_user_option('mail_client', 'editor')
 
1086
        client = config.get_mail_client()
 
1087
        self.assertIsInstance(client, mail_client.Editor)
 
1088
 
 
1089
        config.set_user_option('mail_client', 'mapi')
 
1090
        client = config.get_mail_client()
 
1091
        self.assertIsInstance(client, mail_client.MAPIClient)
 
1092
 
 
1093
        config.set_user_option('mail_client', 'xdg-email')
 
1094
        client = config.get_mail_client()
 
1095
        self.assertIsInstance(client, mail_client.XDGEmail)
 
1096
 
 
1097
        config.set_user_option('mail_client', 'firebird')
 
1098
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
 
1099
 
 
1100
 
 
1101
class TestMailAddressExtraction(tests.TestCase):
661
1102
 
662
1103
    def test_extract_email_address(self):
663
1104
        self.assertEqual('jane@test.com',
664
1105
                         config.extract_email_address('Jane <jane@test.com>'))
665
 
        self.assertRaises(errors.BzrError,
 
1106
        self.assertRaises(errors.NoEmailInUsername,
666
1107
                          config.extract_email_address, 'Jane Tester')
 
1108
 
 
1109
    def test_parse_username(self):
 
1110
        self.assertEqual(('', 'jdoe@example.com'),
 
1111
                         config.parse_username('jdoe@example.com'))
 
1112
        self.assertEqual(('', 'jdoe@example.com'),
 
1113
                         config.parse_username('<jdoe@example.com>'))
 
1114
        self.assertEqual(('John Doe', 'jdoe@example.com'),
 
1115
                         config.parse_username('John Doe <jdoe@example.com>'))
 
1116
        self.assertEqual(('John Doe', ''),
 
1117
                         config.parse_username('John Doe'))
 
1118
        self.assertEqual(('John Doe', 'jdoe@example.com'),
 
1119
                         config.parse_username('John Doe jdoe@example.com'))
 
1120
 
 
1121
class TestTreeConfig(tests.TestCaseWithTransport):
 
1122
 
 
1123
    def test_get_value(self):
 
1124
        """Test that retreiving a value from a section is possible"""
 
1125
        branch = self.make_branch('.')
 
1126
        tree_config = config.TreeConfig(branch)
 
1127
        tree_config.set_option('value', 'key', 'SECTION')
 
1128
        tree_config.set_option('value2', 'key2')
 
1129
        tree_config.set_option('value3-top', 'key3')
 
1130
        tree_config.set_option('value3-section', 'key3', 'SECTION')
 
1131
        value = tree_config.get_option('key', 'SECTION')
 
1132
        self.assertEqual(value, 'value')
 
1133
        value = tree_config.get_option('key2')
 
1134
        self.assertEqual(value, 'value2')
 
1135
        self.assertEqual(tree_config.get_option('non-existant'), None)
 
1136
        value = tree_config.get_option('non-existant', 'SECTION')
 
1137
        self.assertEqual(value, None)
 
1138
        value = tree_config.get_option('non-existant', default='default')
 
1139
        self.assertEqual(value, 'default')
 
1140
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
 
1141
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
 
1142
        self.assertEqual(value, 'default')
 
1143
        value = tree_config.get_option('key3')
 
1144
        self.assertEqual(value, 'value3-top')
 
1145
        value = tree_config.get_option('key3', 'SECTION')
 
1146
        self.assertEqual(value, 'value3-section')
 
1147
 
 
1148
 
 
1149
class TestTransportConfig(tests.TestCaseWithTransport):
 
1150
 
 
1151
    def test_get_value(self):
 
1152
        """Test that retreiving a value from a section is possible"""
 
1153
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
 
1154
                                               'control.conf')
 
1155
        bzrdir_config.set_option('value', 'key', 'SECTION')
 
1156
        bzrdir_config.set_option('value2', 'key2')
 
1157
        bzrdir_config.set_option('value3-top', 'key3')
 
1158
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
 
1159
        value = bzrdir_config.get_option('key', 'SECTION')
 
1160
        self.assertEqual(value, 'value')
 
1161
        value = bzrdir_config.get_option('key2')
 
1162
        self.assertEqual(value, 'value2')
 
1163
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
 
1164
        value = bzrdir_config.get_option('non-existant', 'SECTION')
 
1165
        self.assertEqual(value, None)
 
1166
        value = bzrdir_config.get_option('non-existant', default='default')
 
1167
        self.assertEqual(value, 'default')
 
1168
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
 
1169
        value = bzrdir_config.get_option('key2', 'NOSECTION',
 
1170
                                         default='default')
 
1171
        self.assertEqual(value, 'default')
 
1172
        value = bzrdir_config.get_option('key3')
 
1173
        self.assertEqual(value, 'value3-top')
 
1174
        value = bzrdir_config.get_option('key3', 'SECTION')
 
1175
        self.assertEqual(value, 'value3-section')
 
1176
 
 
1177
 
 
1178
class TestAuthenticationConfigFile(tests.TestCase):
 
1179
    """Test the authentication.conf file matching"""
 
1180
 
 
1181
    def _got_user_passwd(self, expected_user, expected_password,
 
1182
                         config, *args, **kwargs):
 
1183
        credentials = config.get_credentials(*args, **kwargs)
 
1184
        if credentials is None:
 
1185
            user = None
 
1186
            password = None
 
1187
        else:
 
1188
            user = credentials['user']
 
1189
            password = credentials['password']
 
1190
        self.assertEquals(expected_user, user)
 
1191
        self.assertEquals(expected_password, password)
 
1192
 
 
1193
    def test_empty_config(self):
 
1194
        conf = config.AuthenticationConfig(_file=StringIO())
 
1195
        self.assertEquals({}, conf._get_config())
 
1196
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
 
1197
 
 
1198
    def test_broken_config(self):
 
1199
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
 
1200
        self.assertRaises(errors.ParseConfigError, conf._get_config)
 
1201
 
 
1202
        conf = config.AuthenticationConfig(_file=StringIO(
 
1203
                """[broken]
 
1204
scheme=ftp
 
1205
user=joe
 
1206
verify_certificates=askme # Error: Not a boolean
 
1207
"""))
 
1208
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1209
        conf = config.AuthenticationConfig(_file=StringIO(
 
1210
                """[broken]
 
1211
scheme=ftp
 
1212
user=joe
 
1213
port=port # Error: Not an int
 
1214
"""))
 
1215
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1216
 
 
1217
    def test_credentials_for_scheme_host(self):
 
1218
        conf = config.AuthenticationConfig(_file=StringIO(
 
1219
                """# Identity on foo.net
 
1220
[ftp definition]
 
1221
scheme=ftp
 
1222
host=foo.net
 
1223
user=joe
 
1224
password=secret-pass
 
1225
"""))
 
1226
        # Basic matching
 
1227
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
 
1228
        # different scheme
 
1229
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
 
1230
        # different host
 
1231
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
 
1232
 
 
1233
    def test_credentials_for_host_port(self):
 
1234
        conf = config.AuthenticationConfig(_file=StringIO(
 
1235
                """# Identity on foo.net
 
1236
[ftp definition]
 
1237
scheme=ftp
 
1238
port=10021
 
1239
host=foo.net
 
1240
user=joe
 
1241
password=secret-pass
 
1242
"""))
 
1243
        # No port
 
1244
        self._got_user_passwd('joe', 'secret-pass',
 
1245
                              conf, 'ftp', 'foo.net', port=10021)
 
1246
        # different port
 
1247
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
 
1248
 
 
1249
    def test_for_matching_host(self):
 
1250
        conf = config.AuthenticationConfig(_file=StringIO(
 
1251
                """# Identity on foo.net
 
1252
[sourceforge]
 
1253
scheme=bzr
 
1254
host=bzr.sf.net
 
1255
user=joe
 
1256
password=joepass
 
1257
[sourceforge domain]
 
1258
scheme=bzr
 
1259
host=.bzr.sf.net
 
1260
user=georges
 
1261
password=bendover
 
1262
"""))
 
1263
        # matching domain
 
1264
        self._got_user_passwd('georges', 'bendover',
 
1265
                              conf, 'bzr', 'foo.bzr.sf.net')
 
1266
        # phishing attempt
 
1267
        self._got_user_passwd(None, None,
 
1268
                              conf, 'bzr', 'bbzr.sf.net')
 
1269
 
 
1270
    def test_for_matching_host_None(self):
 
1271
        conf = config.AuthenticationConfig(_file=StringIO(
 
1272
                """# Identity on foo.net
 
1273
[catchup bzr]
 
1274
scheme=bzr
 
1275
user=joe
 
1276
password=joepass
 
1277
[DEFAULT]
 
1278
user=georges
 
1279
password=bendover
 
1280
"""))
 
1281
        # match no host
 
1282
        self._got_user_passwd('joe', 'joepass',
 
1283
                              conf, 'bzr', 'quux.net')
 
1284
        # no host but different scheme
 
1285
        self._got_user_passwd('georges', 'bendover',
 
1286
                              conf, 'ftp', 'quux.net')
 
1287
 
 
1288
    def test_credentials_for_path(self):
 
1289
        conf = config.AuthenticationConfig(_file=StringIO(
 
1290
                """
 
1291
[http dir1]
 
1292
scheme=http
 
1293
host=bar.org
 
1294
path=/dir1
 
1295
user=jim
 
1296
password=jimpass
 
1297
[http dir2]
 
1298
scheme=http
 
1299
host=bar.org
 
1300
path=/dir2
 
1301
user=georges
 
1302
password=bendover
 
1303
"""))
 
1304
        # no path no dice
 
1305
        self._got_user_passwd(None, None,
 
1306
                              conf, 'http', host='bar.org', path='/dir3')
 
1307
        # matching path
 
1308
        self._got_user_passwd('georges', 'bendover',
 
1309
                              conf, 'http', host='bar.org', path='/dir2')
 
1310
        # matching subdir
 
1311
        self._got_user_passwd('jim', 'jimpass',
 
1312
                              conf, 'http', host='bar.org',path='/dir1/subdir')
 
1313
 
 
1314
    def test_credentials_for_user(self):
 
1315
        conf = config.AuthenticationConfig(_file=StringIO(
 
1316
                """
 
1317
[with user]
 
1318
scheme=http
 
1319
host=bar.org
 
1320
user=jim
 
1321
password=jimpass
 
1322
"""))
 
1323
        # Get user
 
1324
        self._got_user_passwd('jim', 'jimpass',
 
1325
                              conf, 'http', 'bar.org')
 
1326
        # Get same user
 
1327
        self._got_user_passwd('jim', 'jimpass',
 
1328
                              conf, 'http', 'bar.org', user='jim')
 
1329
        # Don't get a different user if one is specified
 
1330
        self._got_user_passwd(None, None,
 
1331
                              conf, 'http', 'bar.org', user='georges')
 
1332
 
 
1333
    def test_verify_certificates(self):
 
1334
        conf = config.AuthenticationConfig(_file=StringIO(
 
1335
                """
 
1336
[self-signed]
 
1337
scheme=https
 
1338
host=bar.org
 
1339
user=jim
 
1340
password=jimpass
 
1341
verify_certificates=False
 
1342
[normal]
 
1343
scheme=https
 
1344
host=foo.net
 
1345
user=georges
 
1346
password=bendover
 
1347
"""))
 
1348
        credentials = conf.get_credentials('https', 'bar.org')
 
1349
        self.assertEquals(False, credentials.get('verify_certificates'))
 
1350
        credentials = conf.get_credentials('https', 'foo.net')
 
1351
        self.assertEquals(True, credentials.get('verify_certificates'))
 
1352
 
 
1353
 
 
1354
class TestAuthenticationConfig(tests.TestCase):
 
1355
    """Test AuthenticationConfig behaviour"""
 
1356
 
 
1357
    def _check_default_prompt(self, expected_prompt_format, scheme,
 
1358
                              host=None, port=None, realm=None, path=None):
 
1359
        if host is None:
 
1360
            host = 'bar.org'
 
1361
        user, password = 'jim', 'precious'
 
1362
        expected_prompt = expected_prompt_format % {
 
1363
            'scheme': scheme, 'host': host, 'port': port,
 
1364
            'user': user, 'realm': realm}
 
1365
 
 
1366
        stdout = tests.StringIOWrapper()
 
1367
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
 
1368
                                            stdout=stdout)
 
1369
        # We use an empty conf so that the user is always prompted
 
1370
        conf = config.AuthenticationConfig()
 
1371
        self.assertEquals(password,
 
1372
                          conf.get_password(scheme, host, user, port=port,
 
1373
                                            realm=realm, path=path))
 
1374
        self.assertEquals(stdout.getvalue(), expected_prompt)
 
1375
 
 
1376
    def test_default_prompts(self):
 
1377
        # HTTP prompts can't be tested here, see test_http.py
 
1378
        self._check_default_prompt('FTP %(user)s@%(host)s password: ', 'ftp')
 
1379
        self._check_default_prompt('FTP %(user)s@%(host)s:%(port)d password: ',
 
1380
                                   'ftp', port=10020)
 
1381
 
 
1382
        self._check_default_prompt('SSH %(user)s@%(host)s:%(port)d password: ',
 
1383
                                   'ssh', port=12345)
 
1384
        # SMTP port handling is a bit special (it's handled if embedded in the
 
1385
        # host too)
 
1386
        # FIXME: should we: forbid that, extend it to other schemes, leave
 
1387
        # things as they are that's fine thank you ?
 
1388
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
 
1389
                                   'smtp')
 
1390
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
 
1391
                                   'smtp', host='bar.org:10025')
 
1392
        self._check_default_prompt(
 
1393
            'SMTP %(user)s@%(host)s:%(port)d password: ',
 
1394
            'smtp', port=10025)
 
1395
 
 
1396
 
 
1397
# FIXME: Once we have a way to declare authentication to all test servers, we
 
1398
# can implement generic tests.
 
1399
# test_user_password_in_url
 
1400
# test_user_in_url_password_from_config
 
1401
# test_user_in_url_password_prompted
 
1402
# test_user_in_config
 
1403
# test_user_getpass.getuser
 
1404
# test_user_prompted ?
 
1405
class TestAuthenticationRing(tests.TestCaseWithTransport):
 
1406
    pass