~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: 2007-11-13 20:37:09 UTC
  • mto: This revision was merged to the branch mainline in revision 3001.
  • Revision ID: john@arbash-meinel.com-20071113203709-kysdte0emqv84pnj
Fix bug #162486, by having RemoteBranch properly initialize self._revision_id_to_revno_map.

Show diffs side-by-side

added added

removed removed

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