~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Alexander Belchenko
  • Date: 2007-01-30 23:05:35 UTC
  • mto: This revision was merged to the branch mainline in revision 2259.
  • Revision ID: bialix@ukr.net-20070130230535-kx1rd478rtigyc3v
standalone installer: win98 support

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
20
21
from cStringIO import StringIO
21
22
import os
22
23
import sys
23
24
 
24
25
#import bzrlib specific imports here
25
26
from bzrlib import (
26
 
    branch,
27
 
    bzrdir,
28
27
    config,
29
28
    errors,
30
29
    osutils,
31
 
    mail_client,
32
 
    ui,
33
30
    urlutils,
34
 
    tests,
35
 
    trace,
36
31
    )
37
 
from bzrlib.util.configobj import configobj
 
32
from bzrlib.branch import Branch
 
33
from bzrlib.bzrdir import BzrDir
 
34
from bzrlib.tests import TestCase, TestCaseInTempDir, TestCaseWithTransport
38
35
 
39
36
 
40
37
sample_long_alias="log -r-15..-1 --line"
180
177
 
181
178
class InstrumentedConfig(config.Config):
182
179
    """An instrumented config that supplies stubs for template methods."""
183
 
 
 
180
    
184
181
    def __init__(self):
185
182
        super(InstrumentedConfig, self).__init__()
186
183
        self._calls = []
202
199
active = True
203
200
nonactive = False
204
201
"""
205
 
 
206
 
 
207
 
class TestConfigObj(tests.TestCase):
208
 
 
 
202
class TestConfigObj(TestCase):
209
203
    def test_get_bool(self):
210
 
        co = config.ConfigObj(StringIO(bool_config))
 
204
        from bzrlib.config import ConfigObj
 
205
        co = ConfigObj(StringIO(bool_config))
211
206
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
212
207
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
213
208
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
214
209
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
215
210
 
216
 
    def test_hash_sign_in_value(self):
217
 
        """
218
 
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
219
 
        treated as comments when read in again. (#86838)
220
 
        """
221
 
        co = config.ConfigObj()
222
 
        co['test'] = 'foo#bar'
223
 
        lines = co.write()
224
 
        self.assertEqual(lines, ['test = "foo#bar"'])
225
 
        co2 = config.ConfigObj(lines)
226
 
        self.assertEqual(co2['test'], 'foo#bar')
227
 
 
228
 
 
229
 
erroneous_config = """[section] # line 1
230
 
good=good # line 2
231
 
[section] # line 3
232
 
whocares=notme # line 4
233
 
"""
234
 
 
235
 
 
236
 
class TestConfigObjErrors(tests.TestCase):
237
 
 
238
 
    def test_duplicate_section_name_error_line(self):
239
 
        try:
240
 
            co = configobj.ConfigObj(StringIO(erroneous_config),
241
 
                                     raise_errors=True)
242
 
        except config.configobj.DuplicateError, e:
243
 
            self.assertEqual(3, e.line_number)
244
 
        else:
245
 
            self.fail('Error in config file not detected')
246
 
 
247
 
 
248
 
class TestConfig(tests.TestCase):
 
211
 
 
212
class TestConfig(TestCase):
249
213
 
250
214
    def test_constructs(self):
251
215
        config.Config()
252
 
 
 
216
 
253
217
    def test_no_default_editor(self):
254
218
        self.assertRaises(NotImplementedError, config.Config().get_editor)
255
219
 
301
265
        self.assertEqual('long', my_config.log_format())
302
266
 
303
267
 
304
 
class TestConfigPath(tests.TestCase):
 
268
class TestConfigPath(TestCase):
305
269
 
306
270
    def setUp(self):
307
271
        super(TestConfigPath, self).setUp()
 
272
        self.old_home = os.environ.get('HOME', None)
 
273
        self.old_appdata = os.environ.get('APPDATA', None)
308
274
        os.environ['HOME'] = '/home/bogus'
309
 
        if sys.platform == 'win32':
310
 
            os.environ['BZR_HOME'] = \
311
 
                r'C:\Documents and Settings\bogus\Application Data'
312
 
            self.bzr_home = \
313
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
314
 
        else:
315
 
            self.bzr_home = '/home/bogus/.bazaar'
 
275
        os.environ['APPDATA'] = \
 
276
            r'C:\Documents and Settings\bogus\Application Data'
316
277
 
 
278
    def tearDown(self):
 
279
        if self.old_home is None:
 
280
            del os.environ['HOME']
 
281
        else:
 
282
            os.environ['HOME'] = self.old_home
 
283
        if self.old_appdata is None:
 
284
            del os.environ['APPDATA']
 
285
        else:
 
286
            os.environ['APPDATA'] = self.old_appdata
 
287
        super(TestConfigPath, self).tearDown()
 
288
    
317
289
    def test_config_dir(self):
318
 
        self.assertEqual(config.config_dir(), self.bzr_home)
 
290
        if sys.platform == 'win32':
 
291
            self.assertEqual(config.config_dir(), 
 
292
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0')
 
293
        else:
 
294
            self.assertEqual(config.config_dir(), '/home/bogus/.bazaar')
319
295
 
320
296
    def test_config_filename(self):
321
 
        self.assertEqual(config.config_filename(),
322
 
                         self.bzr_home + '/bazaar.conf')
 
297
        if sys.platform == 'win32':
 
298
            self.assertEqual(config.config_filename(), 
 
299
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/bazaar.conf')
 
300
        else:
 
301
            self.assertEqual(config.config_filename(),
 
302
                             '/home/bogus/.bazaar/bazaar.conf')
323
303
 
324
304
    def test_branches_config_filename(self):
325
 
        self.assertEqual(config.branches_config_filename(),
326
 
                         self.bzr_home + '/branches.conf')
 
305
        if sys.platform == 'win32':
 
306
            self.assertEqual(config.branches_config_filename(), 
 
307
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/branches.conf')
 
308
        else:
 
309
            self.assertEqual(config.branches_config_filename(),
 
310
                             '/home/bogus/.bazaar/branches.conf')
327
311
 
328
312
    def test_locations_config_filename(self):
329
 
        self.assertEqual(config.locations_config_filename(),
330
 
                         self.bzr_home + '/locations.conf')
331
 
 
332
 
    def test_authentication_config_filename(self):
333
 
        self.assertEqual(config.authentication_config_filename(),
334
 
                         self.bzr_home + '/authentication.conf')
335
 
 
336
 
 
337
 
class TestIniConfig(tests.TestCase):
 
313
        if sys.platform == 'win32':
 
314
            self.assertEqual(config.locations_config_filename(), 
 
315
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/locations.conf')
 
316
        else:
 
317
            self.assertEqual(config.locations_config_filename(),
 
318
                             '/home/bogus/.bazaar/locations.conf')
 
319
 
 
320
class TestIniConfig(TestCase):
338
321
 
339
322
    def test_contructs(self):
340
323
        my_config = config.IniBasedConfig("nothing")
344
327
        my_config = config.IniBasedConfig(None)
345
328
        self.failUnless(
346
329
            isinstance(my_config._get_parser(file=config_file),
347
 
                        configobj.ConfigObj))
 
330
                        ConfigObj))
348
331
 
349
332
    def test_cached(self):
350
333
        config_file = StringIO(sample_config_text.encode('utf-8'))
353
336
        self.failUnless(my_config._get_parser() is parser)
354
337
 
355
338
 
356
 
class TestGetConfig(tests.TestCase):
 
339
class TestGetConfig(TestCase):
357
340
 
358
341
    def test_constructs(self):
359
342
        my_config = config.GlobalConfig()
360
343
 
361
344
    def test_calls_read_filenames(self):
362
 
        # replace the class that is constructed, to check its parameters
 
345
        # replace the class that is constructured, to check its parameters
363
346
        oldparserclass = config.ConfigObj
364
347
        config.ConfigObj = InstrumentedConfigObj
365
348
        my_config = config.GlobalConfig()
372
355
                                          'utf-8')])
373
356
 
374
357
 
375
 
class TestBranchConfig(tests.TestCaseWithTransport):
 
358
class TestBranchConfig(TestCaseWithTransport):
376
359
 
377
360
    def test_constructs(self):
378
361
        branch = FakeBranch()
388
371
 
389
372
    def test_get_config(self):
390
373
        """The Branch.get_config method works properly"""
391
 
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
 
374
        b = BzrDir.create_standalone_workingtree('.').branch
392
375
        my_config = b.get_config()
393
376
        self.assertIs(my_config.get_user_option('wacky'), None)
394
377
        my_config.set_user_option('wacky', 'unlikely')
395
378
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
396
379
 
397
380
        # Ensure we get the same thing if we start again
398
 
        b2 = branch.Branch.open('.')
 
381
        b2 = Branch.open('.')
399
382
        my_config2 = b2.get_config()
400
383
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
401
384
 
430
413
 
431
414
    def test_config_creates_local(self):
432
415
        """Creating a new entry in config uses a local path."""
433
 
        branch = self.make_branch('branch', format='knit')
 
416
        branch = self.make_branch('branch')
434
417
        branch.set_push_location('http://foobar')
435
418
        locations = config.locations_config_filename()
436
419
        local_path = osutils.getcwd().encode('utf8')
437
420
        # Surprisingly ConfigObj doesn't create a trailing newline
438
421
        self.check_file_contents(locations,
439
 
                                 '[%s/branch]\n'
440
 
                                 'push_location = http://foobar\n'
441
 
                                 'push_location:policy = norecurse\n'
442
 
                                 % (local_path,))
 
422
            '[%s/branch]\npush_location = http://foobar\npush_location:policy = norecurse' % (local_path,))
443
423
 
444
424
    def test_autonick_urlencoded(self):
445
425
        b = self.make_branch('!repo')
446
426
        self.assertEqual('!repo', b.get_config().get_nickname())
447
427
 
448
 
    def test_warn_if_masked(self):
449
 
        _warning = trace.warning
450
 
        warnings = []
451
 
        def warning(*args):
452
 
            warnings.append(args[0] % args[1:])
453
 
 
454
 
        def set_option(store, warn_masked=True):
455
 
            warnings[:] = []
456
 
            conf.set_user_option('example_option', repr(store), store=store,
457
 
                                 warn_masked=warn_masked)
458
 
        def assertWarning(warning):
459
 
            if warning is None:
460
 
                self.assertEqual(0, len(warnings))
461
 
            else:
462
 
                self.assertEqual(1, len(warnings))
463
 
                self.assertEqual(warning, warnings[0])
464
 
        trace.warning = warning
465
 
        try:
466
 
            branch = self.make_branch('.')
467
 
            conf = branch.get_config()
468
 
            set_option(config.STORE_GLOBAL)
469
 
            assertWarning(None)
470
 
            set_option(config.STORE_BRANCH)
471
 
            assertWarning(None)
472
 
            set_option(config.STORE_GLOBAL)
473
 
            assertWarning('Value "4" is masked by "3" from branch.conf')
474
 
            set_option(config.STORE_GLOBAL, warn_masked=False)
475
 
            assertWarning(None)
476
 
            set_option(config.STORE_LOCATION)
477
 
            assertWarning(None)
478
 
            set_option(config.STORE_BRANCH)
479
 
            assertWarning('Value "3" is masked by "0" from locations.conf')
480
 
            set_option(config.STORE_BRANCH, warn_masked=False)
481
 
            assertWarning(None)
482
 
        finally:
483
 
            trace.warning = _warning
484
 
 
485
 
 
486
 
class TestGlobalConfigItems(tests.TestCase):
 
428
 
 
429
class TestGlobalConfigItems(TestCase):
487
430
 
488
431
    def test_user_id(self):
489
432
        config_file = StringIO(sample_config_text.encode('utf-8'))
563
506
        my_config = self._get_sample_config()
564
507
        self.assertEqual("something",
565
508
                         my_config.get_user_option('user_global_option'))
566
 
 
 
509
        
567
510
    def test_post_commit_default(self):
568
511
        my_config = self._get_sample_config()
569
512
        self.assertEqual(None, my_config.post_commit())
585
528
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
586
529
 
587
530
 
588
 
class TestLocationConfig(tests.TestCaseInTempDir):
 
531
class TestLocationConfig(TestCaseInTempDir):
589
532
 
590
533
    def test_constructs(self):
591
534
        my_config = config.LocationConfig('http://example.com')
595
538
        # This is testing the correct file names are provided.
596
539
        # TODO: consolidate with the test for GlobalConfigs filename checks.
597
540
        #
598
 
        # replace the class that is constructed, to check its parameters
 
541
        # replace the class that is constructured, to check its parameters
599
542
        oldparserclass = config.ConfigObj
600
543
        config.ConfigObj = InstrumentedConfigObj
601
544
        try:
629
572
    def test__get_matching_sections_no_match(self):
630
573
        self.get_branch_config('/')
631
574
        self.assertEqual([], self.my_location_config._get_matching_sections())
632
 
 
 
575
        
633
576
    def test__get_matching_sections_exact(self):
634
577
        self.get_branch_config('http://www.example.com')
635
578
        self.assertEqual([('http://www.example.com', '')],
636
579
                         self.my_location_config._get_matching_sections())
637
 
 
 
580
   
638
581
    def test__get_matching_sections_suffix_does_not(self):
639
582
        self.get_branch_config('http://www.example.com-com')
640
583
        self.assertEqual([], self.my_location_config._get_matching_sections())
652
595
    def test__get_matching_sections_ignoreparent_subdir(self):
653
596
        self.get_branch_config(
654
597
            'http://www.example.com/ignoreparent/childbranch')
655
 
        self.assertEqual([('http://www.example.com/ignoreparent',
656
 
                           'childbranch')],
 
598
        self.assertEqual([('http://www.example.com/ignoreparent', 'childbranch')],
657
599
                         self.my_location_config._get_matching_sections())
658
600
 
659
601
    def test__get_matching_sections_subdir_trailing_slash(self):
739
681
        self.get_branch_config('/a/c')
740
682
        self.assertEqual(config.CHECK_NEVER,
741
683
                         self.my_config.signature_checking())
742
 
 
 
684
        
743
685
    def test_signatures_when_available(self):
744
686
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
745
687
        self.assertEqual(config.CHECK_IF_POSSIBLE,
746
688
                         self.my_config.signature_checking())
747
 
 
 
689
        
748
690
    def test_signatures_always(self):
749
691
        self.get_branch_config('/b')
750
692
        self.assertEqual(config.CHECK_ALWAYS,
751
693
                         self.my_config.signature_checking())
752
 
 
 
694
        
753
695
    def test_gpg_signing_command(self):
754
696
        self.get_branch_config('/b')
755
697
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
846
788
            self.my_location_config._get_option_policy(
847
789
            'http://www.example.com/norecurse', 'normal_option'),
848
790
            config.POLICY_NORECURSE)
 
791
        
849
792
 
850
793
    def test_post_commit_default(self):
851
794
        self.get_branch_config('/a/c')
909
852
        self.assertIs(self.my_config.get_user_option('foo'), None)
910
853
        self.my_config.set_user_option('foo', 'bar')
911
854
        self.assertEqual(
912
 
            self.my_config.branch.control_files.files['branch.conf'],
913
 
            'foo = bar\n')
 
855
            self.my_config.branch.control_files.files['branch.conf'], 
 
856
            'foo = bar')
914
857
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
915
858
        self.my_config.set_user_option('foo', 'baz',
916
859
                                       store=config.STORE_LOCATION)
917
860
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
918
861
        self.my_config.set_user_option('foo', 'qux')
919
862
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
920
 
 
921
 
    def test_get_bzr_remote_path(self):
922
 
        my_config = config.LocationConfig('/a/c')
923
 
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
924
 
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
925
 
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
926
 
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
927
 
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
928
 
 
 
863
        
929
864
 
930
865
precedence_global = 'option = global'
931
866
precedence_branch = 'option = branch'
938
873
"""
939
874
 
940
875
 
941
 
class TestBranchConfigItems(tests.TestCaseInTempDir):
 
876
class TestBranchConfigItems(TestCaseInTempDir):
942
877
 
943
 
    def get_branch_config(self, global_config=None, location=None,
 
878
    def get_branch_config(self, global_config=None, location=None, 
944
879
                          location_config=None, branch_data_config=None):
945
880
        my_config = config.BranchConfig(FakeBranch(location))
946
881
        if global_config is not None:
961
896
        self.assertEqual("Robert Collins <robertc@example.net>",
962
897
                         my_config.username())
963
898
        branch.control_files.email = "John"
964
 
        my_config.set_user_option('email',
 
899
        my_config.set_user_option('email', 
965
900
                                  "Robert Collins <robertc@example.org>")
966
901
        self.assertEqual("John", my_config.username())
967
902
        branch.control_files.email = None
982
917
        my_config = config.BranchConfig(branch)
983
918
        self.assertEqual("Robert Collins <robertc@example.org>",
984
919
                         my_config.username())
985
 
 
 
920
    
986
921
    def test_signatures_forced(self):
987
922
        my_config = self.get_branch_config(
988
923
            global_config=sample_always_signatures)
1032
967
    def test_config_precedence(self):
1033
968
        my_config = self.get_branch_config(global_config=precedence_global)
1034
969
        self.assertEqual(my_config.get_user_option('option'), 'global')
1035
 
        my_config = self.get_branch_config(global_config=precedence_global,
 
970
        my_config = self.get_branch_config(global_config=precedence_global, 
1036
971
                                      branch_data_config=precedence_branch)
1037
972
        self.assertEqual(my_config.get_user_option('option'), 'branch')
1038
 
        my_config = self.get_branch_config(global_config=precedence_global,
 
973
        my_config = self.get_branch_config(global_config=precedence_global, 
1039
974
                                      branch_data_config=precedence_branch,
1040
975
                                      location_config=precedence_location)
1041
976
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
1042
 
        my_config = self.get_branch_config(global_config=precedence_global,
 
977
        my_config = self.get_branch_config(global_config=precedence_global, 
1043
978
                                      branch_data_config=precedence_branch,
1044
979
                                      location_config=precedence_location,
1045
980
                                      location='http://example.com/specific')
1046
981
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1047
982
 
1048
 
    def test_get_mail_client(self):
1049
 
        config = self.get_branch_config()
1050
 
        client = config.get_mail_client()
1051
 
        self.assertIsInstance(client, mail_client.DefaultMail)
1052
 
 
1053
 
        # Specific clients
1054
 
        config.set_user_option('mail_client', 'evolution')
1055
 
        client = config.get_mail_client()
1056
 
        self.assertIsInstance(client, mail_client.Evolution)
1057
 
 
1058
 
        config.set_user_option('mail_client', 'kmail')
1059
 
        client = config.get_mail_client()
1060
 
        self.assertIsInstance(client, mail_client.KMail)
1061
 
 
1062
 
        config.set_user_option('mail_client', 'mutt')
1063
 
        client = config.get_mail_client()
1064
 
        self.assertIsInstance(client, mail_client.Mutt)
1065
 
 
1066
 
        config.set_user_option('mail_client', 'thunderbird')
1067
 
        client = config.get_mail_client()
1068
 
        self.assertIsInstance(client, mail_client.Thunderbird)
1069
 
 
1070
 
        # Generic options
1071
 
        config.set_user_option('mail_client', 'default')
1072
 
        client = config.get_mail_client()
1073
 
        self.assertIsInstance(client, mail_client.DefaultMail)
1074
 
 
1075
 
        config.set_user_option('mail_client', 'editor')
1076
 
        client = config.get_mail_client()
1077
 
        self.assertIsInstance(client, mail_client.Editor)
1078
 
 
1079
 
        config.set_user_option('mail_client', 'mapi')
1080
 
        client = config.get_mail_client()
1081
 
        self.assertIsInstance(client, mail_client.MAPIClient)
1082
 
 
1083
 
        config.set_user_option('mail_client', 'xdg-email')
1084
 
        client = config.get_mail_client()
1085
 
        self.assertIsInstance(client, mail_client.XDGEmail)
1086
 
 
1087
 
        config.set_user_option('mail_client', 'firebird')
1088
 
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1089
 
 
1090
 
 
1091
 
class TestMailAddressExtraction(tests.TestCase):
 
983
 
 
984
class TestMailAddressExtraction(TestCase):
1092
985
 
1093
986
    def test_extract_email_address(self):
1094
987
        self.assertEqual('jane@test.com',
1095
988
                         config.extract_email_address('Jane <jane@test.com>'))
1096
989
        self.assertRaises(errors.NoEmailInUsername,
1097
990
                          config.extract_email_address, 'Jane Tester')
1098
 
 
1099
 
    def test_parse_username(self):
1100
 
        self.assertEqual(('', 'jdoe@example.com'),
1101
 
                         config.parse_username('jdoe@example.com'))
1102
 
        self.assertEqual(('', 'jdoe@example.com'),
1103
 
                         config.parse_username('<jdoe@example.com>'))
1104
 
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1105
 
                         config.parse_username('John Doe <jdoe@example.com>'))
1106
 
        self.assertEqual(('John Doe', ''),
1107
 
                         config.parse_username('John Doe'))
1108
 
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1109
 
                         config.parse_username('John Doe jdoe@example.com'))
1110
 
 
1111
 
class TestTreeConfig(tests.TestCaseWithTransport):
1112
 
 
1113
 
    def test_get_value(self):
1114
 
        """Test that retreiving a value from a section is possible"""
1115
 
        branch = self.make_branch('.')
1116
 
        tree_config = config.TreeConfig(branch)
1117
 
        tree_config.set_option('value', 'key', 'SECTION')
1118
 
        tree_config.set_option('value2', 'key2')
1119
 
        tree_config.set_option('value3-top', 'key3')
1120
 
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1121
 
        value = tree_config.get_option('key', 'SECTION')
1122
 
        self.assertEqual(value, 'value')
1123
 
        value = tree_config.get_option('key2')
1124
 
        self.assertEqual(value, 'value2')
1125
 
        self.assertEqual(tree_config.get_option('non-existant'), None)
1126
 
        value = tree_config.get_option('non-existant', 'SECTION')
1127
 
        self.assertEqual(value, None)
1128
 
        value = tree_config.get_option('non-existant', default='default')
1129
 
        self.assertEqual(value, 'default')
1130
 
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1131
 
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1132
 
        self.assertEqual(value, 'default')
1133
 
        value = tree_config.get_option('key3')
1134
 
        self.assertEqual(value, 'value3-top')
1135
 
        value = tree_config.get_option('key3', 'SECTION')
1136
 
        self.assertEqual(value, 'value3-section')
1137
 
 
1138
 
 
1139
 
class TestAuthenticationConfigFile(tests.TestCase):
1140
 
    """Test the authentication.conf file matching"""
1141
 
 
1142
 
    def _got_user_passwd(self, expected_user, expected_password,
1143
 
                         config, *args, **kwargs):
1144
 
        credentials = config.get_credentials(*args, **kwargs)
1145
 
        if credentials is None:
1146
 
            user = None
1147
 
            password = None
1148
 
        else:
1149
 
            user = credentials['user']
1150
 
            password = credentials['password']
1151
 
        self.assertEquals(expected_user, user)
1152
 
        self.assertEquals(expected_password, password)
1153
 
 
1154
 
    def test_empty_config(self):
1155
 
        conf = config.AuthenticationConfig(_file=StringIO())
1156
 
        self.assertEquals({}, conf._get_config())
1157
 
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1158
 
 
1159
 
    def test_broken_config(self):
1160
 
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1161
 
        self.assertRaises(errors.ParseConfigError, conf._get_config)
1162
 
 
1163
 
        conf = config.AuthenticationConfig(_file=StringIO(
1164
 
                """[broken]
1165
 
scheme=ftp
1166
 
user=joe
1167
 
verify_certificates=askme # Error: Not a boolean
1168
 
"""))
1169
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1170
 
        conf = config.AuthenticationConfig(_file=StringIO(
1171
 
                """[broken]
1172
 
scheme=ftp
1173
 
user=joe
1174
 
port=port # Error: Not an int
1175
 
"""))
1176
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1177
 
 
1178
 
    def test_credentials_for_scheme_host(self):
1179
 
        conf = config.AuthenticationConfig(_file=StringIO(
1180
 
                """# Identity on foo.net
1181
 
[ftp definition]
1182
 
scheme=ftp
1183
 
host=foo.net
1184
 
user=joe
1185
 
password=secret-pass
1186
 
"""))
1187
 
        # Basic matching
1188
 
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1189
 
        # different scheme
1190
 
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1191
 
        # different host
1192
 
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1193
 
 
1194
 
    def test_credentials_for_host_port(self):
1195
 
        conf = config.AuthenticationConfig(_file=StringIO(
1196
 
                """# Identity on foo.net
1197
 
[ftp definition]
1198
 
scheme=ftp
1199
 
port=10021
1200
 
host=foo.net
1201
 
user=joe
1202
 
password=secret-pass
1203
 
"""))
1204
 
        # No port
1205
 
        self._got_user_passwd('joe', 'secret-pass',
1206
 
                              conf, 'ftp', 'foo.net', port=10021)
1207
 
        # different port
1208
 
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1209
 
 
1210
 
    def test_for_matching_host(self):
1211
 
        conf = config.AuthenticationConfig(_file=StringIO(
1212
 
                """# Identity on foo.net
1213
 
[sourceforge]
1214
 
scheme=bzr
1215
 
host=bzr.sf.net
1216
 
user=joe
1217
 
password=joepass
1218
 
[sourceforge domain]
1219
 
scheme=bzr
1220
 
host=.bzr.sf.net
1221
 
user=georges
1222
 
password=bendover
1223
 
"""))
1224
 
        # matching domain
1225
 
        self._got_user_passwd('georges', 'bendover',
1226
 
                              conf, 'bzr', 'foo.bzr.sf.net')
1227
 
        # phishing attempt
1228
 
        self._got_user_passwd(None, None,
1229
 
                              conf, 'bzr', 'bbzr.sf.net')
1230
 
 
1231
 
    def test_for_matching_host_None(self):
1232
 
        conf = config.AuthenticationConfig(_file=StringIO(
1233
 
                """# Identity on foo.net
1234
 
[catchup bzr]
1235
 
scheme=bzr
1236
 
user=joe
1237
 
password=joepass
1238
 
[DEFAULT]
1239
 
user=georges
1240
 
password=bendover
1241
 
"""))
1242
 
        # match no host
1243
 
        self._got_user_passwd('joe', 'joepass',
1244
 
                              conf, 'bzr', 'quux.net')
1245
 
        # no host but different scheme
1246
 
        self._got_user_passwd('georges', 'bendover',
1247
 
                              conf, 'ftp', 'quux.net')
1248
 
 
1249
 
    def test_credentials_for_path(self):
1250
 
        conf = config.AuthenticationConfig(_file=StringIO(
1251
 
                """
1252
 
[http dir1]
1253
 
scheme=http
1254
 
host=bar.org
1255
 
path=/dir1
1256
 
user=jim
1257
 
password=jimpass
1258
 
[http dir2]
1259
 
scheme=http
1260
 
host=bar.org
1261
 
path=/dir2
1262
 
user=georges
1263
 
password=bendover
1264
 
"""))
1265
 
        # no path no dice
1266
 
        self._got_user_passwd(None, None,
1267
 
                              conf, 'http', host='bar.org', path='/dir3')
1268
 
        # matching path
1269
 
        self._got_user_passwd('georges', 'bendover',
1270
 
                              conf, 'http', host='bar.org', path='/dir2')
1271
 
        # matching subdir
1272
 
        self._got_user_passwd('jim', 'jimpass',
1273
 
                              conf, 'http', host='bar.org',path='/dir1/subdir')
1274
 
 
1275
 
    def test_credentials_for_user(self):
1276
 
        conf = config.AuthenticationConfig(_file=StringIO(
1277
 
                """
1278
 
[with user]
1279
 
scheme=http
1280
 
host=bar.org
1281
 
user=jim
1282
 
password=jimpass
1283
 
"""))
1284
 
        # Get user
1285
 
        self._got_user_passwd('jim', 'jimpass',
1286
 
                              conf, 'http', 'bar.org')
1287
 
        # Get same user
1288
 
        self._got_user_passwd('jim', 'jimpass',
1289
 
                              conf, 'http', 'bar.org', user='jim')
1290
 
        # Don't get a different user if one is specified
1291
 
        self._got_user_passwd(None, None,
1292
 
                              conf, 'http', 'bar.org', user='georges')
1293
 
 
1294
 
    def test_verify_certificates(self):
1295
 
        conf = config.AuthenticationConfig(_file=StringIO(
1296
 
                """
1297
 
[self-signed]
1298
 
scheme=https
1299
 
host=bar.org
1300
 
user=jim
1301
 
password=jimpass
1302
 
verify_certificates=False
1303
 
[normal]
1304
 
scheme=https
1305
 
host=foo.net
1306
 
user=georges
1307
 
password=bendover
1308
 
"""))
1309
 
        credentials = conf.get_credentials('https', 'bar.org')
1310
 
        self.assertEquals(False, credentials.get('verify_certificates'))
1311
 
        credentials = conf.get_credentials('https', 'foo.net')
1312
 
        self.assertEquals(True, credentials.get('verify_certificates'))
1313
 
 
1314
 
 
1315
 
class TestAuthenticationConfig(tests.TestCase):
1316
 
    """Test AuthenticationConfig behaviour"""
1317
 
 
1318
 
    def _check_default_prompt(self, expected_prompt_format, scheme,
1319
 
                              host=None, port=None, realm=None, path=None):
1320
 
        if host is None:
1321
 
            host = 'bar.org'
1322
 
        user, password = 'jim', 'precious'
1323
 
        expected_prompt = expected_prompt_format % {
1324
 
            'scheme': scheme, 'host': host, 'port': port,
1325
 
            'user': user, 'realm': realm}
1326
 
 
1327
 
        stdout = tests.StringIOWrapper()
1328
 
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
1329
 
                                            stdout=stdout)
1330
 
        # We use an empty conf so that the user is always prompted
1331
 
        conf = config.AuthenticationConfig()
1332
 
        self.assertEquals(password,
1333
 
                          conf.get_password(scheme, host, user, port=port,
1334
 
                                            realm=realm, path=path))
1335
 
        self.assertEquals(stdout.getvalue(), expected_prompt)
1336
 
 
1337
 
    def test_default_prompts(self):
1338
 
        # HTTP prompts can't be tested here, see test_http.py
1339
 
        self._check_default_prompt('FTP %(user)s@%(host)s password: ', 'ftp')
1340
 
        self._check_default_prompt('FTP %(user)s@%(host)s:%(port)d password: ',
1341
 
                                   'ftp', port=10020)
1342
 
 
1343
 
        self._check_default_prompt('SSH %(user)s@%(host)s:%(port)d password: ',
1344
 
                                   'ssh', port=12345)
1345
 
        # SMTP port handling is a bit special (it's handled if embedded in the
1346
 
        # host too)
1347
 
        # FIXME: should we: forbid that, extend it to other schemes, leave
1348
 
        # things as they are that's fine thank you ?
1349
 
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
1350
 
                                   'smtp')
1351
 
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
1352
 
                                   'smtp', host='bar.org:10025')
1353
 
        self._check_default_prompt(
1354
 
            'SMTP %(user)s@%(host)s:%(port)d password: ',
1355
 
            'smtp', port=10025)
1356
 
 
1357
 
 
1358
 
# FIXME: Once we have a way to declare authentication to all test servers, we
1359
 
# can implement generic tests.
1360
 
# test_user_password_in_url
1361
 
# test_user_in_url_password_from_config
1362
 
# test_user_in_url_password_prompted
1363
 
# test_user_in_config
1364
 
# test_user_getpass.getuser
1365
 
# test_user_prompted ?
1366
 
class TestAuthenticationRing(tests.TestCaseWithTransport):
1367
 
    pass