~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Martin Pool
  • Date: 2009-07-19 01:05:42 UTC
  • mto: This revision was merged to the branch mainline in revision 4558.
  • Revision ID: mbp@sourcefrog.net-20090719010542-34bzx1i5ynfvs6zd
TextUIFactory should cope with EOF when in get_boolean

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2008, 2009 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Tests for finding and reading the bzr config file[s]."""
 
18
# import system imports here
 
19
from cStringIO import StringIO
 
20
import os
 
21
import sys
 
22
 
 
23
#import bzrlib specific imports here
 
24
from bzrlib import (
 
25
    branch,
 
26
    bzrdir,
 
27
    config,
 
28
    errors,
 
29
    osutils,
 
30
    mail_client,
 
31
    ui,
 
32
    urlutils,
 
33
    tests,
 
34
    trace,
 
35
    transport,
 
36
    )
 
37
from bzrlib.util.configobj import configobj
 
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
"""
 
104
 
 
105
 
 
106
class InstrumentedConfigObj(object):
 
107
    """A config obj look-enough-alike to record calls made to it."""
 
108
 
 
109
    def __contains__(self, thing):
 
110
        self._calls.append(('__contains__', thing))
 
111
        return False
 
112
 
 
113
    def __getitem__(self, key):
 
114
        self._calls.append(('__getitem__', key))
 
115
        return self
 
116
 
 
117
    def __init__(self, input, encoding=None):
 
118
        self._calls = [('__init__', input, encoding)]
 
119
 
 
120
    def __setitem__(self, key, value):
 
121
        self._calls.append(('__setitem__', key, value))
 
122
 
 
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):
 
131
        self._calls.append(('write',))
 
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
 
 
141
 
 
142
class FakeBranch(object):
 
143
 
 
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._transport = self.control_files = \
 
150
            FakeControlFilesAndTransport(user_id=user_id)
 
151
 
 
152
    def _get_config(self):
 
153
        return config.TransportConfig(self._transport, 'branch.conf')
 
154
 
 
155
    def lock_write(self):
 
156
        pass
 
157
 
 
158
    def unlock(self):
 
159
        pass
 
160
 
 
161
 
 
162
class FakeControlFilesAndTransport(object):
 
163
 
 
164
    def __init__(self, user_id=None):
 
165
        self.files = {}
 
166
        if user_id:
 
167
            self.files['email'] = user_id
 
168
        self._transport = self
 
169
 
 
170
    def get_utf8(self, filename):
 
171
        # from LockableFiles
 
172
        raise AssertionError("get_utf8 should no longer be used")
 
173
 
 
174
    def get(self, filename):
 
175
        # from Transport
 
176
        try:
 
177
            return StringIO(self.files[filename])
 
178
        except KeyError:
 
179
            raise errors.NoSuchFile(filename)
 
180
 
 
181
    def get_bytes(self, filename):
 
182
        # from Transport
 
183
        try:
 
184
            return self.files[filename]
 
185
        except KeyError:
 
186
            raise errors.NoSuchFile(filename)
 
187
 
 
188
    def put(self, filename, fileobj):
 
189
        self.files[filename] = fileobj.read()
 
190
 
 
191
    def put_file(self, filename, fileobj):
 
192
        return self.put(filename, fileobj)
 
193
 
 
194
 
 
195
class InstrumentedConfig(config.Config):
 
196
    """An instrumented config that supplies stubs for template methods."""
 
197
 
 
198
    def __init__(self):
 
199
        super(InstrumentedConfig, self).__init__()
 
200
        self._calls = []
 
201
        self._signatures = config.CHECK_NEVER
 
202
 
 
203
    def _get_user_id(self):
 
204
        self._calls.append('_get_user_id')
 
205
        return "Robert Collins <robert.collins@example.org>"
 
206
 
 
207
    def _get_signature_checking(self):
 
208
        self._calls.append('_get_signature_checking')
 
209
        return self._signatures
 
210
 
 
211
 
 
212
bool_config = """[DEFAULT]
 
213
active = true
 
214
inactive = false
 
215
[UPPERCASE]
 
216
active = True
 
217
nonactive = False
 
218
"""
 
219
 
 
220
 
 
221
class TestConfigObj(tests.TestCase):
 
222
 
 
223
    def test_get_bool(self):
 
224
        co = config.ConfigObj(StringIO(bool_config))
 
225
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
 
226
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
 
227
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
 
228
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
 
229
 
 
230
    def test_hash_sign_in_value(self):
 
231
        """
 
232
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
 
233
        treated as comments when read in again. (#86838)
 
234
        """
 
235
        co = config.ConfigObj()
 
236
        co['test'] = 'foo#bar'
 
237
        lines = co.write()
 
238
        self.assertEqual(lines, ['test = "foo#bar"'])
 
239
        co2 = config.ConfigObj(lines)
 
240
        self.assertEqual(co2['test'], 'foo#bar')
 
241
 
 
242
 
 
243
erroneous_config = """[section] # line 1
 
244
good=good # line 2
 
245
[section] # line 3
 
246
whocares=notme # line 4
 
247
"""
 
248
 
 
249
 
 
250
class TestConfigObjErrors(tests.TestCase):
 
251
 
 
252
    def test_duplicate_section_name_error_line(self):
 
253
        try:
 
254
            co = configobj.ConfigObj(StringIO(erroneous_config),
 
255
                                     raise_errors=True)
 
256
        except config.configobj.DuplicateError, e:
 
257
            self.assertEqual(3, e.line_number)
 
258
        else:
 
259
            self.fail('Error in config file not detected')
 
260
 
 
261
 
 
262
class TestConfig(tests.TestCase):
 
263
 
 
264
    def test_constructs(self):
 
265
        config.Config()
 
266
 
 
267
    def test_no_default_editor(self):
 
268
        self.assertRaises(NotImplementedError, config.Config().get_editor)
 
269
 
 
270
    def test_user_email(self):
 
271
        my_config = InstrumentedConfig()
 
272
        self.assertEqual('robert.collins@example.org', my_config.user_email())
 
273
        self.assertEqual(['_get_user_id'], my_config._calls)
 
274
 
 
275
    def test_username(self):
 
276
        my_config = InstrumentedConfig()
 
277
        self.assertEqual('Robert Collins <robert.collins@example.org>',
 
278
                         my_config.username())
 
279
        self.assertEqual(['_get_user_id'], my_config._calls)
 
280
 
 
281
    def test_signatures_default(self):
 
282
        my_config = config.Config()
 
283
        self.assertFalse(my_config.signature_needed())
 
284
        self.assertEqual(config.CHECK_IF_POSSIBLE,
 
285
                         my_config.signature_checking())
 
286
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
 
287
                         my_config.signing_policy())
 
288
 
 
289
    def test_signatures_template_method(self):
 
290
        my_config = InstrumentedConfig()
 
291
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
292
        self.assertEqual(['_get_signature_checking'], my_config._calls)
 
293
 
 
294
    def test_signatures_template_method_none(self):
 
295
        my_config = InstrumentedConfig()
 
296
        my_config._signatures = None
 
297
        self.assertEqual(config.CHECK_IF_POSSIBLE,
 
298
                         my_config.signature_checking())
 
299
        self.assertEqual(['_get_signature_checking'], my_config._calls)
 
300
 
 
301
    def test_gpg_signing_command_default(self):
 
302
        my_config = config.Config()
 
303
        self.assertEqual('gpg', my_config.gpg_signing_command())
 
304
 
 
305
    def test_get_user_option_default(self):
 
306
        my_config = config.Config()
 
307
        self.assertEqual(None, my_config.get_user_option('no_option'))
 
308
 
 
309
    def test_post_commit_default(self):
 
310
        my_config = config.Config()
 
311
        self.assertEqual(None, my_config.post_commit())
 
312
 
 
313
    def test_log_format_default(self):
 
314
        my_config = config.Config()
 
315
        self.assertEqual('long', my_config.log_format())
 
316
 
 
317
 
 
318
class TestConfigPath(tests.TestCase):
 
319
 
 
320
    def setUp(self):
 
321
        super(TestConfigPath, self).setUp()
 
322
        os.environ['HOME'] = '/home/bogus'
 
323
        if sys.platform == 'win32':
 
324
            os.environ['BZR_HOME'] = \
 
325
                r'C:\Documents and Settings\bogus\Application Data'
 
326
            self.bzr_home = \
 
327
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
 
328
        else:
 
329
            self.bzr_home = '/home/bogus/.bazaar'
 
330
 
 
331
    def test_config_dir(self):
 
332
        self.assertEqual(config.config_dir(), self.bzr_home)
 
333
 
 
334
    def test_config_filename(self):
 
335
        self.assertEqual(config.config_filename(),
 
336
                         self.bzr_home + '/bazaar.conf')
 
337
 
 
338
    def test_branches_config_filename(self):
 
339
        self.assertEqual(config.branches_config_filename(),
 
340
                         self.bzr_home + '/branches.conf')
 
341
 
 
342
    def test_locations_config_filename(self):
 
343
        self.assertEqual(config.locations_config_filename(),
 
344
                         self.bzr_home + '/locations.conf')
 
345
 
 
346
    def test_authentication_config_filename(self):
 
347
        self.assertEqual(config.authentication_config_filename(),
 
348
                         self.bzr_home + '/authentication.conf')
 
349
 
 
350
 
 
351
class TestIniConfig(tests.TestCase):
 
352
 
 
353
    def test_contructs(self):
 
354
        my_config = config.IniBasedConfig("nothing")
 
355
 
 
356
    def test_from_fp(self):
 
357
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
358
        my_config = config.IniBasedConfig(None)
 
359
        self.failUnless(
 
360
            isinstance(my_config._get_parser(file=config_file),
 
361
                        configobj.ConfigObj))
 
362
 
 
363
    def test_cached(self):
 
364
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
365
        my_config = config.IniBasedConfig(None)
 
366
        parser = my_config._get_parser(file=config_file)
 
367
        self.failUnless(my_config._get_parser() is parser)
 
368
 
 
369
 
 
370
class TestGetConfig(tests.TestCase):
 
371
 
 
372
    def test_constructs(self):
 
373
        my_config = config.GlobalConfig()
 
374
 
 
375
    def test_calls_read_filenames(self):
 
376
        # replace the class that is constructed, to check its parameters
 
377
        oldparserclass = config.ConfigObj
 
378
        config.ConfigObj = InstrumentedConfigObj
 
379
        my_config = config.GlobalConfig()
 
380
        try:
 
381
            parser = my_config._get_parser()
 
382
        finally:
 
383
            config.ConfigObj = oldparserclass
 
384
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
385
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
 
386
                                          'utf-8')])
 
387
 
 
388
 
 
389
class TestBranchConfig(tests.TestCaseWithTransport):
 
390
 
 
391
    def test_constructs(self):
 
392
        branch = FakeBranch()
 
393
        my_config = config.BranchConfig(branch)
 
394
        self.assertRaises(TypeError, config.BranchConfig)
 
395
 
 
396
    def test_get_location_config(self):
 
397
        branch = FakeBranch()
 
398
        my_config = config.BranchConfig(branch)
 
399
        location_config = my_config._get_location_config()
 
400
        self.assertEqual(branch.base, location_config.location)
 
401
        self.failUnless(location_config is my_config._get_location_config())
 
402
 
 
403
    def test_get_config(self):
 
404
        """The Branch.get_config method works properly"""
 
405
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
 
406
        my_config = b.get_config()
 
407
        self.assertIs(my_config.get_user_option('wacky'), None)
 
408
        my_config.set_user_option('wacky', 'unlikely')
 
409
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
 
410
 
 
411
        # Ensure we get the same thing if we start again
 
412
        b2 = branch.Branch.open('.')
 
413
        my_config2 = b2.get_config()
 
414
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
 
415
 
 
416
    def test_has_explicit_nickname(self):
 
417
        b = self.make_branch('.')
 
418
        self.assertFalse(b.get_config().has_explicit_nickname())
 
419
        b.nick = 'foo'
 
420
        self.assertTrue(b.get_config().has_explicit_nickname())
 
421
 
 
422
    def test_config_url(self):
 
423
        """The Branch.get_config will use section that uses a local url"""
 
424
        branch = self.make_branch('branch')
 
425
        self.assertEqual('branch', branch.nick)
 
426
 
 
427
        locations = config.locations_config_filename()
 
428
        config.ensure_config_dir_exists()
 
429
        local_url = urlutils.local_path_to_url('branch')
 
430
        open(locations, 'wb').write('[%s]\nnickname = foobar'
 
431
                                    % (local_url,))
 
432
        self.assertEqual('foobar', branch.nick)
 
433
 
 
434
    def test_config_local_path(self):
 
435
        """The Branch.get_config will use a local system path"""
 
436
        branch = self.make_branch('branch')
 
437
        self.assertEqual('branch', branch.nick)
 
438
 
 
439
        locations = config.locations_config_filename()
 
440
        config.ensure_config_dir_exists()
 
441
        open(locations, 'wb').write('[%s/branch]\nnickname = barry'
 
442
                                    % (osutils.getcwd().encode('utf8'),))
 
443
        self.assertEqual('barry', branch.nick)
 
444
 
 
445
    def test_config_creates_local(self):
 
446
        """Creating a new entry in config uses a local path."""
 
447
        branch = self.make_branch('branch', format='knit')
 
448
        branch.set_push_location('http://foobar')
 
449
        locations = config.locations_config_filename()
 
450
        local_path = osutils.getcwd().encode('utf8')
 
451
        # Surprisingly ConfigObj doesn't create a trailing newline
 
452
        self.check_file_contents(locations,
 
453
                                 '[%s/branch]\n'
 
454
                                 'push_location = http://foobar\n'
 
455
                                 'push_location:policy = norecurse\n'
 
456
                                 % (local_path,))
 
457
 
 
458
    def test_autonick_urlencoded(self):
 
459
        b = self.make_branch('!repo')
 
460
        self.assertEqual('!repo', b.get_config().get_nickname())
 
461
 
 
462
    def test_warn_if_masked(self):
 
463
        _warning = trace.warning
 
464
        warnings = []
 
465
        def warning(*args):
 
466
            warnings.append(args[0] % args[1:])
 
467
 
 
468
        def set_option(store, warn_masked=True):
 
469
            warnings[:] = []
 
470
            conf.set_user_option('example_option', repr(store), store=store,
 
471
                                 warn_masked=warn_masked)
 
472
        def assertWarning(warning):
 
473
            if warning is None:
 
474
                self.assertEqual(0, len(warnings))
 
475
            else:
 
476
                self.assertEqual(1, len(warnings))
 
477
                self.assertEqual(warning, warnings[0])
 
478
        trace.warning = warning
 
479
        try:
 
480
            branch = self.make_branch('.')
 
481
            conf = branch.get_config()
 
482
            set_option(config.STORE_GLOBAL)
 
483
            assertWarning(None)
 
484
            set_option(config.STORE_BRANCH)
 
485
            assertWarning(None)
 
486
            set_option(config.STORE_GLOBAL)
 
487
            assertWarning('Value "4" is masked by "3" from branch.conf')
 
488
            set_option(config.STORE_GLOBAL, warn_masked=False)
 
489
            assertWarning(None)
 
490
            set_option(config.STORE_LOCATION)
 
491
            assertWarning(None)
 
492
            set_option(config.STORE_BRANCH)
 
493
            assertWarning('Value "3" is masked by "0" from locations.conf')
 
494
            set_option(config.STORE_BRANCH, warn_masked=False)
 
495
            assertWarning(None)
 
496
        finally:
 
497
            trace.warning = _warning
 
498
 
 
499
 
 
500
class TestGlobalConfigItems(tests.TestCase):
 
501
 
 
502
    def test_user_id(self):
 
503
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
504
        my_config = config.GlobalConfig()
 
505
        my_config._parser = my_config._get_parser(file=config_file)
 
506
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
 
507
                         my_config._get_user_id())
 
508
 
 
509
    def test_absent_user_id(self):
 
510
        config_file = StringIO("")
 
511
        my_config = config.GlobalConfig()
 
512
        my_config._parser = my_config._get_parser(file=config_file)
 
513
        self.assertEqual(None, my_config._get_user_id())
 
514
 
 
515
    def test_configured_editor(self):
 
516
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
517
        my_config = config.GlobalConfig()
 
518
        my_config._parser = my_config._get_parser(file=config_file)
 
519
        self.assertEqual("vim", my_config.get_editor())
 
520
 
 
521
    def test_signatures_always(self):
 
522
        config_file = StringIO(sample_always_signatures)
 
523
        my_config = config.GlobalConfig()
 
524
        my_config._parser = my_config._get_parser(file=config_file)
 
525
        self.assertEqual(config.CHECK_NEVER,
 
526
                         my_config.signature_checking())
 
527
        self.assertEqual(config.SIGN_ALWAYS,
 
528
                         my_config.signing_policy())
 
529
        self.assertEqual(True, my_config.signature_needed())
 
530
 
 
531
    def test_signatures_if_possible(self):
 
532
        config_file = StringIO(sample_maybe_signatures)
 
533
        my_config = config.GlobalConfig()
 
534
        my_config._parser = my_config._get_parser(file=config_file)
 
535
        self.assertEqual(config.CHECK_NEVER,
 
536
                         my_config.signature_checking())
 
537
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
 
538
                         my_config.signing_policy())
 
539
        self.assertEqual(False, my_config.signature_needed())
 
540
 
 
541
    def test_signatures_ignore(self):
 
542
        config_file = StringIO(sample_ignore_signatures)
 
543
        my_config = config.GlobalConfig()
 
544
        my_config._parser = my_config._get_parser(file=config_file)
 
545
        self.assertEqual(config.CHECK_ALWAYS,
 
546
                         my_config.signature_checking())
 
547
        self.assertEqual(config.SIGN_NEVER,
 
548
                         my_config.signing_policy())
 
549
        self.assertEqual(False, my_config.signature_needed())
 
550
 
 
551
    def _get_sample_config(self):
 
552
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
553
        my_config = config.GlobalConfig()
 
554
        my_config._parser = my_config._get_parser(file=config_file)
 
555
        return my_config
 
556
 
 
557
    def test_gpg_signing_command(self):
 
558
        my_config = self._get_sample_config()
 
559
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
 
560
        self.assertEqual(False, my_config.signature_needed())
 
561
 
 
562
    def _get_empty_config(self):
 
563
        config_file = StringIO("")
 
564
        my_config = config.GlobalConfig()
 
565
        my_config._parser = my_config._get_parser(file=config_file)
 
566
        return my_config
 
567
 
 
568
    def test_gpg_signing_command_unset(self):
 
569
        my_config = self._get_empty_config()
 
570
        self.assertEqual("gpg", my_config.gpg_signing_command())
 
571
 
 
572
    def test_get_user_option_default(self):
 
573
        my_config = self._get_empty_config()
 
574
        self.assertEqual(None, my_config.get_user_option('no_option'))
 
575
 
 
576
    def test_get_user_option_global(self):
 
577
        my_config = self._get_sample_config()
 
578
        self.assertEqual("something",
 
579
                         my_config.get_user_option('user_global_option'))
 
580
 
 
581
    def test_post_commit_default(self):
 
582
        my_config = self._get_sample_config()
 
583
        self.assertEqual(None, my_config.post_commit())
 
584
 
 
585
    def test_configured_logformat(self):
 
586
        my_config = self._get_sample_config()
 
587
        self.assertEqual("short", my_config.log_format())
 
588
 
 
589
    def test_get_alias(self):
 
590
        my_config = self._get_sample_config()
 
591
        self.assertEqual('help', my_config.get_alias('h'))
 
592
 
 
593
    def test_get_aliases(self):
 
594
        my_config = self._get_sample_config()
 
595
        aliases = my_config.get_aliases()
 
596
        self.assertEqual(2, len(aliases))
 
597
        sorted_keys = sorted(aliases)
 
598
        self.assertEqual('help', aliases[sorted_keys[0]])
 
599
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
 
600
 
 
601
    def test_get_no_alias(self):
 
602
        my_config = self._get_sample_config()
 
603
        self.assertEqual(None, my_config.get_alias('foo'))
 
604
 
 
605
    def test_get_long_alias(self):
 
606
        my_config = self._get_sample_config()
 
607
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
 
608
 
 
609
 
 
610
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
 
611
 
 
612
    def test_empty(self):
 
613
        my_config = config.GlobalConfig()
 
614
        self.assertEqual(0, len(my_config.get_aliases()))
 
615
 
 
616
    def test_set_alias(self):
 
617
        my_config = config.GlobalConfig()
 
618
        alias_value = 'commit --strict'
 
619
        my_config.set_alias('commit', alias_value)
 
620
        new_config = config.GlobalConfig()
 
621
        self.assertEqual(alias_value, new_config.get_alias('commit'))
 
622
 
 
623
    def test_remove_alias(self):
 
624
        my_config = config.GlobalConfig()
 
625
        my_config.set_alias('commit', 'commit --strict')
 
626
        # Now remove the alias again.
 
627
        my_config.unset_alias('commit')
 
628
        new_config = config.GlobalConfig()
 
629
        self.assertIs(None, new_config.get_alias('commit'))
 
630
 
 
631
 
 
632
class TestLocationConfig(tests.TestCaseInTempDir):
 
633
 
 
634
    def test_constructs(self):
 
635
        my_config = config.LocationConfig('http://example.com')
 
636
        self.assertRaises(TypeError, config.LocationConfig)
 
637
 
 
638
    def test_branch_calls_read_filenames(self):
 
639
        # This is testing the correct file names are provided.
 
640
        # TODO: consolidate with the test for GlobalConfigs filename checks.
 
641
        #
 
642
        # replace the class that is constructed, to check its parameters
 
643
        oldparserclass = config.ConfigObj
 
644
        config.ConfigObj = InstrumentedConfigObj
 
645
        try:
 
646
            my_config = config.LocationConfig('http://www.example.com')
 
647
            parser = my_config._get_parser()
 
648
        finally:
 
649
            config.ConfigObj = oldparserclass
 
650
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
651
        self.assertEqual(parser._calls,
 
652
                         [('__init__', config.locations_config_filename(),
 
653
                           'utf-8')])
 
654
        config.ensure_config_dir_exists()
 
655
        #os.mkdir(config.config_dir())
 
656
        f = file(config.branches_config_filename(), 'wb')
 
657
        f.write('')
 
658
        f.close()
 
659
        oldparserclass = config.ConfigObj
 
660
        config.ConfigObj = InstrumentedConfigObj
 
661
        try:
 
662
            my_config = config.LocationConfig('http://www.example.com')
 
663
            parser = my_config._get_parser()
 
664
        finally:
 
665
            config.ConfigObj = oldparserclass
 
666
 
 
667
    def test_get_global_config(self):
 
668
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
 
669
        global_config = my_config._get_global_config()
 
670
        self.failUnless(isinstance(global_config, config.GlobalConfig))
 
671
        self.failUnless(global_config is my_config._get_global_config())
 
672
 
 
673
    def test__get_matching_sections_no_match(self):
 
674
        self.get_branch_config('/')
 
675
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
676
 
 
677
    def test__get_matching_sections_exact(self):
 
678
        self.get_branch_config('http://www.example.com')
 
679
        self.assertEqual([('http://www.example.com', '')],
 
680
                         self.my_location_config._get_matching_sections())
 
681
 
 
682
    def test__get_matching_sections_suffix_does_not(self):
 
683
        self.get_branch_config('http://www.example.com-com')
 
684
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
685
 
 
686
    def test__get_matching_sections_subdir_recursive(self):
 
687
        self.get_branch_config('http://www.example.com/com')
 
688
        self.assertEqual([('http://www.example.com', 'com')],
 
689
                         self.my_location_config._get_matching_sections())
 
690
 
 
691
    def test__get_matching_sections_ignoreparent(self):
 
692
        self.get_branch_config('http://www.example.com/ignoreparent')
 
693
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
 
694
                         self.my_location_config._get_matching_sections())
 
695
 
 
696
    def test__get_matching_sections_ignoreparent_subdir(self):
 
697
        self.get_branch_config(
 
698
            'http://www.example.com/ignoreparent/childbranch')
 
699
        self.assertEqual([('http://www.example.com/ignoreparent',
 
700
                           'childbranch')],
 
701
                         self.my_location_config._get_matching_sections())
 
702
 
 
703
    def test__get_matching_sections_subdir_trailing_slash(self):
 
704
        self.get_branch_config('/b')
 
705
        self.assertEqual([('/b/', '')],
 
706
                         self.my_location_config._get_matching_sections())
 
707
 
 
708
    def test__get_matching_sections_subdir_child(self):
 
709
        self.get_branch_config('/a/foo')
 
710
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
 
711
                         self.my_location_config._get_matching_sections())
 
712
 
 
713
    def test__get_matching_sections_subdir_child_child(self):
 
714
        self.get_branch_config('/a/foo/bar')
 
715
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
 
716
                         self.my_location_config._get_matching_sections())
 
717
 
 
718
    def test__get_matching_sections_trailing_slash_with_children(self):
 
719
        self.get_branch_config('/a/')
 
720
        self.assertEqual([('/a/', '')],
 
721
                         self.my_location_config._get_matching_sections())
 
722
 
 
723
    def test__get_matching_sections_explicit_over_glob(self):
 
724
        # XXX: 2006-09-08 jamesh
 
725
        # This test only passes because ord('c') > ord('*').  If there
 
726
        # was a config section for '/a/?', it would get precedence
 
727
        # over '/a/c'.
 
728
        self.get_branch_config('/a/c')
 
729
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
 
730
                         self.my_location_config._get_matching_sections())
 
731
 
 
732
    def test__get_option_policy_normal(self):
 
733
        self.get_branch_config('http://www.example.com')
 
734
        self.assertEqual(
 
735
            self.my_location_config._get_config_policy(
 
736
            'http://www.example.com', 'normal_option'),
 
737
            config.POLICY_NONE)
 
738
 
 
739
    def test__get_option_policy_norecurse(self):
 
740
        self.get_branch_config('http://www.example.com')
 
741
        self.assertEqual(
 
742
            self.my_location_config._get_option_policy(
 
743
            'http://www.example.com', 'norecurse_option'),
 
744
            config.POLICY_NORECURSE)
 
745
        # Test old recurse=False setting:
 
746
        self.assertEqual(
 
747
            self.my_location_config._get_option_policy(
 
748
            'http://www.example.com/norecurse', 'normal_option'),
 
749
            config.POLICY_NORECURSE)
 
750
 
 
751
    def test__get_option_policy_normal(self):
 
752
        self.get_branch_config('http://www.example.com')
 
753
        self.assertEqual(
 
754
            self.my_location_config._get_option_policy(
 
755
            'http://www.example.com', 'appendpath_option'),
 
756
            config.POLICY_APPENDPATH)
 
757
 
 
758
    def test_location_without_username(self):
 
759
        self.get_branch_config('http://www.example.com/ignoreparent')
 
760
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
 
761
                         self.my_config.username())
 
762
 
 
763
    def test_location_not_listed(self):
 
764
        """Test that the global username is used when no location matches"""
 
765
        self.get_branch_config('/home/robertc/sources')
 
766
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
 
767
                         self.my_config.username())
 
768
 
 
769
    def test_overriding_location(self):
 
770
        self.get_branch_config('http://www.example.com/foo')
 
771
        self.assertEqual('Robert Collins <robertc@example.org>',
 
772
                         self.my_config.username())
 
773
 
 
774
    def test_signatures_not_set(self):
 
775
        self.get_branch_config('http://www.example.com',
 
776
                                 global_config=sample_ignore_signatures)
 
777
        self.assertEqual(config.CHECK_ALWAYS,
 
778
                         self.my_config.signature_checking())
 
779
        self.assertEqual(config.SIGN_NEVER,
 
780
                         self.my_config.signing_policy())
 
781
 
 
782
    def test_signatures_never(self):
 
783
        self.get_branch_config('/a/c')
 
784
        self.assertEqual(config.CHECK_NEVER,
 
785
                         self.my_config.signature_checking())
 
786
 
 
787
    def test_signatures_when_available(self):
 
788
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
 
789
        self.assertEqual(config.CHECK_IF_POSSIBLE,
 
790
                         self.my_config.signature_checking())
 
791
 
 
792
    def test_signatures_always(self):
 
793
        self.get_branch_config('/b')
 
794
        self.assertEqual(config.CHECK_ALWAYS,
 
795
                         self.my_config.signature_checking())
 
796
 
 
797
    def test_gpg_signing_command(self):
 
798
        self.get_branch_config('/b')
 
799
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
 
800
 
 
801
    def test_gpg_signing_command_missing(self):
 
802
        self.get_branch_config('/a')
 
803
        self.assertEqual("false", self.my_config.gpg_signing_command())
 
804
 
 
805
    def test_get_user_option_global(self):
 
806
        self.get_branch_config('/a')
 
807
        self.assertEqual('something',
 
808
                         self.my_config.get_user_option('user_global_option'))
 
809
 
 
810
    def test_get_user_option_local(self):
 
811
        self.get_branch_config('/a')
 
812
        self.assertEqual('local',
 
813
                         self.my_config.get_user_option('user_local_option'))
 
814
 
 
815
    def test_get_user_option_appendpath(self):
 
816
        # returned as is for the base path:
 
817
        self.get_branch_config('http://www.example.com')
 
818
        self.assertEqual('append',
 
819
                         self.my_config.get_user_option('appendpath_option'))
 
820
        # Extra path components get appended:
 
821
        self.get_branch_config('http://www.example.com/a/b/c')
 
822
        self.assertEqual('append/a/b/c',
 
823
                         self.my_config.get_user_option('appendpath_option'))
 
824
        # Overriden for http://www.example.com/dir, where it is a
 
825
        # normal option:
 
826
        self.get_branch_config('http://www.example.com/dir/a/b/c')
 
827
        self.assertEqual('normal',
 
828
                         self.my_config.get_user_option('appendpath_option'))
 
829
 
 
830
    def test_get_user_option_norecurse(self):
 
831
        self.get_branch_config('http://www.example.com')
 
832
        self.assertEqual('norecurse',
 
833
                         self.my_config.get_user_option('norecurse_option'))
 
834
        self.get_branch_config('http://www.example.com/dir')
 
835
        self.assertEqual(None,
 
836
                         self.my_config.get_user_option('norecurse_option'))
 
837
        # http://www.example.com/norecurse is a recurse=False section
 
838
        # that redefines normal_option.  Subdirectories do not pick up
 
839
        # this redefinition.
 
840
        self.get_branch_config('http://www.example.com/norecurse')
 
841
        self.assertEqual('norecurse',
 
842
                         self.my_config.get_user_option('normal_option'))
 
843
        self.get_branch_config('http://www.example.com/norecurse/subdir')
 
844
        self.assertEqual('normal',
 
845
                         self.my_config.get_user_option('normal_option'))
 
846
 
 
847
    def test_set_user_option_norecurse(self):
 
848
        self.get_branch_config('http://www.example.com')
 
849
        self.my_config.set_user_option('foo', 'bar',
 
850
                                       store=config.STORE_LOCATION_NORECURSE)
 
851
        self.assertEqual(
 
852
            self.my_location_config._get_option_policy(
 
853
            'http://www.example.com', 'foo'),
 
854
            config.POLICY_NORECURSE)
 
855
 
 
856
    def test_set_user_option_appendpath(self):
 
857
        self.get_branch_config('http://www.example.com')
 
858
        self.my_config.set_user_option('foo', 'bar',
 
859
                                       store=config.STORE_LOCATION_APPENDPATH)
 
860
        self.assertEqual(
 
861
            self.my_location_config._get_option_policy(
 
862
            'http://www.example.com', 'foo'),
 
863
            config.POLICY_APPENDPATH)
 
864
 
 
865
    def test_set_user_option_change_policy(self):
 
866
        self.get_branch_config('http://www.example.com')
 
867
        self.my_config.set_user_option('norecurse_option', 'normal',
 
868
                                       store=config.STORE_LOCATION)
 
869
        self.assertEqual(
 
870
            self.my_location_config._get_option_policy(
 
871
            'http://www.example.com', 'norecurse_option'),
 
872
            config.POLICY_NONE)
 
873
 
 
874
    def test_set_user_option_recurse_false_section(self):
 
875
        # The following section has recurse=False set.  The test is to
 
876
        # make sure that a normal option can be added to the section,
 
877
        # converting recurse=False to the norecurse policy.
 
878
        self.get_branch_config('http://www.example.com/norecurse')
 
879
        self.callDeprecated(['The recurse option is deprecated as of 0.14.  '
 
880
                             'The section "http://www.example.com/norecurse" '
 
881
                             'has been converted to use policies.'],
 
882
                            self.my_config.set_user_option,
 
883
                            'foo', 'bar', store=config.STORE_LOCATION)
 
884
        self.assertEqual(
 
885
            self.my_location_config._get_option_policy(
 
886
            'http://www.example.com/norecurse', 'foo'),
 
887
            config.POLICY_NONE)
 
888
        # The previously existing option is still norecurse:
 
889
        self.assertEqual(
 
890
            self.my_location_config._get_option_policy(
 
891
            'http://www.example.com/norecurse', 'normal_option'),
 
892
            config.POLICY_NORECURSE)
 
893
 
 
894
    def test_post_commit_default(self):
 
895
        self.get_branch_config('/a/c')
 
896
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
897
                         self.my_config.post_commit())
 
898
 
 
899
    def get_branch_config(self, location, global_config=None):
 
900
        if global_config is None:
 
901
            global_file = StringIO(sample_config_text.encode('utf-8'))
 
902
        else:
 
903
            global_file = StringIO(global_config.encode('utf-8'))
 
904
        branches_file = StringIO(sample_branches_text.encode('utf-8'))
 
905
        self.my_config = config.BranchConfig(FakeBranch(location))
 
906
        # Force location config to use specified file
 
907
        self.my_location_config = self.my_config._get_location_config()
 
908
        self.my_location_config._get_parser(branches_file)
 
909
        # Force global config to use specified file
 
910
        self.my_config._get_global_config()._get_parser(global_file)
 
911
 
 
912
    def test_set_user_setting_sets_and_saves(self):
 
913
        self.get_branch_config('/a/c')
 
914
        record = InstrumentedConfigObj("foo")
 
915
        self.my_location_config._parser = record
 
916
 
 
917
        real_mkdir = os.mkdir
 
918
        self.created = False
 
919
        def checked_mkdir(path, mode=0777):
 
920
            self.log('making directory: %s', path)
 
921
            real_mkdir(path, mode)
 
922
            self.created = True
 
923
 
 
924
        os.mkdir = checked_mkdir
 
925
        try:
 
926
            self.callDeprecated(['The recurse option is deprecated as of '
 
927
                                 '0.14.  The section "/a/c" has been '
 
928
                                 'converted to use policies.'],
 
929
                                self.my_config.set_user_option,
 
930
                                'foo', 'bar', store=config.STORE_LOCATION)
 
931
        finally:
 
932
            os.mkdir = real_mkdir
 
933
 
 
934
        self.failUnless(self.created, 'Failed to create ~/.bazaar')
 
935
        self.assertEqual([('__contains__', '/a/c'),
 
936
                          ('__contains__', '/a/c/'),
 
937
                          ('__setitem__', '/a/c', {}),
 
938
                          ('__getitem__', '/a/c'),
 
939
                          ('__setitem__', 'foo', 'bar'),
 
940
                          ('__getitem__', '/a/c'),
 
941
                          ('as_bool', 'recurse'),
 
942
                          ('__getitem__', '/a/c'),
 
943
                          ('__delitem__', 'recurse'),
 
944
                          ('__getitem__', '/a/c'),
 
945
                          ('keys',),
 
946
                          ('__getitem__', '/a/c'),
 
947
                          ('__contains__', 'foo:policy'),
 
948
                          ('write',)],
 
949
                         record._calls[1:])
 
950
 
 
951
    def test_set_user_setting_sets_and_saves2(self):
 
952
        self.get_branch_config('/a/c')
 
953
        self.assertIs(self.my_config.get_user_option('foo'), None)
 
954
        self.my_config.set_user_option('foo', 'bar')
 
955
        self.assertEqual(
 
956
            self.my_config.branch.control_files.files['branch.conf'].strip(),
 
957
            'foo = bar')
 
958
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
 
959
        self.my_config.set_user_option('foo', 'baz',
 
960
                                       store=config.STORE_LOCATION)
 
961
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
 
962
        self.my_config.set_user_option('foo', 'qux')
 
963
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
 
964
 
 
965
    def test_get_bzr_remote_path(self):
 
966
        my_config = config.LocationConfig('/a/c')
 
967
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
 
968
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
 
969
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
 
970
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
971
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
 
972
 
 
973
 
 
974
precedence_global = 'option = global'
 
975
precedence_branch = 'option = branch'
 
976
precedence_location = """
 
977
[http://]
 
978
recurse = true
 
979
option = recurse
 
980
[http://example.com/specific]
 
981
option = exact
 
982
"""
 
983
 
 
984
 
 
985
class TestBranchConfigItems(tests.TestCaseInTempDir):
 
986
 
 
987
    def get_branch_config(self, global_config=None, location=None,
 
988
                          location_config=None, branch_data_config=None):
 
989
        my_config = config.BranchConfig(FakeBranch(location))
 
990
        if global_config is not None:
 
991
            global_file = StringIO(global_config.encode('utf-8'))
 
992
            my_config._get_global_config()._get_parser(global_file)
 
993
        self.my_location_config = my_config._get_location_config()
 
994
        if location_config is not None:
 
995
            location_file = StringIO(location_config.encode('utf-8'))
 
996
            self.my_location_config._get_parser(location_file)
 
997
        if branch_data_config is not None:
 
998
            my_config.branch.control_files.files['branch.conf'] = \
 
999
                branch_data_config
 
1000
        return my_config
 
1001
 
 
1002
    def test_user_id(self):
 
1003
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
 
1004
        my_config = config.BranchConfig(branch)
 
1005
        self.assertEqual("Robert Collins <robertc@example.net>",
 
1006
                         my_config.username())
 
1007
        my_config.branch.control_files.files['email'] = "John"
 
1008
        my_config.set_user_option('email',
 
1009
                                  "Robert Collins <robertc@example.org>")
 
1010
        self.assertEqual("John", my_config.username())
 
1011
        del my_config.branch.control_files.files['email']
 
1012
        self.assertEqual("Robert Collins <robertc@example.org>",
 
1013
                         my_config.username())
 
1014
 
 
1015
    def test_not_set_in_branch(self):
 
1016
        my_config = self.get_branch_config(sample_config_text)
 
1017
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
 
1018
                         my_config._get_user_id())
 
1019
        my_config.branch.control_files.files['email'] = "John"
 
1020
        self.assertEqual("John", my_config._get_user_id())
 
1021
 
 
1022
    def test_BZR_EMAIL_OVERRIDES(self):
 
1023
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
 
1024
        branch = FakeBranch()
 
1025
        my_config = config.BranchConfig(branch)
 
1026
        self.assertEqual("Robert Collins <robertc@example.org>",
 
1027
                         my_config.username())
 
1028
 
 
1029
    def test_signatures_forced(self):
 
1030
        my_config = self.get_branch_config(
 
1031
            global_config=sample_always_signatures)
 
1032
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
1033
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
 
1034
        self.assertTrue(my_config.signature_needed())
 
1035
 
 
1036
    def test_signatures_forced_branch(self):
 
1037
        my_config = self.get_branch_config(
 
1038
            global_config=sample_ignore_signatures,
 
1039
            branch_data_config=sample_always_signatures)
 
1040
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
1041
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
 
1042
        self.assertTrue(my_config.signature_needed())
 
1043
 
 
1044
    def test_gpg_signing_command(self):
 
1045
        my_config = self.get_branch_config(
 
1046
            # branch data cannot set gpg_signing_command
 
1047
            branch_data_config="gpg_signing_command=pgp")
 
1048
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
1049
        my_config._get_global_config()._get_parser(config_file)
 
1050
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
 
1051
 
 
1052
    def test_get_user_option_global(self):
 
1053
        branch = FakeBranch()
 
1054
        my_config = config.BranchConfig(branch)
 
1055
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
1056
        (my_config._get_global_config()._get_parser(config_file))
 
1057
        self.assertEqual('something',
 
1058
                         my_config.get_user_option('user_global_option'))
 
1059
 
 
1060
    def test_post_commit_default(self):
 
1061
        branch = FakeBranch()
 
1062
        my_config = self.get_branch_config(sample_config_text, '/a/c',
 
1063
                                           sample_branches_text)
 
1064
        self.assertEqual(my_config.branch.base, '/a/c')
 
1065
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
1066
                         my_config.post_commit())
 
1067
        my_config.set_user_option('post_commit', 'rmtree_root')
 
1068
        # post-commit is ignored when bresent in branch data
 
1069
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
1070
                         my_config.post_commit())
 
1071
        my_config.set_user_option('post_commit', 'rmtree_root',
 
1072
                                  store=config.STORE_LOCATION)
 
1073
        self.assertEqual('rmtree_root', my_config.post_commit())
 
1074
 
 
1075
    def test_config_precedence(self):
 
1076
        my_config = self.get_branch_config(global_config=precedence_global)
 
1077
        self.assertEqual(my_config.get_user_option('option'), 'global')
 
1078
        my_config = self.get_branch_config(global_config=precedence_global,
 
1079
                                      branch_data_config=precedence_branch)
 
1080
        self.assertEqual(my_config.get_user_option('option'), 'branch')
 
1081
        my_config = self.get_branch_config(global_config=precedence_global,
 
1082
                                      branch_data_config=precedence_branch,
 
1083
                                      location_config=precedence_location)
 
1084
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
 
1085
        my_config = self.get_branch_config(global_config=precedence_global,
 
1086
                                      branch_data_config=precedence_branch,
 
1087
                                      location_config=precedence_location,
 
1088
                                      location='http://example.com/specific')
 
1089
        self.assertEqual(my_config.get_user_option('option'), 'exact')
 
1090
 
 
1091
    def test_get_mail_client(self):
 
1092
        config = self.get_branch_config()
 
1093
        client = config.get_mail_client()
 
1094
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1095
 
 
1096
        # Specific clients
 
1097
        config.set_user_option('mail_client', 'evolution')
 
1098
        client = config.get_mail_client()
 
1099
        self.assertIsInstance(client, mail_client.Evolution)
 
1100
 
 
1101
        config.set_user_option('mail_client', 'kmail')
 
1102
        client = config.get_mail_client()
 
1103
        self.assertIsInstance(client, mail_client.KMail)
 
1104
 
 
1105
        config.set_user_option('mail_client', 'mutt')
 
1106
        client = config.get_mail_client()
 
1107
        self.assertIsInstance(client, mail_client.Mutt)
 
1108
 
 
1109
        config.set_user_option('mail_client', 'thunderbird')
 
1110
        client = config.get_mail_client()
 
1111
        self.assertIsInstance(client, mail_client.Thunderbird)
 
1112
 
 
1113
        # Generic options
 
1114
        config.set_user_option('mail_client', 'default')
 
1115
        client = config.get_mail_client()
 
1116
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1117
 
 
1118
        config.set_user_option('mail_client', 'editor')
 
1119
        client = config.get_mail_client()
 
1120
        self.assertIsInstance(client, mail_client.Editor)
 
1121
 
 
1122
        config.set_user_option('mail_client', 'mapi')
 
1123
        client = config.get_mail_client()
 
1124
        self.assertIsInstance(client, mail_client.MAPIClient)
 
1125
 
 
1126
        config.set_user_option('mail_client', 'xdg-email')
 
1127
        client = config.get_mail_client()
 
1128
        self.assertIsInstance(client, mail_client.XDGEmail)
 
1129
 
 
1130
        config.set_user_option('mail_client', 'firebird')
 
1131
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
 
1132
 
 
1133
 
 
1134
class TestMailAddressExtraction(tests.TestCase):
 
1135
 
 
1136
    def test_extract_email_address(self):
 
1137
        self.assertEqual('jane@test.com',
 
1138
                         config.extract_email_address('Jane <jane@test.com>'))
 
1139
        self.assertRaises(errors.NoEmailInUsername,
 
1140
                          config.extract_email_address, 'Jane Tester')
 
1141
 
 
1142
    def test_parse_username(self):
 
1143
        self.assertEqual(('', 'jdoe@example.com'),
 
1144
                         config.parse_username('jdoe@example.com'))
 
1145
        self.assertEqual(('', 'jdoe@example.com'),
 
1146
                         config.parse_username('<jdoe@example.com>'))
 
1147
        self.assertEqual(('John Doe', 'jdoe@example.com'),
 
1148
                         config.parse_username('John Doe <jdoe@example.com>'))
 
1149
        self.assertEqual(('John Doe', ''),
 
1150
                         config.parse_username('John Doe'))
 
1151
        self.assertEqual(('John Doe', 'jdoe@example.com'),
 
1152
                         config.parse_username('John Doe jdoe@example.com'))
 
1153
 
 
1154
class TestTreeConfig(tests.TestCaseWithTransport):
 
1155
 
 
1156
    def test_get_value(self):
 
1157
        """Test that retreiving a value from a section is possible"""
 
1158
        branch = self.make_branch('.')
 
1159
        tree_config = config.TreeConfig(branch)
 
1160
        tree_config.set_option('value', 'key', 'SECTION')
 
1161
        tree_config.set_option('value2', 'key2')
 
1162
        tree_config.set_option('value3-top', 'key3')
 
1163
        tree_config.set_option('value3-section', 'key3', 'SECTION')
 
1164
        value = tree_config.get_option('key', 'SECTION')
 
1165
        self.assertEqual(value, 'value')
 
1166
        value = tree_config.get_option('key2')
 
1167
        self.assertEqual(value, 'value2')
 
1168
        self.assertEqual(tree_config.get_option('non-existant'), None)
 
1169
        value = tree_config.get_option('non-existant', 'SECTION')
 
1170
        self.assertEqual(value, None)
 
1171
        value = tree_config.get_option('non-existant', default='default')
 
1172
        self.assertEqual(value, 'default')
 
1173
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
 
1174
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
 
1175
        self.assertEqual(value, 'default')
 
1176
        value = tree_config.get_option('key3')
 
1177
        self.assertEqual(value, 'value3-top')
 
1178
        value = tree_config.get_option('key3', 'SECTION')
 
1179
        self.assertEqual(value, 'value3-section')
 
1180
 
 
1181
 
 
1182
class TestTransportConfig(tests.TestCaseWithTransport):
 
1183
 
 
1184
    def test_get_value(self):
 
1185
        """Test that retreiving a value from a section is possible"""
 
1186
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
 
1187
                                               'control.conf')
 
1188
        bzrdir_config.set_option('value', 'key', 'SECTION')
 
1189
        bzrdir_config.set_option('value2', 'key2')
 
1190
        bzrdir_config.set_option('value3-top', 'key3')
 
1191
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
 
1192
        value = bzrdir_config.get_option('key', 'SECTION')
 
1193
        self.assertEqual(value, 'value')
 
1194
        value = bzrdir_config.get_option('key2')
 
1195
        self.assertEqual(value, 'value2')
 
1196
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
 
1197
        value = bzrdir_config.get_option('non-existant', 'SECTION')
 
1198
        self.assertEqual(value, None)
 
1199
        value = bzrdir_config.get_option('non-existant', default='default')
 
1200
        self.assertEqual(value, 'default')
 
1201
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
 
1202
        value = bzrdir_config.get_option('key2', 'NOSECTION',
 
1203
                                         default='default')
 
1204
        self.assertEqual(value, 'default')
 
1205
        value = bzrdir_config.get_option('key3')
 
1206
        self.assertEqual(value, 'value3-top')
 
1207
        value = bzrdir_config.get_option('key3', 'SECTION')
 
1208
        self.assertEqual(value, 'value3-section')
 
1209
 
 
1210
    def test_set_unset_default_stack_on(self):
 
1211
        my_dir = self.make_bzrdir('.')
 
1212
        bzrdir_config = config.BzrDirConfig(my_dir)
 
1213
        self.assertIs(None, bzrdir_config.get_default_stack_on())
 
1214
        bzrdir_config.set_default_stack_on('Foo')
 
1215
        self.assertEqual('Foo', bzrdir_config._config.get_option(
 
1216
                         'default_stack_on'))
 
1217
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
 
1218
        bzrdir_config.set_default_stack_on(None)
 
1219
        self.assertIs(None, bzrdir_config.get_default_stack_on())
 
1220
 
 
1221
 
 
1222
class TestAuthenticationConfigFile(tests.TestCase):
 
1223
    """Test the authentication.conf file matching"""
 
1224
 
 
1225
    def _got_user_passwd(self, expected_user, expected_password,
 
1226
                         config, *args, **kwargs):
 
1227
        credentials = config.get_credentials(*args, **kwargs)
 
1228
        if credentials is None:
 
1229
            user = None
 
1230
            password = None
 
1231
        else:
 
1232
            user = credentials['user']
 
1233
            password = credentials['password']
 
1234
        self.assertEquals(expected_user, user)
 
1235
        self.assertEquals(expected_password, password)
 
1236
 
 
1237
    def test_empty_config(self):
 
1238
        conf = config.AuthenticationConfig(_file=StringIO())
 
1239
        self.assertEquals({}, conf._get_config())
 
1240
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
 
1241
 
 
1242
    def test_missing_auth_section_header(self):
 
1243
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
 
1244
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1245
 
 
1246
    def test_auth_section_header_not_closed(self):
 
1247
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
 
1248
        self.assertRaises(errors.ParseConfigError, conf._get_config)
 
1249
 
 
1250
    def test_auth_value_not_boolean(self):
 
1251
        conf = config.AuthenticationConfig(_file=StringIO(
 
1252
                """[broken]
 
1253
scheme=ftp
 
1254
user=joe
 
1255
verify_certificates=askme # Error: Not a boolean
 
1256
"""))
 
1257
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1258
 
 
1259
    def test_auth_value_not_int(self):
 
1260
        conf = config.AuthenticationConfig(_file=StringIO(
 
1261
                """[broken]
 
1262
scheme=ftp
 
1263
user=joe
 
1264
port=port # Error: Not an int
 
1265
"""))
 
1266
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1267
 
 
1268
    def test_unknown_password_encoding(self):
 
1269
        conf = config.AuthenticationConfig(_file=StringIO(
 
1270
                """[broken]
 
1271
scheme=ftp
 
1272
user=joe
 
1273
password_encoding=unknown
 
1274
"""))
 
1275
        self.assertRaises(ValueError, conf.get_password,
 
1276
                          'ftp', 'foo.net', 'joe')
 
1277
 
 
1278
    def test_credentials_for_scheme_host(self):
 
1279
        conf = config.AuthenticationConfig(_file=StringIO(
 
1280
                """# Identity on foo.net
 
1281
[ftp definition]
 
1282
scheme=ftp
 
1283
host=foo.net
 
1284
user=joe
 
1285
password=secret-pass
 
1286
"""))
 
1287
        # Basic matching
 
1288
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
 
1289
        # different scheme
 
1290
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
 
1291
        # different host
 
1292
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
 
1293
 
 
1294
    def test_credentials_for_host_port(self):
 
1295
        conf = config.AuthenticationConfig(_file=StringIO(
 
1296
                """# Identity on foo.net
 
1297
[ftp definition]
 
1298
scheme=ftp
 
1299
port=10021
 
1300
host=foo.net
 
1301
user=joe
 
1302
password=secret-pass
 
1303
"""))
 
1304
        # No port
 
1305
        self._got_user_passwd('joe', 'secret-pass',
 
1306
                              conf, 'ftp', 'foo.net', port=10021)
 
1307
        # different port
 
1308
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
 
1309
 
 
1310
    def test_for_matching_host(self):
 
1311
        conf = config.AuthenticationConfig(_file=StringIO(
 
1312
                """# Identity on foo.net
 
1313
[sourceforge]
 
1314
scheme=bzr
 
1315
host=bzr.sf.net
 
1316
user=joe
 
1317
password=joepass
 
1318
[sourceforge domain]
 
1319
scheme=bzr
 
1320
host=.bzr.sf.net
 
1321
user=georges
 
1322
password=bendover
 
1323
"""))
 
1324
        # matching domain
 
1325
        self._got_user_passwd('georges', 'bendover',
 
1326
                              conf, 'bzr', 'foo.bzr.sf.net')
 
1327
        # phishing attempt
 
1328
        self._got_user_passwd(None, None,
 
1329
                              conf, 'bzr', 'bbzr.sf.net')
 
1330
 
 
1331
    def test_for_matching_host_None(self):
 
1332
        conf = config.AuthenticationConfig(_file=StringIO(
 
1333
                """# Identity on foo.net
 
1334
[catchup bzr]
 
1335
scheme=bzr
 
1336
user=joe
 
1337
password=joepass
 
1338
[DEFAULT]
 
1339
user=georges
 
1340
password=bendover
 
1341
"""))
 
1342
        # match no host
 
1343
        self._got_user_passwd('joe', 'joepass',
 
1344
                              conf, 'bzr', 'quux.net')
 
1345
        # no host but different scheme
 
1346
        self._got_user_passwd('georges', 'bendover',
 
1347
                              conf, 'ftp', 'quux.net')
 
1348
 
 
1349
    def test_credentials_for_path(self):
 
1350
        conf = config.AuthenticationConfig(_file=StringIO(
 
1351
                """
 
1352
[http dir1]
 
1353
scheme=http
 
1354
host=bar.org
 
1355
path=/dir1
 
1356
user=jim
 
1357
password=jimpass
 
1358
[http dir2]
 
1359
scheme=http
 
1360
host=bar.org
 
1361
path=/dir2
 
1362
user=georges
 
1363
password=bendover
 
1364
"""))
 
1365
        # no path no dice
 
1366
        self._got_user_passwd(None, None,
 
1367
                              conf, 'http', host='bar.org', path='/dir3')
 
1368
        # matching path
 
1369
        self._got_user_passwd('georges', 'bendover',
 
1370
                              conf, 'http', host='bar.org', path='/dir2')
 
1371
        # matching subdir
 
1372
        self._got_user_passwd('jim', 'jimpass',
 
1373
                              conf, 'http', host='bar.org',path='/dir1/subdir')
 
1374
 
 
1375
    def test_credentials_for_user(self):
 
1376
        conf = config.AuthenticationConfig(_file=StringIO(
 
1377
                """
 
1378
[with user]
 
1379
scheme=http
 
1380
host=bar.org
 
1381
user=jim
 
1382
password=jimpass
 
1383
"""))
 
1384
        # Get user
 
1385
        self._got_user_passwd('jim', 'jimpass',
 
1386
                              conf, 'http', 'bar.org')
 
1387
        # Get same user
 
1388
        self._got_user_passwd('jim', 'jimpass',
 
1389
                              conf, 'http', 'bar.org', user='jim')
 
1390
        # Don't get a different user if one is specified
 
1391
        self._got_user_passwd(None, None,
 
1392
                              conf, 'http', 'bar.org', user='georges')
 
1393
 
 
1394
    def test_credentials_for_user_without_password(self):
 
1395
        conf = config.AuthenticationConfig(_file=StringIO(
 
1396
                """
 
1397
[without password]
 
1398
scheme=http
 
1399
host=bar.org
 
1400
user=jim
 
1401
"""))
 
1402
        # Get user but no password
 
1403
        self._got_user_passwd('jim', None,
 
1404
                              conf, 'http', 'bar.org')
 
1405
 
 
1406
    def test_verify_certificates(self):
 
1407
        conf = config.AuthenticationConfig(_file=StringIO(
 
1408
                """
 
1409
[self-signed]
 
1410
scheme=https
 
1411
host=bar.org
 
1412
user=jim
 
1413
password=jimpass
 
1414
verify_certificates=False
 
1415
[normal]
 
1416
scheme=https
 
1417
host=foo.net
 
1418
user=georges
 
1419
password=bendover
 
1420
"""))
 
1421
        credentials = conf.get_credentials('https', 'bar.org')
 
1422
        self.assertEquals(False, credentials.get('verify_certificates'))
 
1423
        credentials = conf.get_credentials('https', 'foo.net')
 
1424
        self.assertEquals(True, credentials.get('verify_certificates'))
 
1425
 
 
1426
 
 
1427
class TestAuthenticationStorage(tests.TestCaseInTempDir):
 
1428
 
 
1429
    def test_set_credentials(self):
 
1430
        conf = config.AuthenticationConfig()
 
1431
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
 
1432
        99, path='/foo', verify_certificates=False, realm='realm')
 
1433
        credentials = conf.get_credentials(host='host', scheme='scheme',
 
1434
                                           port=99, path='/foo',
 
1435
                                           realm='realm')
 
1436
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
 
1437
                       'verify_certificates': False, 'scheme': 'scheme', 
 
1438
                       'host': 'host', 'port': 99, 'path': '/foo', 
 
1439
                       'realm': 'realm'}
 
1440
        self.assertEqual(CREDENTIALS, credentials)
 
1441
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
 
1442
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
 
1443
        self.assertEqual(CREDENTIALS, credentials_from_disk)
 
1444
 
 
1445
    def test_reset_credentials_different_name(self):
 
1446
        conf = config.AuthenticationConfig()
 
1447
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
 
1448
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
 
1449
        self.assertIs(None, conf._get_config().get('name'))
 
1450
        credentials = conf.get_credentials(host='host', scheme='scheme')
 
1451
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
 
1452
                       'password', 'verify_certificates': True, 
 
1453
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
 
1454
                       'path': None, 'realm': None}
 
1455
        self.assertEqual(CREDENTIALS, credentials)
 
1456
 
 
1457
 
 
1458
class TestAuthenticationConfig(tests.TestCase):
 
1459
    """Test AuthenticationConfig behaviour"""
 
1460
 
 
1461
    def _check_default_password_prompt(self, expected_prompt_format, scheme,
 
1462
                                       host=None, port=None, realm=None,
 
1463
                                       path=None):
 
1464
        if host is None:
 
1465
            host = 'bar.org'
 
1466
        user, password = 'jim', 'precious'
 
1467
        expected_prompt = expected_prompt_format % {
 
1468
            'scheme': scheme, 'host': host, 'port': port,
 
1469
            'user': user, 'realm': realm}
 
1470
 
 
1471
        stdout = tests.StringIOWrapper()
 
1472
        stderr = tests.StringIOWrapper()
 
1473
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
 
1474
                                            stdout=stdout, stderr=stderr)
 
1475
        # We use an empty conf so that the user is always prompted
 
1476
        conf = config.AuthenticationConfig()
 
1477
        self.assertEquals(password,
 
1478
                          conf.get_password(scheme, host, user, port=port,
 
1479
                                            realm=realm, path=path))
 
1480
        self.assertEquals(expected_prompt, stderr.getvalue())
 
1481
        self.assertEquals('', stdout.getvalue())
 
1482
 
 
1483
    def _check_default_username_prompt(self, expected_prompt_format, scheme,
 
1484
                                       host=None, port=None, realm=None,
 
1485
                                       path=None):
 
1486
        if host is None:
 
1487
            host = 'bar.org'
 
1488
        username = 'jim'
 
1489
        expected_prompt = expected_prompt_format % {
 
1490
            'scheme': scheme, 'host': host, 'port': port,
 
1491
            'realm': realm}
 
1492
        stdout = tests.StringIOWrapper()
 
1493
        stderr = tests.StringIOWrapper()
 
1494
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
 
1495
                                            stdout=stdout, stderr=stderr)
 
1496
        # We use an empty conf so that the user is always prompted
 
1497
        conf = config.AuthenticationConfig()
 
1498
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
 
1499
                          realm=realm, path=path, ask=True))
 
1500
        self.assertEquals(expected_prompt, stderr.getvalue())
 
1501
        self.assertEquals('', stdout.getvalue())
 
1502
 
 
1503
    def test_username_defaults_prompts(self):
 
1504
        # HTTP prompts can't be tested here, see test_http.py
 
1505
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
 
1506
        self._check_default_username_prompt(
 
1507
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
 
1508
        self._check_default_username_prompt(
 
1509
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
 
1510
 
 
1511
    def test_username_default_no_prompt(self):
 
1512
        conf = config.AuthenticationConfig()
 
1513
        self.assertEquals(None,
 
1514
            conf.get_user('ftp', 'example.com'))
 
1515
        self.assertEquals("explicitdefault",
 
1516
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
 
1517
 
 
1518
    def test_password_default_prompts(self):
 
1519
        # HTTP prompts can't be tested here, see test_http.py
 
1520
        self._check_default_password_prompt(
 
1521
            'FTP %(user)s@%(host)s password: ', 'ftp')
 
1522
        self._check_default_password_prompt(
 
1523
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
 
1524
        self._check_default_password_prompt(
 
1525
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
 
1526
        # SMTP port handling is a bit special (it's handled if embedded in the
 
1527
        # host too)
 
1528
        # FIXME: should we: forbid that, extend it to other schemes, leave
 
1529
        # things as they are that's fine thank you ?
 
1530
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
 
1531
                                            'smtp')
 
1532
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
 
1533
                                            'smtp', host='bar.org:10025')
 
1534
        self._check_default_password_prompt(
 
1535
            'SMTP %(user)s@%(host)s:%(port)d password: ',
 
1536
            'smtp', port=10025)
 
1537
 
 
1538
    def test_ssh_password_emits_warning(self):
 
1539
        conf = config.AuthenticationConfig(_file=StringIO(
 
1540
                """
 
1541
[ssh with password]
 
1542
scheme=ssh
 
1543
host=bar.org
 
1544
user=jim
 
1545
password=jimpass
 
1546
"""))
 
1547
        entered_password = 'typed-by-hand'
 
1548
        stdout = tests.StringIOWrapper()
 
1549
        stderr = tests.StringIOWrapper()
 
1550
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
 
1551
                                            stdout=stdout, stderr=stderr)
 
1552
 
 
1553
        # Since the password defined in the authentication config is ignored,
 
1554
        # the user is prompted
 
1555
        self.assertEquals(entered_password,
 
1556
                          conf.get_password('ssh', 'bar.org', user='jim'))
 
1557
        self.assertContainsRe(
 
1558
            self._get_log(keep_log_file=True),
 
1559
            'password ignored in section \[ssh with password\]')
 
1560
 
 
1561
    def test_ssh_without_password_doesnt_emit_warning(self):
 
1562
        conf = config.AuthenticationConfig(_file=StringIO(
 
1563
                """
 
1564
[ssh with password]
 
1565
scheme=ssh
 
1566
host=bar.org
 
1567
user=jim
 
1568
"""))
 
1569
        entered_password = 'typed-by-hand'
 
1570
        stdout = tests.StringIOWrapper()
 
1571
        stderr = tests.StringIOWrapper()
 
1572
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
 
1573
                                            stdout=stdout,
 
1574
                                            stderr=stderr)
 
1575
 
 
1576
        # Since the password defined in the authentication config is ignored,
 
1577
        # the user is prompted
 
1578
        self.assertEquals(entered_password,
 
1579
                          conf.get_password('ssh', 'bar.org', user='jim'))
 
1580
        # No warning shoud be emitted since there is no password. We are only
 
1581
        # providing "user".
 
1582
        self.assertNotContainsRe(
 
1583
            self._get_log(keep_log_file=True),
 
1584
            'password ignored in section \[ssh with password\]')
 
1585
 
 
1586
    def test_uses_fallback_stores(self):
 
1587
        self._old_cs_registry = config.credential_store_registry
 
1588
        def restore():
 
1589
            config.credential_store_registry = self._old_cs_registry
 
1590
        self.addCleanup(restore)
 
1591
        config.credential_store_registry = config.CredentialStoreRegistry()
 
1592
        store = StubCredentialStore()
 
1593
        store.add_credentials("http", "example.com", "joe", "secret")
 
1594
        config.credential_store_registry.register("stub", store, fallback=True)
 
1595
        conf = config.AuthenticationConfig(_file=StringIO())
 
1596
        creds = conf.get_credentials("http", "example.com")
 
1597
        self.assertEquals("joe", creds["user"])
 
1598
        self.assertEquals("secret", creds["password"])
 
1599
 
 
1600
 
 
1601
class StubCredentialStore(config.CredentialStore):
 
1602
 
 
1603
    def __init__(self):
 
1604
        self._username = {}
 
1605
        self._password = {}
 
1606
 
 
1607
    def add_credentials(self, scheme, host, user, password=None):
 
1608
        self._username[(scheme, host)] = user
 
1609
        self._password[(scheme, host)] = password
 
1610
 
 
1611
    def get_credentials(self, scheme, host, port=None, user=None,
 
1612
        path=None, realm=None):
 
1613
        key = (scheme, host)
 
1614
        if not key in self._username:
 
1615
            return None
 
1616
        return { "scheme": scheme, "host": host, "port": port,
 
1617
                "user": self._username[key], "password": self._password[key]}
 
1618
 
 
1619
 
 
1620
class CountingCredentialStore(config.CredentialStore):
 
1621
 
 
1622
    def __init__(self):
 
1623
        self._calls = 0
 
1624
 
 
1625
    def get_credentials(self, scheme, host, port=None, user=None,
 
1626
        path=None, realm=None):
 
1627
        self._calls += 1
 
1628
        return None
 
1629
 
 
1630
 
 
1631
class TestCredentialStoreRegistry(tests.TestCase):
 
1632
 
 
1633
    def _get_cs_registry(self):
 
1634
        return config.credential_store_registry
 
1635
 
 
1636
    def test_default_credential_store(self):
 
1637
        r = self._get_cs_registry()
 
1638
        default = r.get_credential_store(None)
 
1639
        self.assertIsInstance(default, config.PlainTextCredentialStore)
 
1640
 
 
1641
    def test_unknown_credential_store(self):
 
1642
        r = self._get_cs_registry()
 
1643
        # It's hard to imagine someone creating a credential store named
 
1644
        # 'unknown' so we use that as an never registered key.
 
1645
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
 
1646
 
 
1647
    def test_fallback_none_registered(self):
 
1648
        r = config.CredentialStoreRegistry()
 
1649
        self.assertEquals(None,
 
1650
                          r.get_fallback_credentials("http", "example.com"))
 
1651
 
 
1652
    def test_register(self):
 
1653
        r = config.CredentialStoreRegistry()
 
1654
        r.register("stub", StubCredentialStore(), fallback=False)
 
1655
        r.register("another", StubCredentialStore(), fallback=True)
 
1656
        self.assertEquals(["another", "stub"], r.keys())
 
1657
 
 
1658
    def test_register_lazy(self):
 
1659
        r = config.CredentialStoreRegistry()
 
1660
        r.register_lazy("stub", "bzrlib.tests.test_config",
 
1661
                        "StubCredentialStore", fallback=False)
 
1662
        self.assertEquals(["stub"], r.keys())
 
1663
        self.assertIsInstance(r.get_credential_store("stub"),
 
1664
                              StubCredentialStore)
 
1665
 
 
1666
    def test_is_fallback(self):
 
1667
        r = config.CredentialStoreRegistry()
 
1668
        r.register("stub1", None, fallback=False)
 
1669
        r.register("stub2", None, fallback=True)
 
1670
        self.assertEquals(False, r.is_fallback("stub1"))
 
1671
        self.assertEquals(True, r.is_fallback("stub2"))
 
1672
 
 
1673
    def test_no_fallback(self):
 
1674
        r = config.CredentialStoreRegistry()
 
1675
        store = CountingCredentialStore()
 
1676
        r.register("count", store, fallback=False)
 
1677
        self.assertEquals(None,
 
1678
                          r.get_fallback_credentials("http", "example.com"))
 
1679
        self.assertEquals(0, store._calls)
 
1680
 
 
1681
    def test_fallback_credentials(self):
 
1682
        r = config.CredentialStoreRegistry()
 
1683
        store = StubCredentialStore()
 
1684
        store.add_credentials("http", "example.com",
 
1685
                              "somebody", "geheim")
 
1686
        r.register("stub", store, fallback=True)
 
1687
        creds = r.get_fallback_credentials("http", "example.com")
 
1688
        self.assertEquals("somebody", creds["user"])
 
1689
        self.assertEquals("geheim", creds["password"])
 
1690
 
 
1691
    def test_fallback_first_wins(self):
 
1692
        r = config.CredentialStoreRegistry()
 
1693
        stub1 = StubCredentialStore()
 
1694
        stub1.add_credentials("http", "example.com",
 
1695
                              "somebody", "stub1")
 
1696
        r.register("stub1", stub1, fallback=True)
 
1697
        stub2 = StubCredentialStore()
 
1698
        stub2.add_credentials("http", "example.com",
 
1699
                              "somebody", "stub2")
 
1700
        r.register("stub2", stub1, fallback=True)
 
1701
        creds = r.get_fallback_credentials("http", "example.com")
 
1702
        self.assertEquals("somebody", creds["user"])
 
1703
        self.assertEquals("stub1", creds["password"])
 
1704
 
 
1705
 
 
1706
class TestPlainTextCredentialStore(tests.TestCase):
 
1707
 
 
1708
    def test_decode_password(self):
 
1709
        r = config.credential_store_registry
 
1710
        plain_text = r.get_credential_store()
 
1711
        decoded = plain_text.decode_password(dict(password='secret'))
 
1712
        self.assertEquals('secret', decoded)
 
1713
 
 
1714
 
 
1715
# FIXME: Once we have a way to declare authentication to all test servers, we
 
1716
# can implement generic tests.
 
1717
# test_user_password_in_url
 
1718
# test_user_in_url_password_from_config
 
1719
# test_user_in_url_password_prompted
 
1720
# test_user_in_config
 
1721
# test_user_getpass.getuser
 
1722
# test_user_prompted ?
 
1723
class TestAuthenticationRing(tests.TestCaseWithTransport):
 
1724
    pass