~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-01-02 08:23:44 UTC
  • mfrom: (3140.1.9 find-branches)
  • Revision ID: pqm@pqm.ubuntu.com-20080102082344-qret383z2bdk1ud4
Optimize find_branches for standalone repositories (abentley)

Show diffs side-by-side

added added

removed removed

Lines of Context:
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,
 
35
    trace,
31
36
    )
32
 
from bzrlib.branch import Branch
33
 
from bzrlib.bzrdir import BzrDir
34
 
from bzrlib.tests import TestCase, TestCaseInTempDir, TestCaseWithTransport
 
37
from bzrlib.util.configobj import configobj
35
38
 
36
39
 
37
40
sample_long_alias="log -r-15..-1 --line"
177
180
 
178
181
class InstrumentedConfig(config.Config):
179
182
    """An instrumented config that supplies stubs for template methods."""
180
 
    
 
183
 
181
184
    def __init__(self):
182
185
        super(InstrumentedConfig, self).__init__()
183
186
        self._calls = []
199
202
active = True
200
203
nonactive = False
201
204
"""
202
 
class TestConfigObj(TestCase):
 
205
 
 
206
 
 
207
class TestConfigObj(tests.TestCase):
203
208
    def test_get_bool(self):
204
 
        from bzrlib.config import ConfigObj
205
 
        co = ConfigObj(StringIO(bool_config))
 
209
        co = config.ConfigObj(StringIO(bool_config))
206
210
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
207
211
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
208
212
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
209
213
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
210
214
 
211
215
 
212
 
class TestConfig(TestCase):
 
216
erroneous_config = """[section] # line 1
 
217
good=good # line 2
 
218
[section] # line 3
 
219
whocares=notme # line 4
 
220
"""
 
221
 
 
222
 
 
223
class TestConfigObjErrors(tests.TestCase):
 
224
 
 
225
    def test_duplicate_section_name_error_line(self):
 
226
        try:
 
227
            co = configobj.ConfigObj(StringIO(erroneous_config),
 
228
                                     raise_errors=True)
 
229
        except config.configobj.DuplicateError, e:
 
230
            self.assertEqual(3, e.line_number)
 
231
        else:
 
232
            self.fail('Error in config file not detected')
 
233
 
 
234
 
 
235
class TestConfig(tests.TestCase):
213
236
 
214
237
    def test_constructs(self):
215
238
        config.Config()
216
 
 
 
239
 
217
240
    def test_no_default_editor(self):
218
241
        self.assertRaises(NotImplementedError, config.Config().get_editor)
219
242
 
265
288
        self.assertEqual('long', my_config.log_format())
266
289
 
267
290
 
268
 
class TestConfigPath(TestCase):
 
291
class TestConfigPath(tests.TestCase):
269
292
 
270
293
    def setUp(self):
271
294
        super(TestConfigPath, self).setUp()
273
296
        if sys.platform == 'win32':
274
297
            os.environ['BZR_HOME'] = \
275
298
                r'C:\Documents and Settings\bogus\Application Data'
 
299
            self.bzr_home = \
 
300
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
 
301
        else:
 
302
            self.bzr_home = '/home/bogus/.bazaar'
276
303
 
277
304
    def test_config_dir(self):
278
 
        if sys.platform == 'win32':
279
 
            self.assertEqual(config.config_dir(), 
280
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0')
281
 
        else:
282
 
            self.assertEqual(config.config_dir(), '/home/bogus/.bazaar')
 
305
        self.assertEqual(config.config_dir(), self.bzr_home)
283
306
 
284
307
    def test_config_filename(self):
285
 
        if sys.platform == 'win32':
286
 
            self.assertEqual(config.config_filename(), 
287
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/bazaar.conf')
288
 
        else:
289
 
            self.assertEqual(config.config_filename(),
290
 
                             '/home/bogus/.bazaar/bazaar.conf')
 
308
        self.assertEqual(config.config_filename(),
 
309
                         self.bzr_home + '/bazaar.conf')
291
310
 
292
311
    def test_branches_config_filename(self):
293
 
        if sys.platform == 'win32':
294
 
            self.assertEqual(config.branches_config_filename(), 
295
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/branches.conf')
296
 
        else:
297
 
            self.assertEqual(config.branches_config_filename(),
298
 
                             '/home/bogus/.bazaar/branches.conf')
 
312
        self.assertEqual(config.branches_config_filename(),
 
313
                         self.bzr_home + '/branches.conf')
299
314
 
300
315
    def test_locations_config_filename(self):
301
 
        if sys.platform == 'win32':
302
 
            self.assertEqual(config.locations_config_filename(), 
303
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/locations.conf')
304
 
        else:
305
 
            self.assertEqual(config.locations_config_filename(),
306
 
                             '/home/bogus/.bazaar/locations.conf')
307
 
 
308
 
class TestIniConfig(TestCase):
 
316
        self.assertEqual(config.locations_config_filename(),
 
317
                         self.bzr_home + '/locations.conf')
 
318
 
 
319
    def test_authentication_config_filename(self):
 
320
        self.assertEqual(config.authentication_config_filename(),
 
321
                         self.bzr_home + '/authentication.conf')
 
322
 
 
323
 
 
324
class TestIniConfig(tests.TestCase):
309
325
 
310
326
    def test_contructs(self):
311
327
        my_config = config.IniBasedConfig("nothing")
315
331
        my_config = config.IniBasedConfig(None)
316
332
        self.failUnless(
317
333
            isinstance(my_config._get_parser(file=config_file),
318
 
                        ConfigObj))
 
334
                        configobj.ConfigObj))
319
335
 
320
336
    def test_cached(self):
321
337
        config_file = StringIO(sample_config_text.encode('utf-8'))
324
340
        self.failUnless(my_config._get_parser() is parser)
325
341
 
326
342
 
327
 
class TestGetConfig(TestCase):
 
343
class TestGetConfig(tests.TestCase):
328
344
 
329
345
    def test_constructs(self):
330
346
        my_config = config.GlobalConfig()
331
347
 
332
348
    def test_calls_read_filenames(self):
333
 
        # replace the class that is constructured, to check its parameters
 
349
        # replace the class that is constructed, to check its parameters
334
350
        oldparserclass = config.ConfigObj
335
351
        config.ConfigObj = InstrumentedConfigObj
336
352
        my_config = config.GlobalConfig()
343
359
                                          'utf-8')])
344
360
 
345
361
 
346
 
class TestBranchConfig(TestCaseWithTransport):
 
362
class TestBranchConfig(tests.TestCaseWithTransport):
347
363
 
348
364
    def test_constructs(self):
349
365
        branch = FakeBranch()
359
375
 
360
376
    def test_get_config(self):
361
377
        """The Branch.get_config method works properly"""
362
 
        b = BzrDir.create_standalone_workingtree('.').branch
 
378
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
363
379
        my_config = b.get_config()
364
380
        self.assertIs(my_config.get_user_option('wacky'), None)
365
381
        my_config.set_user_option('wacky', 'unlikely')
366
382
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
367
383
 
368
384
        # Ensure we get the same thing if we start again
369
 
        b2 = Branch.open('.')
 
385
        b2 = branch.Branch.open('.')
370
386
        my_config2 = b2.get_config()
371
387
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
372
388
 
407
423
        local_path = osutils.getcwd().encode('utf8')
408
424
        # Surprisingly ConfigObj doesn't create a trailing newline
409
425
        self.check_file_contents(locations,
410
 
            '[%s/branch]\npush_location = http://foobar\npush_location:policy = norecurse' % (local_path,))
 
426
                                 '[%s/branch]\n'
 
427
                                 'push_location = http://foobar\n'
 
428
                                 'push_location:policy = norecurse'
 
429
                                 % (local_path,))
411
430
 
412
431
    def test_autonick_urlencoded(self):
413
432
        b = self.make_branch('!repo')
414
433
        self.assertEqual('!repo', b.get_config().get_nickname())
415
434
 
416
 
 
417
 
class TestGlobalConfigItems(TestCase):
 
435
    def test_warn_if_masked(self):
 
436
        _warning = trace.warning
 
437
        warnings = []
 
438
        def warning(*args):
 
439
            warnings.append(args[0] % args[1:])
 
440
 
 
441
        def set_option(store, warn_masked=True):
 
442
            warnings[:] = []
 
443
            conf.set_user_option('example_option', repr(store), store=store,
 
444
                                 warn_masked=warn_masked)
 
445
        def assertWarning(warning):
 
446
            if warning is None:
 
447
                self.assertEqual(0, len(warnings))
 
448
            else:
 
449
                self.assertEqual(1, len(warnings))
 
450
                self.assertEqual(warning, warnings[0])
 
451
        trace.warning = warning
 
452
        try:
 
453
            branch = self.make_branch('.')
 
454
            conf = branch.get_config()
 
455
            set_option(config.STORE_GLOBAL)
 
456
            assertWarning(None)
 
457
            set_option(config.STORE_BRANCH)
 
458
            assertWarning(None)
 
459
            set_option(config.STORE_GLOBAL)
 
460
            assertWarning('Value "4" is masked by "3" from branch.conf')
 
461
            set_option(config.STORE_GLOBAL, warn_masked=False)
 
462
            assertWarning(None)
 
463
            set_option(config.STORE_LOCATION)
 
464
            assertWarning(None)
 
465
            set_option(config.STORE_BRANCH)
 
466
            assertWarning('Value "3" is masked by "0" from locations.conf')
 
467
            set_option(config.STORE_BRANCH, warn_masked=False)
 
468
            assertWarning(None)
 
469
        finally:
 
470
            trace.warning = _warning
 
471
 
 
472
 
 
473
class TestGlobalConfigItems(tests.TestCase):
418
474
 
419
475
    def test_user_id(self):
420
476
        config_file = StringIO(sample_config_text.encode('utf-8'))
494
550
        my_config = self._get_sample_config()
495
551
        self.assertEqual("something",
496
552
                         my_config.get_user_option('user_global_option'))
497
 
        
 
553
 
498
554
    def test_post_commit_default(self):
499
555
        my_config = self._get_sample_config()
500
556
        self.assertEqual(None, my_config.post_commit())
516
572
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
517
573
 
518
574
 
519
 
class TestLocationConfig(TestCaseInTempDir):
 
575
class TestLocationConfig(tests.TestCaseInTempDir):
520
576
 
521
577
    def test_constructs(self):
522
578
        my_config = config.LocationConfig('http://example.com')
526
582
        # This is testing the correct file names are provided.
527
583
        # TODO: consolidate with the test for GlobalConfigs filename checks.
528
584
        #
529
 
        # replace the class that is constructured, to check its parameters
 
585
        # replace the class that is constructed, to check its parameters
530
586
        oldparserclass = config.ConfigObj
531
587
        config.ConfigObj = InstrumentedConfigObj
532
588
        try:
560
616
    def test__get_matching_sections_no_match(self):
561
617
        self.get_branch_config('/')
562
618
        self.assertEqual([], self.my_location_config._get_matching_sections())
563
 
        
 
619
 
564
620
    def test__get_matching_sections_exact(self):
565
621
        self.get_branch_config('http://www.example.com')
566
622
        self.assertEqual([('http://www.example.com', '')],
567
623
                         self.my_location_config._get_matching_sections())
568
 
   
 
624
 
569
625
    def test__get_matching_sections_suffix_does_not(self):
570
626
        self.get_branch_config('http://www.example.com-com')
571
627
        self.assertEqual([], self.my_location_config._get_matching_sections())
583
639
    def test__get_matching_sections_ignoreparent_subdir(self):
584
640
        self.get_branch_config(
585
641
            'http://www.example.com/ignoreparent/childbranch')
586
 
        self.assertEqual([('http://www.example.com/ignoreparent', 'childbranch')],
 
642
        self.assertEqual([('http://www.example.com/ignoreparent',
 
643
                           'childbranch')],
587
644
                         self.my_location_config._get_matching_sections())
588
645
 
589
646
    def test__get_matching_sections_subdir_trailing_slash(self):
669
726
        self.get_branch_config('/a/c')
670
727
        self.assertEqual(config.CHECK_NEVER,
671
728
                         self.my_config.signature_checking())
672
 
        
 
729
 
673
730
    def test_signatures_when_available(self):
674
731
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
675
732
        self.assertEqual(config.CHECK_IF_POSSIBLE,
676
733
                         self.my_config.signature_checking())
677
 
        
 
734
 
678
735
    def test_signatures_always(self):
679
736
        self.get_branch_config('/b')
680
737
        self.assertEqual(config.CHECK_ALWAYS,
681
738
                         self.my_config.signature_checking())
682
 
        
 
739
 
683
740
    def test_gpg_signing_command(self):
684
741
        self.get_branch_config('/b')
685
742
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
776
833
            self.my_location_config._get_option_policy(
777
834
            'http://www.example.com/norecurse', 'normal_option'),
778
835
            config.POLICY_NORECURSE)
779
 
        
780
836
 
781
837
    def test_post_commit_default(self):
782
838
        self.get_branch_config('/a/c')
840
896
        self.assertIs(self.my_config.get_user_option('foo'), None)
841
897
        self.my_config.set_user_option('foo', 'bar')
842
898
        self.assertEqual(
843
 
            self.my_config.branch.control_files.files['branch.conf'], 
 
899
            self.my_config.branch.control_files.files['branch.conf'],
844
900
            'foo = bar')
845
901
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
846
902
        self.my_config.set_user_option('foo', 'baz',
848
904
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
849
905
        self.my_config.set_user_option('foo', 'qux')
850
906
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
851
 
        
 
907
 
 
908
    def test_get_bzr_remote_path(self):
 
909
        my_config = config.LocationConfig('/a/c')
 
910
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
 
911
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
 
912
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
 
913
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
914
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
 
915
 
852
916
 
853
917
precedence_global = 'option = global'
854
918
precedence_branch = 'option = branch'
861
925
"""
862
926
 
863
927
 
864
 
class TestBranchConfigItems(TestCaseInTempDir):
 
928
class TestBranchConfigItems(tests.TestCaseInTempDir):
865
929
 
866
 
    def get_branch_config(self, global_config=None, location=None, 
 
930
    def get_branch_config(self, global_config=None, location=None,
867
931
                          location_config=None, branch_data_config=None):
868
932
        my_config = config.BranchConfig(FakeBranch(location))
869
933
        if global_config is not None:
884
948
        self.assertEqual("Robert Collins <robertc@example.net>",
885
949
                         my_config.username())
886
950
        branch.control_files.email = "John"
887
 
        my_config.set_user_option('email', 
 
951
        my_config.set_user_option('email',
888
952
                                  "Robert Collins <robertc@example.org>")
889
953
        self.assertEqual("John", my_config.username())
890
954
        branch.control_files.email = None
905
969
        my_config = config.BranchConfig(branch)
906
970
        self.assertEqual("Robert Collins <robertc@example.org>",
907
971
                         my_config.username())
908
 
    
 
972
 
909
973
    def test_signatures_forced(self):
910
974
        my_config = self.get_branch_config(
911
975
            global_config=sample_always_signatures)
955
1019
    def test_config_precedence(self):
956
1020
        my_config = self.get_branch_config(global_config=precedence_global)
957
1021
        self.assertEqual(my_config.get_user_option('option'), 'global')
958
 
        my_config = self.get_branch_config(global_config=precedence_global, 
 
1022
        my_config = self.get_branch_config(global_config=precedence_global,
959
1023
                                      branch_data_config=precedence_branch)
960
1024
        self.assertEqual(my_config.get_user_option('option'), 'branch')
961
 
        my_config = self.get_branch_config(global_config=precedence_global, 
 
1025
        my_config = self.get_branch_config(global_config=precedence_global,
962
1026
                                      branch_data_config=precedence_branch,
963
1027
                                      location_config=precedence_location)
964
1028
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
965
 
        my_config = self.get_branch_config(global_config=precedence_global, 
 
1029
        my_config = self.get_branch_config(global_config=precedence_global,
966
1030
                                      branch_data_config=precedence_branch,
967
1031
                                      location_config=precedence_location,
968
1032
                                      location='http://example.com/specific')
969
1033
        self.assertEqual(my_config.get_user_option('option'), 'exact')
970
1034
 
971
 
 
972
 
class TestMailAddressExtraction(TestCase):
 
1035
    def test_get_mail_client(self):
 
1036
        config = self.get_branch_config()
 
1037
        client = config.get_mail_client()
 
1038
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1039
 
 
1040
        # Specific clients
 
1041
        config.set_user_option('mail_client', 'evolution')
 
1042
        client = config.get_mail_client()
 
1043
        self.assertIsInstance(client, mail_client.Evolution)
 
1044
 
 
1045
        config.set_user_option('mail_client', 'kmail')
 
1046
        client = config.get_mail_client()
 
1047
        self.assertIsInstance(client, mail_client.KMail)
 
1048
 
 
1049
        config.set_user_option('mail_client', 'mutt')
 
1050
        client = config.get_mail_client()
 
1051
        self.assertIsInstance(client, mail_client.Mutt)
 
1052
 
 
1053
        config.set_user_option('mail_client', 'thunderbird')
 
1054
        client = config.get_mail_client()
 
1055
        self.assertIsInstance(client, mail_client.Thunderbird)
 
1056
 
 
1057
        # Generic options
 
1058
        config.set_user_option('mail_client', 'default')
 
1059
        client = config.get_mail_client()
 
1060
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1061
 
 
1062
        config.set_user_option('mail_client', 'editor')
 
1063
        client = config.get_mail_client()
 
1064
        self.assertIsInstance(client, mail_client.Editor)
 
1065
 
 
1066
        config.set_user_option('mail_client', 'mapi')
 
1067
        client = config.get_mail_client()
 
1068
        self.assertIsInstance(client, mail_client.MAPIClient)
 
1069
 
 
1070
        config.set_user_option('mail_client', 'xdg-email')
 
1071
        client = config.get_mail_client()
 
1072
        self.assertIsInstance(client, mail_client.XDGEmail)
 
1073
 
 
1074
        config.set_user_option('mail_client', 'firebird')
 
1075
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
 
1076
 
 
1077
 
 
1078
class TestMailAddressExtraction(tests.TestCase):
973
1079
 
974
1080
    def test_extract_email_address(self):
975
1081
        self.assertEqual('jane@test.com',
976
1082
                         config.extract_email_address('Jane <jane@test.com>'))
977
1083
        self.assertRaises(errors.NoEmailInUsername,
978
1084
                          config.extract_email_address, 'Jane Tester')
 
1085
 
 
1086
    def test_parse_username(self):
 
1087
        self.assertEqual(('', 'jdoe@example.com'),
 
1088
                         config.parse_username('jdoe@example.com'))
 
1089
        self.assertEqual(('', 'jdoe@example.com'),
 
1090
                         config.parse_username('<jdoe@example.com>'))
 
1091
        self.assertEqual(('John Doe', 'jdoe@example.com'),
 
1092
                         config.parse_username('John Doe <jdoe@example.com>'))
 
1093
        self.assertEqual(('John Doe', ''),
 
1094
                         config.parse_username('John Doe'))
 
1095
        self.assertEqual(('John Doe', 'jdoe@example.com'),
 
1096
                         config.parse_username('John Doe jdoe@example.com'))
 
1097
 
 
1098
class TestTreeConfig(tests.TestCaseWithTransport):
 
1099
 
 
1100
    def test_get_value(self):
 
1101
        """Test that retreiving a value from a section is possible"""
 
1102
        branch = self.make_branch('.')
 
1103
        tree_config = config.TreeConfig(branch)
 
1104
        tree_config.set_option('value', 'key', 'SECTION')
 
1105
        tree_config.set_option('value2', 'key2')
 
1106
        tree_config.set_option('value3-top', 'key3')
 
1107
        tree_config.set_option('value3-section', 'key3', 'SECTION')
 
1108
        value = tree_config.get_option('key', 'SECTION')
 
1109
        self.assertEqual(value, 'value')
 
1110
        value = tree_config.get_option('key2')
 
1111
        self.assertEqual(value, 'value2')
 
1112
        self.assertEqual(tree_config.get_option('non-existant'), None)
 
1113
        value = tree_config.get_option('non-existant', 'SECTION')
 
1114
        self.assertEqual(value, None)
 
1115
        value = tree_config.get_option('non-existant', default='default')
 
1116
        self.assertEqual(value, 'default')
 
1117
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
 
1118
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
 
1119
        self.assertEqual(value, 'default')
 
1120
        value = tree_config.get_option('key3')
 
1121
        self.assertEqual(value, 'value3-top')
 
1122
        value = tree_config.get_option('key3', 'SECTION')
 
1123
        self.assertEqual(value, 'value3-section')
 
1124
 
 
1125
 
 
1126
class TestAuthenticationConfigFile(tests.TestCase):
 
1127
    """Test the authentication.conf file matching"""
 
1128
 
 
1129
    def _got_user_passwd(self, expected_user, expected_password,
 
1130
                         config, *args, **kwargs):
 
1131
        credentials = config.get_credentials(*args, **kwargs)
 
1132
        if credentials is None:
 
1133
            user = None
 
1134
            password = None
 
1135
        else:
 
1136
            user = credentials['user']
 
1137
            password = credentials['password']
 
1138
        self.assertEquals(expected_user, user)
 
1139
        self.assertEquals(expected_password, password)
 
1140
 
 
1141
    def test_empty_config(self):
 
1142
        conf = config.AuthenticationConfig(_file=StringIO())
 
1143
        self.assertEquals({}, conf._get_config())
 
1144
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
 
1145
 
 
1146
    def test_broken_config(self):
 
1147
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
 
1148
        self.assertRaises(errors.ParseConfigError, conf._get_config)
 
1149
 
 
1150
        conf = config.AuthenticationConfig(_file=StringIO(
 
1151
                """[broken]
 
1152
scheme=ftp
 
1153
user=joe
 
1154
verify_certificates=askme # Error: Not a boolean
 
1155
"""))
 
1156
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1157
        conf = config.AuthenticationConfig(_file=StringIO(
 
1158
                """[broken]
 
1159
scheme=ftp
 
1160
user=joe
 
1161
port=port # Error: Not an int
 
1162
"""))
 
1163
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1164
 
 
1165
    def test_credentials_for_scheme_host(self):
 
1166
        conf = config.AuthenticationConfig(_file=StringIO(
 
1167
                """# Identity on foo.net
 
1168
[ftp definition]
 
1169
scheme=ftp
 
1170
host=foo.net
 
1171
user=joe
 
1172
password=secret-pass
 
1173
"""))
 
1174
        # Basic matching
 
1175
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
 
1176
        # different scheme
 
1177
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
 
1178
        # different host
 
1179
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
 
1180
 
 
1181
    def test_credentials_for_host_port(self):
 
1182
        conf = config.AuthenticationConfig(_file=StringIO(
 
1183
                """# Identity on foo.net
 
1184
[ftp definition]
 
1185
scheme=ftp
 
1186
port=10021
 
1187
host=foo.net
 
1188
user=joe
 
1189
password=secret-pass
 
1190
"""))
 
1191
        # No port
 
1192
        self._got_user_passwd('joe', 'secret-pass',
 
1193
                              conf, 'ftp', 'foo.net', port=10021)
 
1194
        # different port
 
1195
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
 
1196
 
 
1197
    def test_for_matching_host(self):
 
1198
        conf = config.AuthenticationConfig(_file=StringIO(
 
1199
                """# Identity on foo.net
 
1200
[sourceforge]
 
1201
scheme=bzr
 
1202
host=bzr.sf.net
 
1203
user=joe
 
1204
password=joepass
 
1205
[sourceforge domain]
 
1206
scheme=bzr
 
1207
host=.bzr.sf.net
 
1208
user=georges
 
1209
password=bendover
 
1210
"""))
 
1211
        # matching domain
 
1212
        self._got_user_passwd('georges', 'bendover',
 
1213
                              conf, 'bzr', 'foo.bzr.sf.net')
 
1214
        # phishing attempt
 
1215
        self._got_user_passwd(None, None,
 
1216
                              conf, 'bzr', 'bbzr.sf.net')
 
1217
 
 
1218
    def test_for_matching_host_None(self):
 
1219
        conf = config.AuthenticationConfig(_file=StringIO(
 
1220
                """# Identity on foo.net
 
1221
[catchup bzr]
 
1222
scheme=bzr
 
1223
user=joe
 
1224
password=joepass
 
1225
[DEFAULT]
 
1226
user=georges
 
1227
password=bendover
 
1228
"""))
 
1229
        # match no host
 
1230
        self._got_user_passwd('joe', 'joepass',
 
1231
                              conf, 'bzr', 'quux.net')
 
1232
        # no host but different scheme
 
1233
        self._got_user_passwd('georges', 'bendover',
 
1234
                              conf, 'ftp', 'quux.net')
 
1235
 
 
1236
    def test_credentials_for_path(self):
 
1237
        conf = config.AuthenticationConfig(_file=StringIO(
 
1238
                """
 
1239
[http dir1]
 
1240
scheme=http
 
1241
host=bar.org
 
1242
path=/dir1
 
1243
user=jim
 
1244
password=jimpass
 
1245
[http dir2]
 
1246
scheme=http
 
1247
host=bar.org
 
1248
path=/dir2
 
1249
user=georges
 
1250
password=bendover
 
1251
"""))
 
1252
        # no path no dice
 
1253
        self._got_user_passwd(None, None,
 
1254
                              conf, 'http', host='bar.org', path='/dir3')
 
1255
        # matching path
 
1256
        self._got_user_passwd('georges', 'bendover',
 
1257
                              conf, 'http', host='bar.org', path='/dir2')
 
1258
        # matching subdir
 
1259
        self._got_user_passwd('jim', 'jimpass',
 
1260
                              conf, 'http', host='bar.org',path='/dir1/subdir')
 
1261
 
 
1262
    def test_credentials_for_user(self):
 
1263
        conf = config.AuthenticationConfig(_file=StringIO(
 
1264
                """
 
1265
[with user]
 
1266
scheme=http
 
1267
host=bar.org
 
1268
user=jim
 
1269
password=jimpass
 
1270
"""))
 
1271
        # Get user
 
1272
        self._got_user_passwd('jim', 'jimpass',
 
1273
                              conf, 'http', 'bar.org')
 
1274
        # Get same user
 
1275
        self._got_user_passwd('jim', 'jimpass',
 
1276
                              conf, 'http', 'bar.org', user='jim')
 
1277
        # Don't get a different user if one is specified
 
1278
        self._got_user_passwd(None, None,
 
1279
                              conf, 'http', 'bar.org', user='georges')
 
1280
 
 
1281
    def test_verify_certificates(self):
 
1282
        conf = config.AuthenticationConfig(_file=StringIO(
 
1283
                """
 
1284
[self-signed]
 
1285
scheme=https
 
1286
host=bar.org
 
1287
user=jim
 
1288
password=jimpass
 
1289
verify_certificates=False
 
1290
[normal]
 
1291
scheme=https
 
1292
host=foo.net
 
1293
user=georges
 
1294
password=bendover
 
1295
"""))
 
1296
        credentials = conf.get_credentials('https', 'bar.org')
 
1297
        self.assertEquals(False, credentials.get('verify_certificates'))
 
1298
        credentials = conf.get_credentials('https', 'foo.net')
 
1299
        self.assertEquals(True, credentials.get('verify_certificates'))
 
1300
 
 
1301
 
 
1302
class TestAuthenticationConfig(tests.TestCase):
 
1303
    """Test AuthenticationConfig behaviour"""
 
1304
 
 
1305
    def _check_default_prompt(self, expected_prompt_format, scheme,
 
1306
                              host=None, port=None, realm=None, path=None):
 
1307
        if host is None:
 
1308
            host = 'bar.org'
 
1309
        user, password = 'jim', 'precious'
 
1310
        expected_prompt = expected_prompt_format % {
 
1311
            'scheme': scheme, 'host': host, 'port': port,
 
1312
            'user': user, 'realm': realm}
 
1313
 
 
1314
        stdout = tests.StringIOWrapper()
 
1315
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
 
1316
                                            stdout=stdout)
 
1317
        # We use an empty conf so that the user is always prompted
 
1318
        conf = config.AuthenticationConfig()
 
1319
        self.assertEquals(password,
 
1320
                          conf.get_password(scheme, host, user, port=port,
 
1321
                                            realm=realm, path=path))
 
1322
        self.assertEquals(stdout.getvalue(), expected_prompt)
 
1323
 
 
1324
    def test_default_prompts(self):
 
1325
        # HTTP prompts can't be tested here, see test_http.py
 
1326
        self._check_default_prompt('FTP %(user)s@%(host)s password: ', 'ftp')
 
1327
        self._check_default_prompt('FTP %(user)s@%(host)s:%(port)d password: ',
 
1328
                                   'ftp', port=10020)
 
1329
 
 
1330
        self._check_default_prompt('SSH %(user)s@%(host)s:%(port)d password: ',
 
1331
                                   'ssh', port=12345)
 
1332
        # SMTP port handling is a bit special (it's handled if embedded in the
 
1333
        # host too)
 
1334
        # FIXME: should we: forbid that, extend it to other schemes, leave
 
1335
        # things as they are that's fine thank you ?
 
1336
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
 
1337
                                   'smtp')
 
1338
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
 
1339
                                   'smtp', host='bar.org:10025')
 
1340
        self._check_default_prompt(
 
1341
            'SMTP %(user)s@%(host)s:%(port)d password: ',
 
1342
            'smtp', port=10025)
 
1343
 
 
1344
 
 
1345
# FIXME: Once we have a way to declare authentication to all test servers, we
 
1346
# can implement generic tests.
 
1347
# test_user_password_in_url
 
1348
# test_user_in_url_password_from_config
 
1349
# test_user_in_url_password_prompted
 
1350
# test_user_in_config
 
1351
# test_user_getpass.getuser
 
1352
# test_user_prompted ?
 
1353
class TestAuthenticationRing(tests.TestCaseWithTransport):
 
1354
    pass