~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Robert Collins
  • Date: 2009-07-07 04:32:13 UTC
  • mto: This revision was merged to the branch mainline in revision 4524.
  • Revision ID: robertc@robertcollins.net-20090707043213-4hjjhgr40iq7gk2d
More informative assertions in xml serialisation.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2008 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
13
13
#
14
14
# You should have received a copy of the GNU General Public License
15
15
# along with this program; if not, write to the Free Software
16
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
 
18
18
"""Tests for finding and reading the bzr config file[s]."""
19
19
# import system imports here
20
 
from bzrlib.util.configobj.configobj import ConfigObj, ConfigObjError
21
20
from cStringIO import StringIO
22
21
import os
23
22
import sys
24
23
 
25
24
#import bzrlib specific imports here
26
25
from bzrlib import (
 
26
    branch,
 
27
    bzrdir,
27
28
    config,
28
29
    errors,
29
30
    osutils,
 
31
    mail_client,
 
32
    ui,
30
33
    urlutils,
 
34
    tests,
31
35
    trace,
 
36
    transport,
32
37
    )
33
 
from bzrlib.branch import Branch
34
 
from bzrlib.bzrdir import BzrDir
35
 
from bzrlib.tests import TestCase, TestCaseInTempDir, TestCaseWithTransport
 
38
from bzrlib.util.configobj import configobj
36
39
 
37
40
 
38
41
sample_long_alias="log -r-15..-1 --line"
144
147
            self.base = "http://example.com/branches/demo"
145
148
        else:
146
149
            self.base = base
147
 
        self.control_files = FakeControlFiles(user_id=user_id)
 
150
        self._transport = self.control_files = \
 
151
            FakeControlFilesAndTransport(user_id=user_id)
 
152
 
 
153
    def _get_config(self):
 
154
        return config.TransportConfig(self._transport, 'branch.conf')
148
155
 
149
156
    def lock_write(self):
150
157
        pass
153
160
        pass
154
161
 
155
162
 
156
 
class FakeControlFiles(object):
 
163
class FakeControlFilesAndTransport(object):
157
164
 
158
165
    def __init__(self, user_id=None):
159
 
        self.email = user_id
160
166
        self.files = {}
 
167
        if user_id:
 
168
            self.files['email'] = user_id
 
169
        self._transport = self
161
170
 
162
171
    def get_utf8(self, filename):
163
 
        if filename != 'email':
164
 
            raise NotImplementedError
165
 
        if self.email is not None:
166
 
            return StringIO(self.email)
167
 
        raise errors.NoSuchFile(filename)
 
172
        # from LockableFiles
 
173
        raise AssertionError("get_utf8 should no longer be used")
168
174
 
169
175
    def get(self, filename):
 
176
        # from Transport
170
177
        try:
171
178
            return StringIO(self.files[filename])
172
179
        except KeyError:
173
180
            raise errors.NoSuchFile(filename)
174
181
 
 
182
    def get_bytes(self, filename):
 
183
        # from Transport
 
184
        try:
 
185
            return self.files[filename]
 
186
        except KeyError:
 
187
            raise errors.NoSuchFile(filename)
 
188
 
175
189
    def put(self, filename, fileobj):
176
190
        self.files[filename] = fileobj.read()
177
191
 
 
192
    def put_file(self, filename, fileobj):
 
193
        return self.put(filename, fileobj)
 
194
 
178
195
 
179
196
class InstrumentedConfig(config.Config):
180
197
    """An instrumented config that supplies stubs for template methods."""
181
 
    
 
198
 
182
199
    def __init__(self):
183
200
        super(InstrumentedConfig, self).__init__()
184
201
        self._calls = []
200
217
active = True
201
218
nonactive = False
202
219
"""
203
 
class TestConfigObj(TestCase):
 
220
 
 
221
 
 
222
class TestConfigObj(tests.TestCase):
 
223
 
204
224
    def test_get_bool(self):
205
 
        from bzrlib.config import ConfigObj
206
 
        co = ConfigObj(StringIO(bool_config))
 
225
        co = config.ConfigObj(StringIO(bool_config))
207
226
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
208
227
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
209
228
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
210
229
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
211
230
 
212
 
 
213
 
class TestConfig(TestCase):
 
231
    def test_hash_sign_in_value(self):
 
232
        """
 
233
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
 
234
        treated as comments when read in again. (#86838)
 
235
        """
 
236
        co = config.ConfigObj()
 
237
        co['test'] = 'foo#bar'
 
238
        lines = co.write()
 
239
        self.assertEqual(lines, ['test = "foo#bar"'])
 
240
        co2 = config.ConfigObj(lines)
 
241
        self.assertEqual(co2['test'], 'foo#bar')
 
242
 
 
243
 
 
244
erroneous_config = """[section] # line 1
 
245
good=good # line 2
 
246
[section] # line 3
 
247
whocares=notme # line 4
 
248
"""
 
249
 
 
250
 
 
251
class TestConfigObjErrors(tests.TestCase):
 
252
 
 
253
    def test_duplicate_section_name_error_line(self):
 
254
        try:
 
255
            co = configobj.ConfigObj(StringIO(erroneous_config),
 
256
                                     raise_errors=True)
 
257
        except config.configobj.DuplicateError, e:
 
258
            self.assertEqual(3, e.line_number)
 
259
        else:
 
260
            self.fail('Error in config file not detected')
 
261
 
 
262
 
 
263
class TestConfig(tests.TestCase):
214
264
 
215
265
    def test_constructs(self):
216
266
        config.Config()
217
 
 
 
267
 
218
268
    def test_no_default_editor(self):
219
269
        self.assertRaises(NotImplementedError, config.Config().get_editor)
220
270
 
266
316
        self.assertEqual('long', my_config.log_format())
267
317
 
268
318
 
269
 
class TestConfigPath(TestCase):
 
319
class TestConfigPath(tests.TestCase):
270
320
 
271
321
    def setUp(self):
272
322
        super(TestConfigPath, self).setUp()
274
324
        if sys.platform == 'win32':
275
325
            os.environ['BZR_HOME'] = \
276
326
                r'C:\Documents and Settings\bogus\Application Data'
 
327
            self.bzr_home = \
 
328
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
 
329
        else:
 
330
            self.bzr_home = '/home/bogus/.bazaar'
277
331
 
278
332
    def test_config_dir(self):
279
 
        if sys.platform == 'win32':
280
 
            self.assertEqual(config.config_dir(), 
281
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0')
282
 
        else:
283
 
            self.assertEqual(config.config_dir(), '/home/bogus/.bazaar')
 
333
        self.assertEqual(config.config_dir(), self.bzr_home)
284
334
 
285
335
    def test_config_filename(self):
286
 
        if sys.platform == 'win32':
287
 
            self.assertEqual(config.config_filename(), 
288
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/bazaar.conf')
289
 
        else:
290
 
            self.assertEqual(config.config_filename(),
291
 
                             '/home/bogus/.bazaar/bazaar.conf')
 
336
        self.assertEqual(config.config_filename(),
 
337
                         self.bzr_home + '/bazaar.conf')
292
338
 
293
339
    def test_branches_config_filename(self):
294
 
        if sys.platform == 'win32':
295
 
            self.assertEqual(config.branches_config_filename(), 
296
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/branches.conf')
297
 
        else:
298
 
            self.assertEqual(config.branches_config_filename(),
299
 
                             '/home/bogus/.bazaar/branches.conf')
 
340
        self.assertEqual(config.branches_config_filename(),
 
341
                         self.bzr_home + '/branches.conf')
300
342
 
301
343
    def test_locations_config_filename(self):
302
 
        if sys.platform == 'win32':
303
 
            self.assertEqual(config.locations_config_filename(), 
304
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/locations.conf')
305
 
        else:
306
 
            self.assertEqual(config.locations_config_filename(),
307
 
                             '/home/bogus/.bazaar/locations.conf')
308
 
 
309
 
class TestIniConfig(TestCase):
 
344
        self.assertEqual(config.locations_config_filename(),
 
345
                         self.bzr_home + '/locations.conf')
 
346
 
 
347
    def test_authentication_config_filename(self):
 
348
        self.assertEqual(config.authentication_config_filename(),
 
349
                         self.bzr_home + '/authentication.conf')
 
350
 
 
351
 
 
352
class TestIniConfig(tests.TestCase):
310
353
 
311
354
    def test_contructs(self):
312
355
        my_config = config.IniBasedConfig("nothing")
316
359
        my_config = config.IniBasedConfig(None)
317
360
        self.failUnless(
318
361
            isinstance(my_config._get_parser(file=config_file),
319
 
                        ConfigObj))
 
362
                        configobj.ConfigObj))
320
363
 
321
364
    def test_cached(self):
322
365
        config_file = StringIO(sample_config_text.encode('utf-8'))
325
368
        self.failUnless(my_config._get_parser() is parser)
326
369
 
327
370
 
328
 
class TestGetConfig(TestCase):
 
371
class TestGetConfig(tests.TestCase):
329
372
 
330
373
    def test_constructs(self):
331
374
        my_config = config.GlobalConfig()
332
375
 
333
376
    def test_calls_read_filenames(self):
334
 
        # replace the class that is constructured, to check its parameters
 
377
        # replace the class that is constructed, to check its parameters
335
378
        oldparserclass = config.ConfigObj
336
379
        config.ConfigObj = InstrumentedConfigObj
337
380
        my_config = config.GlobalConfig()
344
387
                                          'utf-8')])
345
388
 
346
389
 
347
 
class TestBranchConfig(TestCaseWithTransport):
 
390
class TestBranchConfig(tests.TestCaseWithTransport):
348
391
 
349
392
    def test_constructs(self):
350
393
        branch = FakeBranch()
360
403
 
361
404
    def test_get_config(self):
362
405
        """The Branch.get_config method works properly"""
363
 
        b = BzrDir.create_standalone_workingtree('.').branch
 
406
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
364
407
        my_config = b.get_config()
365
408
        self.assertIs(my_config.get_user_option('wacky'), None)
366
409
        my_config.set_user_option('wacky', 'unlikely')
367
410
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
368
411
 
369
412
        # Ensure we get the same thing if we start again
370
 
        b2 = Branch.open('.')
 
413
        b2 = branch.Branch.open('.')
371
414
        my_config2 = b2.get_config()
372
415
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
373
416
 
385
428
        locations = config.locations_config_filename()
386
429
        config.ensure_config_dir_exists()
387
430
        local_url = urlutils.local_path_to_url('branch')
388
 
        open(locations, 'wb').write('[%s]\nnickname = foobar' 
 
431
        open(locations, 'wb').write('[%s]\nnickname = foobar'
389
432
                                    % (local_url,))
390
433
        self.assertEqual('foobar', branch.nick)
391
434
 
396
439
 
397
440
        locations = config.locations_config_filename()
398
441
        config.ensure_config_dir_exists()
399
 
        open(locations, 'wb').write('[%s/branch]\nnickname = barry' 
 
442
        open(locations, 'wb').write('[%s/branch]\nnickname = barry'
400
443
                                    % (osutils.getcwd().encode('utf8'),))
401
444
        self.assertEqual('barry', branch.nick)
402
445
 
408
451
        local_path = osutils.getcwd().encode('utf8')
409
452
        # Surprisingly ConfigObj doesn't create a trailing newline
410
453
        self.check_file_contents(locations,
411
 
            '[%s/branch]\npush_location = http://foobar\npush_location:policy = norecurse' % (local_path,))
 
454
                                 '[%s/branch]\n'
 
455
                                 'push_location = http://foobar\n'
 
456
                                 'push_location:policy = norecurse\n'
 
457
                                 % (local_path,))
412
458
 
413
459
    def test_autonick_urlencoded(self):
414
460
        b = self.make_branch('!repo')
452
498
            trace.warning = _warning
453
499
 
454
500
 
455
 
class TestGlobalConfigItems(TestCase):
 
501
class TestGlobalConfigItems(tests.TestCase):
456
502
 
457
503
    def test_user_id(self):
458
504
        config_file = StringIO(sample_config_text.encode('utf-8'))
532
578
        my_config = self._get_sample_config()
533
579
        self.assertEqual("something",
534
580
                         my_config.get_user_option('user_global_option'))
535
 
        
 
581
 
536
582
    def test_post_commit_default(self):
537
583
        my_config = self._get_sample_config()
538
584
        self.assertEqual(None, my_config.post_commit())
545
591
        my_config = self._get_sample_config()
546
592
        self.assertEqual('help', my_config.get_alias('h'))
547
593
 
 
594
    def test_get_aliases(self):
 
595
        my_config = self._get_sample_config()
 
596
        aliases = my_config.get_aliases()
 
597
        self.assertEqual(2, len(aliases))
 
598
        sorted_keys = sorted(aliases)
 
599
        self.assertEqual('help', aliases[sorted_keys[0]])
 
600
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
 
601
 
548
602
    def test_get_no_alias(self):
549
603
        my_config = self._get_sample_config()
550
604
        self.assertEqual(None, my_config.get_alias('foo'))
554
608
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
555
609
 
556
610
 
557
 
class TestLocationConfig(TestCaseInTempDir):
 
611
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
 
612
 
 
613
    def test_empty(self):
 
614
        my_config = config.GlobalConfig()
 
615
        self.assertEqual(0, len(my_config.get_aliases()))
 
616
 
 
617
    def test_set_alias(self):
 
618
        my_config = config.GlobalConfig()
 
619
        alias_value = 'commit --strict'
 
620
        my_config.set_alias('commit', alias_value)
 
621
        new_config = config.GlobalConfig()
 
622
        self.assertEqual(alias_value, new_config.get_alias('commit'))
 
623
 
 
624
    def test_remove_alias(self):
 
625
        my_config = config.GlobalConfig()
 
626
        my_config.set_alias('commit', 'commit --strict')
 
627
        # Now remove the alias again.
 
628
        my_config.unset_alias('commit')
 
629
        new_config = config.GlobalConfig()
 
630
        self.assertIs(None, new_config.get_alias('commit'))
 
631
 
 
632
 
 
633
class TestLocationConfig(tests.TestCaseInTempDir):
558
634
 
559
635
    def test_constructs(self):
560
636
        my_config = config.LocationConfig('http://example.com')
564
640
        # This is testing the correct file names are provided.
565
641
        # TODO: consolidate with the test for GlobalConfigs filename checks.
566
642
        #
567
 
        # replace the class that is constructured, to check its parameters
 
643
        # replace the class that is constructed, to check its parameters
568
644
        oldparserclass = config.ConfigObj
569
645
        config.ConfigObj = InstrumentedConfigObj
570
646
        try:
598
674
    def test__get_matching_sections_no_match(self):
599
675
        self.get_branch_config('/')
600
676
        self.assertEqual([], self.my_location_config._get_matching_sections())
601
 
        
 
677
 
602
678
    def test__get_matching_sections_exact(self):
603
679
        self.get_branch_config('http://www.example.com')
604
680
        self.assertEqual([('http://www.example.com', '')],
605
681
                         self.my_location_config._get_matching_sections())
606
 
   
 
682
 
607
683
    def test__get_matching_sections_suffix_does_not(self):
608
684
        self.get_branch_config('http://www.example.com-com')
609
685
        self.assertEqual([], self.my_location_config._get_matching_sections())
621
697
    def test__get_matching_sections_ignoreparent_subdir(self):
622
698
        self.get_branch_config(
623
699
            'http://www.example.com/ignoreparent/childbranch')
624
 
        self.assertEqual([('http://www.example.com/ignoreparent', 'childbranch')],
 
700
        self.assertEqual([('http://www.example.com/ignoreparent',
 
701
                           'childbranch')],
625
702
                         self.my_location_config._get_matching_sections())
626
703
 
627
704
    def test__get_matching_sections_subdir_trailing_slash(self):
707
784
        self.get_branch_config('/a/c')
708
785
        self.assertEqual(config.CHECK_NEVER,
709
786
                         self.my_config.signature_checking())
710
 
        
 
787
 
711
788
    def test_signatures_when_available(self):
712
789
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
713
790
        self.assertEqual(config.CHECK_IF_POSSIBLE,
714
791
                         self.my_config.signature_checking())
715
 
        
 
792
 
716
793
    def test_signatures_always(self):
717
794
        self.get_branch_config('/b')
718
795
        self.assertEqual(config.CHECK_ALWAYS,
719
796
                         self.my_config.signature_checking())
720
 
        
 
797
 
721
798
    def test_gpg_signing_command(self):
722
799
        self.get_branch_config('/b')
723
800
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
877
954
        self.assertIs(self.my_config.get_user_option('foo'), None)
878
955
        self.my_config.set_user_option('foo', 'bar')
879
956
        self.assertEqual(
880
 
            self.my_config.branch.control_files.files['branch.conf'], 
 
957
            self.my_config.branch.control_files.files['branch.conf'].strip(),
881
958
            'foo = bar')
882
959
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
883
960
        self.my_config.set_user_option('foo', 'baz',
885
962
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
886
963
        self.my_config.set_user_option('foo', 'qux')
887
964
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
888
 
        
 
965
 
 
966
    def test_get_bzr_remote_path(self):
 
967
        my_config = config.LocationConfig('/a/c')
 
968
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
 
969
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
 
970
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
 
971
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
972
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
 
973
 
889
974
 
890
975
precedence_global = 'option = global'
891
976
precedence_branch = 'option = branch'
898
983
"""
899
984
 
900
985
 
901
 
class TestBranchConfigItems(TestCaseInTempDir):
 
986
class TestBranchConfigItems(tests.TestCaseInTempDir):
902
987
 
903
 
    def get_branch_config(self, global_config=None, location=None, 
 
988
    def get_branch_config(self, global_config=None, location=None,
904
989
                          location_config=None, branch_data_config=None):
905
990
        my_config = config.BranchConfig(FakeBranch(location))
906
991
        if global_config is not None:
920
1005
        my_config = config.BranchConfig(branch)
921
1006
        self.assertEqual("Robert Collins <robertc@example.net>",
922
1007
                         my_config.username())
923
 
        branch.control_files.email = "John"
924
 
        my_config.set_user_option('email', 
 
1008
        my_config.branch.control_files.files['email'] = "John"
 
1009
        my_config.set_user_option('email',
925
1010
                                  "Robert Collins <robertc@example.org>")
926
1011
        self.assertEqual("John", my_config.username())
927
 
        branch.control_files.email = None
 
1012
        del my_config.branch.control_files.files['email']
928
1013
        self.assertEqual("Robert Collins <robertc@example.org>",
929
1014
                         my_config.username())
930
1015
 
931
1016
    def test_not_set_in_branch(self):
932
1017
        my_config = self.get_branch_config(sample_config_text)
933
 
        my_config.branch.control_files.email = None
934
1018
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
935
1019
                         my_config._get_user_id())
936
 
        my_config.branch.control_files.email = "John"
 
1020
        my_config.branch.control_files.files['email'] = "John"
937
1021
        self.assertEqual("John", my_config._get_user_id())
938
1022
 
939
1023
    def test_BZR_EMAIL_OVERRIDES(self):
942
1026
        my_config = config.BranchConfig(branch)
943
1027
        self.assertEqual("Robert Collins <robertc@example.org>",
944
1028
                         my_config.username())
945
 
    
 
1029
 
946
1030
    def test_signatures_forced(self):
947
1031
        my_config = self.get_branch_config(
948
1032
            global_config=sample_always_signatures)
992
1076
    def test_config_precedence(self):
993
1077
        my_config = self.get_branch_config(global_config=precedence_global)
994
1078
        self.assertEqual(my_config.get_user_option('option'), 'global')
995
 
        my_config = self.get_branch_config(global_config=precedence_global, 
 
1079
        my_config = self.get_branch_config(global_config=precedence_global,
996
1080
                                      branch_data_config=precedence_branch)
997
1081
        self.assertEqual(my_config.get_user_option('option'), 'branch')
998
 
        my_config = self.get_branch_config(global_config=precedence_global, 
 
1082
        my_config = self.get_branch_config(global_config=precedence_global,
999
1083
                                      branch_data_config=precedence_branch,
1000
1084
                                      location_config=precedence_location)
1001
1085
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
1002
 
        my_config = self.get_branch_config(global_config=precedence_global, 
 
1086
        my_config = self.get_branch_config(global_config=precedence_global,
1003
1087
                                      branch_data_config=precedence_branch,
1004
1088
                                      location_config=precedence_location,
1005
1089
                                      location='http://example.com/specific')
1006
1090
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1007
1091
 
1008
 
 
1009
 
class TestMailAddressExtraction(TestCase):
 
1092
    def test_get_mail_client(self):
 
1093
        config = self.get_branch_config()
 
1094
        client = config.get_mail_client()
 
1095
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1096
 
 
1097
        # Specific clients
 
1098
        config.set_user_option('mail_client', 'evolution')
 
1099
        client = config.get_mail_client()
 
1100
        self.assertIsInstance(client, mail_client.Evolution)
 
1101
 
 
1102
        config.set_user_option('mail_client', 'kmail')
 
1103
        client = config.get_mail_client()
 
1104
        self.assertIsInstance(client, mail_client.KMail)
 
1105
 
 
1106
        config.set_user_option('mail_client', 'mutt')
 
1107
        client = config.get_mail_client()
 
1108
        self.assertIsInstance(client, mail_client.Mutt)
 
1109
 
 
1110
        config.set_user_option('mail_client', 'thunderbird')
 
1111
        client = config.get_mail_client()
 
1112
        self.assertIsInstance(client, mail_client.Thunderbird)
 
1113
 
 
1114
        # Generic options
 
1115
        config.set_user_option('mail_client', 'default')
 
1116
        client = config.get_mail_client()
 
1117
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1118
 
 
1119
        config.set_user_option('mail_client', 'editor')
 
1120
        client = config.get_mail_client()
 
1121
        self.assertIsInstance(client, mail_client.Editor)
 
1122
 
 
1123
        config.set_user_option('mail_client', 'mapi')
 
1124
        client = config.get_mail_client()
 
1125
        self.assertIsInstance(client, mail_client.MAPIClient)
 
1126
 
 
1127
        config.set_user_option('mail_client', 'xdg-email')
 
1128
        client = config.get_mail_client()
 
1129
        self.assertIsInstance(client, mail_client.XDGEmail)
 
1130
 
 
1131
        config.set_user_option('mail_client', 'firebird')
 
1132
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
 
1133
 
 
1134
 
 
1135
class TestMailAddressExtraction(tests.TestCase):
1010
1136
 
1011
1137
    def test_extract_email_address(self):
1012
1138
        self.assertEqual('jane@test.com',
1014
1140
        self.assertRaises(errors.NoEmailInUsername,
1015
1141
                          config.extract_email_address, 'Jane Tester')
1016
1142
 
 
1143
    def test_parse_username(self):
 
1144
        self.assertEqual(('', 'jdoe@example.com'),
 
1145
                         config.parse_username('jdoe@example.com'))
 
1146
        self.assertEqual(('', 'jdoe@example.com'),
 
1147
                         config.parse_username('<jdoe@example.com>'))
 
1148
        self.assertEqual(('John Doe', 'jdoe@example.com'),
 
1149
                         config.parse_username('John Doe <jdoe@example.com>'))
 
1150
        self.assertEqual(('John Doe', ''),
 
1151
                         config.parse_username('John Doe'))
 
1152
        self.assertEqual(('John Doe', 'jdoe@example.com'),
 
1153
                         config.parse_username('John Doe jdoe@example.com'))
1017
1154
 
1018
 
class TestTreeConfig(TestCaseWithTransport):
 
1155
class TestTreeConfig(tests.TestCaseWithTransport):
1019
1156
 
1020
1157
    def test_get_value(self):
1021
1158
        """Test that retreiving a value from a section is possible"""
1041
1178
        self.assertEqual(value, 'value3-top')
1042
1179
        value = tree_config.get_option('key3', 'SECTION')
1043
1180
        self.assertEqual(value, 'value3-section')
 
1181
 
 
1182
 
 
1183
class TestTransportConfig(tests.TestCaseWithTransport):
 
1184
 
 
1185
    def test_get_value(self):
 
1186
        """Test that retreiving a value from a section is possible"""
 
1187
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
 
1188
                                               'control.conf')
 
1189
        bzrdir_config.set_option('value', 'key', 'SECTION')
 
1190
        bzrdir_config.set_option('value2', 'key2')
 
1191
        bzrdir_config.set_option('value3-top', 'key3')
 
1192
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
 
1193
        value = bzrdir_config.get_option('key', 'SECTION')
 
1194
        self.assertEqual(value, 'value')
 
1195
        value = bzrdir_config.get_option('key2')
 
1196
        self.assertEqual(value, 'value2')
 
1197
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
 
1198
        value = bzrdir_config.get_option('non-existant', 'SECTION')
 
1199
        self.assertEqual(value, None)
 
1200
        value = bzrdir_config.get_option('non-existant', default='default')
 
1201
        self.assertEqual(value, 'default')
 
1202
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
 
1203
        value = bzrdir_config.get_option('key2', 'NOSECTION',
 
1204
                                         default='default')
 
1205
        self.assertEqual(value, 'default')
 
1206
        value = bzrdir_config.get_option('key3')
 
1207
        self.assertEqual(value, 'value3-top')
 
1208
        value = bzrdir_config.get_option('key3', 'SECTION')
 
1209
        self.assertEqual(value, 'value3-section')
 
1210
 
 
1211
    def test_set_unset_default_stack_on(self):
 
1212
        my_dir = self.make_bzrdir('.')
 
1213
        bzrdir_config = config.BzrDirConfig(my_dir)
 
1214
        self.assertIs(None, bzrdir_config.get_default_stack_on())
 
1215
        bzrdir_config.set_default_stack_on('Foo')
 
1216
        self.assertEqual('Foo', bzrdir_config._config.get_option(
 
1217
                         'default_stack_on'))
 
1218
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
 
1219
        bzrdir_config.set_default_stack_on(None)
 
1220
        self.assertIs(None, bzrdir_config.get_default_stack_on())
 
1221
 
 
1222
 
 
1223
class TestAuthenticationConfigFile(tests.TestCase):
 
1224
    """Test the authentication.conf file matching"""
 
1225
 
 
1226
    def _got_user_passwd(self, expected_user, expected_password,
 
1227
                         config, *args, **kwargs):
 
1228
        credentials = config.get_credentials(*args, **kwargs)
 
1229
        if credentials is None:
 
1230
            user = None
 
1231
            password = None
 
1232
        else:
 
1233
            user = credentials['user']
 
1234
            password = credentials['password']
 
1235
        self.assertEquals(expected_user, user)
 
1236
        self.assertEquals(expected_password, password)
 
1237
 
 
1238
    def test_empty_config(self):
 
1239
        conf = config.AuthenticationConfig(_file=StringIO())
 
1240
        self.assertEquals({}, conf._get_config())
 
1241
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
 
1242
 
 
1243
    def test_missing_auth_section_header(self):
 
1244
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
 
1245
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1246
 
 
1247
    def test_auth_section_header_not_closed(self):
 
1248
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
 
1249
        self.assertRaises(errors.ParseConfigError, conf._get_config)
 
1250
 
 
1251
    def test_auth_value_not_boolean(self):
 
1252
        conf = config.AuthenticationConfig(_file=StringIO(
 
1253
                """[broken]
 
1254
scheme=ftp
 
1255
user=joe
 
1256
verify_certificates=askme # Error: Not a boolean
 
1257
"""))
 
1258
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1259
 
 
1260
    def test_auth_value_not_int(self):
 
1261
        conf = config.AuthenticationConfig(_file=StringIO(
 
1262
                """[broken]
 
1263
scheme=ftp
 
1264
user=joe
 
1265
port=port # Error: Not an int
 
1266
"""))
 
1267
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1268
 
 
1269
    def test_unknown_password_encoding(self):
 
1270
        conf = config.AuthenticationConfig(_file=StringIO(
 
1271
                """[broken]
 
1272
scheme=ftp
 
1273
user=joe
 
1274
password_encoding=unknown
 
1275
"""))
 
1276
        self.assertRaises(ValueError, conf.get_password,
 
1277
                          'ftp', 'foo.net', 'joe')
 
1278
 
 
1279
    def test_credentials_for_scheme_host(self):
 
1280
        conf = config.AuthenticationConfig(_file=StringIO(
 
1281
                """# Identity on foo.net
 
1282
[ftp definition]
 
1283
scheme=ftp
 
1284
host=foo.net
 
1285
user=joe
 
1286
password=secret-pass
 
1287
"""))
 
1288
        # Basic matching
 
1289
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
 
1290
        # different scheme
 
1291
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
 
1292
        # different host
 
1293
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
 
1294
 
 
1295
    def test_credentials_for_host_port(self):
 
1296
        conf = config.AuthenticationConfig(_file=StringIO(
 
1297
                """# Identity on foo.net
 
1298
[ftp definition]
 
1299
scheme=ftp
 
1300
port=10021
 
1301
host=foo.net
 
1302
user=joe
 
1303
password=secret-pass
 
1304
"""))
 
1305
        # No port
 
1306
        self._got_user_passwd('joe', 'secret-pass',
 
1307
                              conf, 'ftp', 'foo.net', port=10021)
 
1308
        # different port
 
1309
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
 
1310
 
 
1311
    def test_for_matching_host(self):
 
1312
        conf = config.AuthenticationConfig(_file=StringIO(
 
1313
                """# Identity on foo.net
 
1314
[sourceforge]
 
1315
scheme=bzr
 
1316
host=bzr.sf.net
 
1317
user=joe
 
1318
password=joepass
 
1319
[sourceforge domain]
 
1320
scheme=bzr
 
1321
host=.bzr.sf.net
 
1322
user=georges
 
1323
password=bendover
 
1324
"""))
 
1325
        # matching domain
 
1326
        self._got_user_passwd('georges', 'bendover',
 
1327
                              conf, 'bzr', 'foo.bzr.sf.net')
 
1328
        # phishing attempt
 
1329
        self._got_user_passwd(None, None,
 
1330
                              conf, 'bzr', 'bbzr.sf.net')
 
1331
 
 
1332
    def test_for_matching_host_None(self):
 
1333
        conf = config.AuthenticationConfig(_file=StringIO(
 
1334
                """# Identity on foo.net
 
1335
[catchup bzr]
 
1336
scheme=bzr
 
1337
user=joe
 
1338
password=joepass
 
1339
[DEFAULT]
 
1340
user=georges
 
1341
password=bendover
 
1342
"""))
 
1343
        # match no host
 
1344
        self._got_user_passwd('joe', 'joepass',
 
1345
                              conf, 'bzr', 'quux.net')
 
1346
        # no host but different scheme
 
1347
        self._got_user_passwd('georges', 'bendover',
 
1348
                              conf, 'ftp', 'quux.net')
 
1349
 
 
1350
    def test_credentials_for_path(self):
 
1351
        conf = config.AuthenticationConfig(_file=StringIO(
 
1352
                """
 
1353
[http dir1]
 
1354
scheme=http
 
1355
host=bar.org
 
1356
path=/dir1
 
1357
user=jim
 
1358
password=jimpass
 
1359
[http dir2]
 
1360
scheme=http
 
1361
host=bar.org
 
1362
path=/dir2
 
1363
user=georges
 
1364
password=bendover
 
1365
"""))
 
1366
        # no path no dice
 
1367
        self._got_user_passwd(None, None,
 
1368
                              conf, 'http', host='bar.org', path='/dir3')
 
1369
        # matching path
 
1370
        self._got_user_passwd('georges', 'bendover',
 
1371
                              conf, 'http', host='bar.org', path='/dir2')
 
1372
        # matching subdir
 
1373
        self._got_user_passwd('jim', 'jimpass',
 
1374
                              conf, 'http', host='bar.org',path='/dir1/subdir')
 
1375
 
 
1376
    def test_credentials_for_user(self):
 
1377
        conf = config.AuthenticationConfig(_file=StringIO(
 
1378
                """
 
1379
[with user]
 
1380
scheme=http
 
1381
host=bar.org
 
1382
user=jim
 
1383
password=jimpass
 
1384
"""))
 
1385
        # Get user
 
1386
        self._got_user_passwd('jim', 'jimpass',
 
1387
                              conf, 'http', 'bar.org')
 
1388
        # Get same user
 
1389
        self._got_user_passwd('jim', 'jimpass',
 
1390
                              conf, 'http', 'bar.org', user='jim')
 
1391
        # Don't get a different user if one is specified
 
1392
        self._got_user_passwd(None, None,
 
1393
                              conf, 'http', 'bar.org', user='georges')
 
1394
 
 
1395
    def test_credentials_for_user_without_password(self):
 
1396
        conf = config.AuthenticationConfig(_file=StringIO(
 
1397
                """
 
1398
[without password]
 
1399
scheme=http
 
1400
host=bar.org
 
1401
user=jim
 
1402
"""))
 
1403
        # Get user but no password
 
1404
        self._got_user_passwd('jim', None,
 
1405
                              conf, 'http', 'bar.org')
 
1406
 
 
1407
    def test_verify_certificates(self):
 
1408
        conf = config.AuthenticationConfig(_file=StringIO(
 
1409
                """
 
1410
[self-signed]
 
1411
scheme=https
 
1412
host=bar.org
 
1413
user=jim
 
1414
password=jimpass
 
1415
verify_certificates=False
 
1416
[normal]
 
1417
scheme=https
 
1418
host=foo.net
 
1419
user=georges
 
1420
password=bendover
 
1421
"""))
 
1422
        credentials = conf.get_credentials('https', 'bar.org')
 
1423
        self.assertEquals(False, credentials.get('verify_certificates'))
 
1424
        credentials = conf.get_credentials('https', 'foo.net')
 
1425
        self.assertEquals(True, credentials.get('verify_certificates'))
 
1426
 
 
1427
 
 
1428
class TestAuthenticationStorage(tests.TestCaseInTempDir):
 
1429
 
 
1430
    def test_set_credentials(self):
 
1431
        conf = config.AuthenticationConfig()
 
1432
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
 
1433
        99, path='/foo', verify_certificates=False, realm='realm')
 
1434
        credentials = conf.get_credentials(host='host', scheme='scheme',
 
1435
                                           port=99, path='/foo',
 
1436
                                           realm='realm')
 
1437
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
 
1438
                       'verify_certificates': False, 'scheme': 'scheme', 
 
1439
                       'host': 'host', 'port': 99, 'path': '/foo', 
 
1440
                       'realm': 'realm'}
 
1441
        self.assertEqual(CREDENTIALS, credentials)
 
1442
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
 
1443
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
 
1444
        self.assertEqual(CREDENTIALS, credentials_from_disk)
 
1445
 
 
1446
    def test_reset_credentials_different_name(self):
 
1447
        conf = config.AuthenticationConfig()
 
1448
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
 
1449
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
 
1450
        self.assertIs(None, conf._get_config().get('name'))
 
1451
        credentials = conf.get_credentials(host='host', scheme='scheme')
 
1452
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
 
1453
                       'password', 'verify_certificates': True, 
 
1454
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
 
1455
                       'path': None, 'realm': None}
 
1456
        self.assertEqual(CREDENTIALS, credentials)
 
1457
 
 
1458
 
 
1459
class TestAuthenticationConfig(tests.TestCase):
 
1460
    """Test AuthenticationConfig behaviour"""
 
1461
 
 
1462
    def _check_default_password_prompt(self, expected_prompt_format, scheme,
 
1463
                                       host=None, port=None, realm=None,
 
1464
                                       path=None):
 
1465
        if host is None:
 
1466
            host = 'bar.org'
 
1467
        user, password = 'jim', 'precious'
 
1468
        expected_prompt = expected_prompt_format % {
 
1469
            'scheme': scheme, 'host': host, 'port': port,
 
1470
            'user': user, 'realm': realm}
 
1471
 
 
1472
        stdout = tests.StringIOWrapper()
 
1473
        stderr = tests.StringIOWrapper()
 
1474
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
 
1475
                                            stdout=stdout, stderr=stderr)
 
1476
        # We use an empty conf so that the user is always prompted
 
1477
        conf = config.AuthenticationConfig()
 
1478
        self.assertEquals(password,
 
1479
                          conf.get_password(scheme, host, user, port=port,
 
1480
                                            realm=realm, path=path))
 
1481
        self.assertEquals(expected_prompt, stderr.getvalue())
 
1482
        self.assertEquals('', stdout.getvalue())
 
1483
 
 
1484
    def _check_default_username_prompt(self, expected_prompt_format, scheme,
 
1485
                                       host=None, port=None, realm=None,
 
1486
                                       path=None):
 
1487
        if host is None:
 
1488
            host = 'bar.org'
 
1489
        username = 'jim'
 
1490
        expected_prompt = expected_prompt_format % {
 
1491
            'scheme': scheme, 'host': host, 'port': port,
 
1492
            'realm': realm}
 
1493
        stdout = tests.StringIOWrapper()
 
1494
        stderr = tests.StringIOWrapper()
 
1495
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
 
1496
                                            stdout=stdout, stderr=stderr)
 
1497
        # We use an empty conf so that the user is always prompted
 
1498
        conf = config.AuthenticationConfig()
 
1499
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
 
1500
                          realm=realm, path=path, ask=True))
 
1501
        self.assertEquals(expected_prompt, stderr.getvalue())
 
1502
        self.assertEquals('', stdout.getvalue())
 
1503
 
 
1504
    def test_username_defaults_prompts(self):
 
1505
        # HTTP prompts can't be tested here, see test_http.py
 
1506
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
 
1507
        self._check_default_username_prompt(
 
1508
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
 
1509
        self._check_default_username_prompt(
 
1510
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
 
1511
 
 
1512
    def test_username_default_no_prompt(self):
 
1513
        conf = config.AuthenticationConfig()
 
1514
        self.assertEquals(None,
 
1515
            conf.get_user('ftp', 'example.com'))
 
1516
        self.assertEquals("explicitdefault",
 
1517
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
 
1518
 
 
1519
    def test_password_default_prompts(self):
 
1520
        # HTTP prompts can't be tested here, see test_http.py
 
1521
        self._check_default_password_prompt(
 
1522
            'FTP %(user)s@%(host)s password: ', 'ftp')
 
1523
        self._check_default_password_prompt(
 
1524
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
 
1525
        self._check_default_password_prompt(
 
1526
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
 
1527
        # SMTP port handling is a bit special (it's handled if embedded in the
 
1528
        # host too)
 
1529
        # FIXME: should we: forbid that, extend it to other schemes, leave
 
1530
        # things as they are that's fine thank you ?
 
1531
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
 
1532
                                            'smtp')
 
1533
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
 
1534
                                            'smtp', host='bar.org:10025')
 
1535
        self._check_default_password_prompt(
 
1536
            'SMTP %(user)s@%(host)s:%(port)d password: ',
 
1537
            'smtp', port=10025)
 
1538
 
 
1539
    def test_ssh_password_emits_warning(self):
 
1540
        conf = config.AuthenticationConfig(_file=StringIO(
 
1541
                """
 
1542
[ssh with password]
 
1543
scheme=ssh
 
1544
host=bar.org
 
1545
user=jim
 
1546
password=jimpass
 
1547
"""))
 
1548
        entered_password = 'typed-by-hand'
 
1549
        stdout = tests.StringIOWrapper()
 
1550
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
 
1551
                                            stdout=stdout)
 
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
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
 
1572
                                            stdout=stdout)
 
1573
 
 
1574
        # Since the password defined in the authentication config is ignored,
 
1575
        # the user is prompted
 
1576
        self.assertEquals(entered_password,
 
1577
                          conf.get_password('ssh', 'bar.org', user='jim'))
 
1578
        # No warning shoud be emitted since there is no password. We are only
 
1579
        # providing "user".
 
1580
        self.assertNotContainsRe(
 
1581
            self._get_log(keep_log_file=True),
 
1582
            'password ignored in section \[ssh with password\]')
 
1583
 
 
1584
    def test_uses_fallback_stores(self):
 
1585
        self._old_cs_registry = config.credential_store_registry
 
1586
        def restore():
 
1587
            config.credential_store_registry = self._old_cs_registry
 
1588
        self.addCleanup(restore)
 
1589
        config.credential_store_registry = config.CredentialStoreRegistry()
 
1590
        store = StubCredentialStore()
 
1591
        store.add_credentials("http", "example.com", "joe", "secret")
 
1592
        config.credential_store_registry.register("stub", store, fallback=True)
 
1593
        conf = config.AuthenticationConfig(_file=StringIO())
 
1594
        creds = conf.get_credentials("http", "example.com")
 
1595
        self.assertEquals("joe", creds["user"])
 
1596
        self.assertEquals("secret", creds["password"])
 
1597
 
 
1598
 
 
1599
class StubCredentialStore(config.CredentialStore):
 
1600
 
 
1601
    def __init__(self):
 
1602
        self._username = {}
 
1603
        self._password = {}
 
1604
 
 
1605
    def add_credentials(self, scheme, host, user, password=None):
 
1606
        self._username[(scheme, host)] = user
 
1607
        self._password[(scheme, host)] = password
 
1608
 
 
1609
    def get_credentials(self, scheme, host, port=None, user=None,
 
1610
        path=None, realm=None):
 
1611
        key = (scheme, host)
 
1612
        if not key in self._username:
 
1613
            return None
 
1614
        return { "scheme": scheme, "host": host, "port": port,
 
1615
                "user": self._username[key], "password": self._password[key]}
 
1616
 
 
1617
 
 
1618
class CountingCredentialStore(config.CredentialStore):
 
1619
 
 
1620
    def __init__(self):
 
1621
        self._calls = 0
 
1622
 
 
1623
    def get_credentials(self, scheme, host, port=None, user=None,
 
1624
        path=None, realm=None):
 
1625
        self._calls += 1
 
1626
        return None
 
1627
 
 
1628
 
 
1629
class TestCredentialStoreRegistry(tests.TestCase):
 
1630
 
 
1631
    def _get_cs_registry(self):
 
1632
        return config.credential_store_registry
 
1633
 
 
1634
    def test_default_credential_store(self):
 
1635
        r = self._get_cs_registry()
 
1636
        default = r.get_credential_store(None)
 
1637
        self.assertIsInstance(default, config.PlainTextCredentialStore)
 
1638
 
 
1639
    def test_unknown_credential_store(self):
 
1640
        r = self._get_cs_registry()
 
1641
        # It's hard to imagine someone creating a credential store named
 
1642
        # 'unknown' so we use that as an never registered key.
 
1643
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
 
1644
 
 
1645
    def test_fallback_none_registered(self):
 
1646
        r = config.CredentialStoreRegistry()
 
1647
        self.assertEquals(None,
 
1648
                          r.get_fallback_credentials("http", "example.com"))
 
1649
 
 
1650
    def test_register(self):
 
1651
        r = config.CredentialStoreRegistry()
 
1652
        r.register("stub", StubCredentialStore(), fallback=False)
 
1653
        r.register("another", StubCredentialStore(), fallback=True)
 
1654
        self.assertEquals(["another", "stub"], r.keys())
 
1655
 
 
1656
    def test_register_lazy(self):
 
1657
        r = config.CredentialStoreRegistry()
 
1658
        r.register_lazy("stub", "bzrlib.tests.test_config",
 
1659
                        "StubCredentialStore", fallback=False)
 
1660
        self.assertEquals(["stub"], r.keys())
 
1661
        self.assertIsInstance(r.get_credential_store("stub"),
 
1662
                              StubCredentialStore)
 
1663
 
 
1664
    def test_is_fallback(self):
 
1665
        r = config.CredentialStoreRegistry()
 
1666
        r.register("stub1", None, fallback=False)
 
1667
        r.register("stub2", None, fallback=True)
 
1668
        self.assertEquals(False, r.is_fallback("stub1"))
 
1669
        self.assertEquals(True, r.is_fallback("stub2"))
 
1670
 
 
1671
    def test_no_fallback(self):
 
1672
        r = config.CredentialStoreRegistry()
 
1673
        store = CountingCredentialStore()
 
1674
        r.register("count", store, fallback=False)
 
1675
        self.assertEquals(None,
 
1676
                          r.get_fallback_credentials("http", "example.com"))
 
1677
        self.assertEquals(0, store._calls)
 
1678
 
 
1679
    def test_fallback_credentials(self):
 
1680
        r = config.CredentialStoreRegistry()
 
1681
        store = StubCredentialStore()
 
1682
        store.add_credentials("http", "example.com",
 
1683
                              "somebody", "geheim")
 
1684
        r.register("stub", store, fallback=True)
 
1685
        creds = r.get_fallback_credentials("http", "example.com")
 
1686
        self.assertEquals("somebody", creds["user"])
 
1687
        self.assertEquals("geheim", creds["password"])
 
1688
 
 
1689
    def test_fallback_first_wins(self):
 
1690
        r = config.CredentialStoreRegistry()
 
1691
        stub1 = StubCredentialStore()
 
1692
        stub1.add_credentials("http", "example.com",
 
1693
                              "somebody", "stub1")
 
1694
        r.register("stub1", stub1, fallback=True)
 
1695
        stub2 = StubCredentialStore()
 
1696
        stub2.add_credentials("http", "example.com",
 
1697
                              "somebody", "stub2")
 
1698
        r.register("stub2", stub1, fallback=True)
 
1699
        creds = r.get_fallback_credentials("http", "example.com")
 
1700
        self.assertEquals("somebody", creds["user"])
 
1701
        self.assertEquals("stub1", creds["password"])
 
1702
 
 
1703
 
 
1704
class TestPlainTextCredentialStore(tests.TestCase):
 
1705
 
 
1706
    def test_decode_password(self):
 
1707
        r = config.credential_store_registry
 
1708
        plain_text = r.get_credential_store()
 
1709
        decoded = plain_text.decode_password(dict(password='secret'))
 
1710
        self.assertEquals('secret', decoded)
 
1711
 
 
1712
 
 
1713
# FIXME: Once we have a way to declare authentication to all test servers, we
 
1714
# can implement generic tests.
 
1715
# test_user_password_in_url
 
1716
# test_user_in_url_password_from_config
 
1717
# test_user_in_url_password_prompted
 
1718
# test_user_in_config
 
1719
# test_user_getpass.getuser
 
1720
# test_user_prompted ?
 
1721
class TestAuthenticationRing(tests.TestCaseWithTransport):
 
1722
    pass