~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Jelmer Vernooij
  • Date: 2008-09-02 00:29:28 UTC
  • mto: (3680.1.1 bzr.dev)
  • mto: This revision was merged to the branch mainline in revision 3689.
  • Revision ID: jelmer@samba.org-20080902002928-qp0m5mq97t5zm414
Eliminate more uses of Repository.revision_tree(None).

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,
 
36
    transport,
31
37
    )
32
 
from bzrlib.branch import Branch
33
 
from bzrlib.bzrdir import BzrDir
34
 
from bzrlib.tests import TestCase, TestCaseInTempDir, TestCaseWithTransport
 
38
from bzrlib.util.configobj import configobj
35
39
 
36
40
 
37
41
sample_long_alias="log -r-15..-1 --line"
143
147
            self.base = "http://example.com/branches/demo"
144
148
        else:
145
149
            self.base = base
146
 
        self.control_files = FakeControlFiles(user_id=user_id)
 
150
        self._transport = self.control_files = \
 
151
            FakeControlFilesAndTransport(user_id=user_id)
147
152
 
148
153
    def lock_write(self):
149
154
        pass
152
157
        pass
153
158
 
154
159
 
155
 
class FakeControlFiles(object):
 
160
class FakeControlFilesAndTransport(object):
156
161
 
157
162
    def __init__(self, user_id=None):
158
 
        self.email = user_id
159
163
        self.files = {}
 
164
        if user_id:
 
165
            self.files['email'] = user_id
 
166
        self._transport = self
160
167
 
161
168
    def get_utf8(self, filename):
162
 
        if filename != 'email':
163
 
            raise NotImplementedError
164
 
        if self.email is not None:
165
 
            return StringIO(self.email)
166
 
        raise errors.NoSuchFile(filename)
 
169
        # from LockableFiles
 
170
        raise AssertionError("get_utf8 should no longer be used")
167
171
 
168
172
    def get(self, filename):
 
173
        # from Transport
169
174
        try:
170
175
            return StringIO(self.files[filename])
171
176
        except KeyError:
172
177
            raise errors.NoSuchFile(filename)
173
178
 
 
179
    def get_bytes(self, filename):
 
180
        # from Transport
 
181
        try:
 
182
            return self.files[filename]
 
183
        except KeyError:
 
184
            raise errors.NoSuchFile(filename)
 
185
 
174
186
    def put(self, filename, fileobj):
175
187
        self.files[filename] = fileobj.read()
176
188
 
 
189
    def put_file(self, filename, fileobj):
 
190
        return self.put(filename, fileobj)
 
191
 
177
192
 
178
193
class InstrumentedConfig(config.Config):
179
194
    """An instrumented config that supplies stubs for template methods."""
180
 
    
 
195
 
181
196
    def __init__(self):
182
197
        super(InstrumentedConfig, self).__init__()
183
198
        self._calls = []
199
214
active = True
200
215
nonactive = False
201
216
"""
202
 
class TestConfigObj(TestCase):
 
217
 
 
218
 
 
219
class TestConfigObj(tests.TestCase):
 
220
 
203
221
    def test_get_bool(self):
204
 
        from bzrlib.config import ConfigObj
205
 
        co = ConfigObj(StringIO(bool_config))
 
222
        co = config.ConfigObj(StringIO(bool_config))
206
223
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
207
224
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
208
225
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
209
226
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
210
227
 
211
 
 
212
 
class TestConfig(TestCase):
 
228
    def test_hash_sign_in_value(self):
 
229
        """
 
230
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
 
231
        treated as comments when read in again. (#86838)
 
232
        """
 
233
        co = config.ConfigObj()
 
234
        co['test'] = 'foo#bar'
 
235
        lines = co.write()
 
236
        self.assertEqual(lines, ['test = "foo#bar"'])
 
237
        co2 = config.ConfigObj(lines)
 
238
        self.assertEqual(co2['test'], 'foo#bar')
 
239
 
 
240
 
 
241
erroneous_config = """[section] # line 1
 
242
good=good # line 2
 
243
[section] # line 3
 
244
whocares=notme # line 4
 
245
"""
 
246
 
 
247
 
 
248
class TestConfigObjErrors(tests.TestCase):
 
249
 
 
250
    def test_duplicate_section_name_error_line(self):
 
251
        try:
 
252
            co = configobj.ConfigObj(StringIO(erroneous_config),
 
253
                                     raise_errors=True)
 
254
        except config.configobj.DuplicateError, e:
 
255
            self.assertEqual(3, e.line_number)
 
256
        else:
 
257
            self.fail('Error in config file not detected')
 
258
 
 
259
 
 
260
class TestConfig(tests.TestCase):
213
261
 
214
262
    def test_constructs(self):
215
263
        config.Config()
216
 
 
 
264
 
217
265
    def test_no_default_editor(self):
218
266
        self.assertRaises(NotImplementedError, config.Config().get_editor)
219
267
 
265
313
        self.assertEqual('long', my_config.log_format())
266
314
 
267
315
 
268
 
class TestConfigPath(TestCase):
 
316
class TestConfigPath(tests.TestCase):
269
317
 
270
318
    def setUp(self):
271
319
        super(TestConfigPath, self).setUp()
273
321
        if sys.platform == 'win32':
274
322
            os.environ['BZR_HOME'] = \
275
323
                r'C:\Documents and Settings\bogus\Application Data'
 
324
            self.bzr_home = \
 
325
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
 
326
        else:
 
327
            self.bzr_home = '/home/bogus/.bazaar'
276
328
 
277
329
    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')
 
330
        self.assertEqual(config.config_dir(), self.bzr_home)
283
331
 
284
332
    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')
 
333
        self.assertEqual(config.config_filename(),
 
334
                         self.bzr_home + '/bazaar.conf')
291
335
 
292
336
    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')
 
337
        self.assertEqual(config.branches_config_filename(),
 
338
                         self.bzr_home + '/branches.conf')
299
339
 
300
340
    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):
 
341
        self.assertEqual(config.locations_config_filename(),
 
342
                         self.bzr_home + '/locations.conf')
 
343
 
 
344
    def test_authentication_config_filename(self):
 
345
        self.assertEqual(config.authentication_config_filename(),
 
346
                         self.bzr_home + '/authentication.conf')
 
347
 
 
348
 
 
349
class TestIniConfig(tests.TestCase):
309
350
 
310
351
    def test_contructs(self):
311
352
        my_config = config.IniBasedConfig("nothing")
315
356
        my_config = config.IniBasedConfig(None)
316
357
        self.failUnless(
317
358
            isinstance(my_config._get_parser(file=config_file),
318
 
                        ConfigObj))
 
359
                        configobj.ConfigObj))
319
360
 
320
361
    def test_cached(self):
321
362
        config_file = StringIO(sample_config_text.encode('utf-8'))
324
365
        self.failUnless(my_config._get_parser() is parser)
325
366
 
326
367
 
327
 
class TestGetConfig(TestCase):
 
368
class TestGetConfig(tests.TestCase):
328
369
 
329
370
    def test_constructs(self):
330
371
        my_config = config.GlobalConfig()
331
372
 
332
373
    def test_calls_read_filenames(self):
333
 
        # replace the class that is constructured, to check its parameters
 
374
        # replace the class that is constructed, to check its parameters
334
375
        oldparserclass = config.ConfigObj
335
376
        config.ConfigObj = InstrumentedConfigObj
336
377
        my_config = config.GlobalConfig()
343
384
                                          'utf-8')])
344
385
 
345
386
 
346
 
class TestBranchConfig(TestCaseWithTransport):
 
387
class TestBranchConfig(tests.TestCaseWithTransport):
347
388
 
348
389
    def test_constructs(self):
349
390
        branch = FakeBranch()
359
400
 
360
401
    def test_get_config(self):
361
402
        """The Branch.get_config method works properly"""
362
 
        b = BzrDir.create_standalone_workingtree('.').branch
 
403
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
363
404
        my_config = b.get_config()
364
405
        self.assertIs(my_config.get_user_option('wacky'), None)
365
406
        my_config.set_user_option('wacky', 'unlikely')
366
407
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
367
408
 
368
409
        # Ensure we get the same thing if we start again
369
 
        b2 = Branch.open('.')
 
410
        b2 = branch.Branch.open('.')
370
411
        my_config2 = b2.get_config()
371
412
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
372
413
 
407
448
        local_path = osutils.getcwd().encode('utf8')
408
449
        # Surprisingly ConfigObj doesn't create a trailing newline
409
450
        self.check_file_contents(locations,
410
 
            '[%s/branch]\npush_location = http://foobar\npush_location:policy = norecurse' % (local_path,))
 
451
                                 '[%s/branch]\n'
 
452
                                 'push_location = http://foobar\n'
 
453
                                 'push_location:policy = norecurse\n'
 
454
                                 % (local_path,))
411
455
 
412
456
    def test_autonick_urlencoded(self):
413
457
        b = self.make_branch('!repo')
414
458
        self.assertEqual('!repo', b.get_config().get_nickname())
415
459
 
416
 
 
417
 
class TestGlobalConfigItems(TestCase):
 
460
    def test_warn_if_masked(self):
 
461
        _warning = trace.warning
 
462
        warnings = []
 
463
        def warning(*args):
 
464
            warnings.append(args[0] % args[1:])
 
465
 
 
466
        def set_option(store, warn_masked=True):
 
467
            warnings[:] = []
 
468
            conf.set_user_option('example_option', repr(store), store=store,
 
469
                                 warn_masked=warn_masked)
 
470
        def assertWarning(warning):
 
471
            if warning is None:
 
472
                self.assertEqual(0, len(warnings))
 
473
            else:
 
474
                self.assertEqual(1, len(warnings))
 
475
                self.assertEqual(warning, warnings[0])
 
476
        trace.warning = warning
 
477
        try:
 
478
            branch = self.make_branch('.')
 
479
            conf = branch.get_config()
 
480
            set_option(config.STORE_GLOBAL)
 
481
            assertWarning(None)
 
482
            set_option(config.STORE_BRANCH)
 
483
            assertWarning(None)
 
484
            set_option(config.STORE_GLOBAL)
 
485
            assertWarning('Value "4" is masked by "3" from branch.conf')
 
486
            set_option(config.STORE_GLOBAL, warn_masked=False)
 
487
            assertWarning(None)
 
488
            set_option(config.STORE_LOCATION)
 
489
            assertWarning(None)
 
490
            set_option(config.STORE_BRANCH)
 
491
            assertWarning('Value "3" is masked by "0" from locations.conf')
 
492
            set_option(config.STORE_BRANCH, warn_masked=False)
 
493
            assertWarning(None)
 
494
        finally:
 
495
            trace.warning = _warning
 
496
 
 
497
 
 
498
class TestGlobalConfigItems(tests.TestCase):
418
499
 
419
500
    def test_user_id(self):
420
501
        config_file = StringIO(sample_config_text.encode('utf-8'))
494
575
        my_config = self._get_sample_config()
495
576
        self.assertEqual("something",
496
577
                         my_config.get_user_option('user_global_option'))
497
 
        
 
578
 
498
579
    def test_post_commit_default(self):
499
580
        my_config = self._get_sample_config()
500
581
        self.assertEqual(None, my_config.post_commit())
507
588
        my_config = self._get_sample_config()
508
589
        self.assertEqual('help', my_config.get_alias('h'))
509
590
 
 
591
    def test_get_aliases(self):
 
592
        my_config = self._get_sample_config()
 
593
        aliases = my_config.get_aliases()
 
594
        self.assertEqual(2, len(aliases))
 
595
        sorted_keys = sorted(aliases)
 
596
        self.assertEqual('help', aliases[sorted_keys[0]])
 
597
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
 
598
 
510
599
    def test_get_no_alias(self):
511
600
        my_config = self._get_sample_config()
512
601
        self.assertEqual(None, my_config.get_alias('foo'))
516
605
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
517
606
 
518
607
 
519
 
class TestLocationConfig(TestCaseInTempDir):
 
608
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
 
609
 
 
610
    def test_empty(self):
 
611
        my_config = config.GlobalConfig()
 
612
        self.assertEqual(0, len(my_config.get_aliases()))
 
613
 
 
614
    def test_set_alias(self):
 
615
        my_config = config.GlobalConfig()
 
616
        alias_value = 'commit --strict'
 
617
        my_config.set_alias('commit', alias_value)
 
618
        new_config = config.GlobalConfig()
 
619
        self.assertEqual(alias_value, new_config.get_alias('commit'))
 
620
 
 
621
    def test_remove_alias(self):
 
622
        my_config = config.GlobalConfig()
 
623
        my_config.set_alias('commit', 'commit --strict')
 
624
        # Now remove the alias again.
 
625
        my_config.unset_alias('commit')
 
626
        new_config = config.GlobalConfig()
 
627
        self.assertIs(None, new_config.get_alias('commit'))
 
628
 
 
629
 
 
630
class TestLocationConfig(tests.TestCaseInTempDir):
520
631
 
521
632
    def test_constructs(self):
522
633
        my_config = config.LocationConfig('http://example.com')
526
637
        # This is testing the correct file names are provided.
527
638
        # TODO: consolidate with the test for GlobalConfigs filename checks.
528
639
        #
529
 
        # replace the class that is constructured, to check its parameters
 
640
        # replace the class that is constructed, to check its parameters
530
641
        oldparserclass = config.ConfigObj
531
642
        config.ConfigObj = InstrumentedConfigObj
532
643
        try:
560
671
    def test__get_matching_sections_no_match(self):
561
672
        self.get_branch_config('/')
562
673
        self.assertEqual([], self.my_location_config._get_matching_sections())
563
 
        
 
674
 
564
675
    def test__get_matching_sections_exact(self):
565
676
        self.get_branch_config('http://www.example.com')
566
677
        self.assertEqual([('http://www.example.com', '')],
567
678
                         self.my_location_config._get_matching_sections())
568
 
   
 
679
 
569
680
    def test__get_matching_sections_suffix_does_not(self):
570
681
        self.get_branch_config('http://www.example.com-com')
571
682
        self.assertEqual([], self.my_location_config._get_matching_sections())
583
694
    def test__get_matching_sections_ignoreparent_subdir(self):
584
695
        self.get_branch_config(
585
696
            'http://www.example.com/ignoreparent/childbranch')
586
 
        self.assertEqual([('http://www.example.com/ignoreparent', 'childbranch')],
 
697
        self.assertEqual([('http://www.example.com/ignoreparent',
 
698
                           'childbranch')],
587
699
                         self.my_location_config._get_matching_sections())
588
700
 
589
701
    def test__get_matching_sections_subdir_trailing_slash(self):
669
781
        self.get_branch_config('/a/c')
670
782
        self.assertEqual(config.CHECK_NEVER,
671
783
                         self.my_config.signature_checking())
672
 
        
 
784
 
673
785
    def test_signatures_when_available(self):
674
786
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
675
787
        self.assertEqual(config.CHECK_IF_POSSIBLE,
676
788
                         self.my_config.signature_checking())
677
 
        
 
789
 
678
790
    def test_signatures_always(self):
679
791
        self.get_branch_config('/b')
680
792
        self.assertEqual(config.CHECK_ALWAYS,
681
793
                         self.my_config.signature_checking())
682
 
        
 
794
 
683
795
    def test_gpg_signing_command(self):
684
796
        self.get_branch_config('/b')
685
797
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
776
888
            self.my_location_config._get_option_policy(
777
889
            'http://www.example.com/norecurse', 'normal_option'),
778
890
            config.POLICY_NORECURSE)
779
 
        
780
891
 
781
892
    def test_post_commit_default(self):
782
893
        self.get_branch_config('/a/c')
840
951
        self.assertIs(self.my_config.get_user_option('foo'), None)
841
952
        self.my_config.set_user_option('foo', 'bar')
842
953
        self.assertEqual(
843
 
            self.my_config.branch.control_files.files['branch.conf'], 
 
954
            self.my_config.branch.control_files.files['branch.conf'].strip(),
844
955
            'foo = bar')
845
956
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
846
957
        self.my_config.set_user_option('foo', 'baz',
848
959
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
849
960
        self.my_config.set_user_option('foo', 'qux')
850
961
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
851
 
        
 
962
 
 
963
    def test_get_bzr_remote_path(self):
 
964
        my_config = config.LocationConfig('/a/c')
 
965
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
 
966
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
 
967
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
 
968
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
 
969
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
 
970
 
852
971
 
853
972
precedence_global = 'option = global'
854
973
precedence_branch = 'option = branch'
861
980
"""
862
981
 
863
982
 
864
 
class TestBranchConfigItems(TestCaseInTempDir):
 
983
class TestBranchConfigItems(tests.TestCaseInTempDir):
865
984
 
866
 
    def get_branch_config(self, global_config=None, location=None, 
 
985
    def get_branch_config(self, global_config=None, location=None,
867
986
                          location_config=None, branch_data_config=None):
868
987
        my_config = config.BranchConfig(FakeBranch(location))
869
988
        if global_config is not None:
883
1002
        my_config = config.BranchConfig(branch)
884
1003
        self.assertEqual("Robert Collins <robertc@example.net>",
885
1004
                         my_config.username())
886
 
        branch.control_files.email = "John"
887
 
        my_config.set_user_option('email', 
 
1005
        my_config.branch.control_files.files['email'] = "John"
 
1006
        my_config.set_user_option('email',
888
1007
                                  "Robert Collins <robertc@example.org>")
889
1008
        self.assertEqual("John", my_config.username())
890
 
        branch.control_files.email = None
 
1009
        del my_config.branch.control_files.files['email']
891
1010
        self.assertEqual("Robert Collins <robertc@example.org>",
892
1011
                         my_config.username())
893
1012
 
894
1013
    def test_not_set_in_branch(self):
895
1014
        my_config = self.get_branch_config(sample_config_text)
896
 
        my_config.branch.control_files.email = None
897
1015
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
898
1016
                         my_config._get_user_id())
899
 
        my_config.branch.control_files.email = "John"
 
1017
        my_config.branch.control_files.files['email'] = "John"
900
1018
        self.assertEqual("John", my_config._get_user_id())
901
1019
 
902
1020
    def test_BZR_EMAIL_OVERRIDES(self):
905
1023
        my_config = config.BranchConfig(branch)
906
1024
        self.assertEqual("Robert Collins <robertc@example.org>",
907
1025
                         my_config.username())
908
 
    
 
1026
 
909
1027
    def test_signatures_forced(self):
910
1028
        my_config = self.get_branch_config(
911
1029
            global_config=sample_always_signatures)
955
1073
    def test_config_precedence(self):
956
1074
        my_config = self.get_branch_config(global_config=precedence_global)
957
1075
        self.assertEqual(my_config.get_user_option('option'), 'global')
958
 
        my_config = self.get_branch_config(global_config=precedence_global, 
 
1076
        my_config = self.get_branch_config(global_config=precedence_global,
959
1077
                                      branch_data_config=precedence_branch)
960
1078
        self.assertEqual(my_config.get_user_option('option'), 'branch')
961
 
        my_config = self.get_branch_config(global_config=precedence_global, 
 
1079
        my_config = self.get_branch_config(global_config=precedence_global,
962
1080
                                      branch_data_config=precedence_branch,
963
1081
                                      location_config=precedence_location)
964
1082
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
965
 
        my_config = self.get_branch_config(global_config=precedence_global, 
 
1083
        my_config = self.get_branch_config(global_config=precedence_global,
966
1084
                                      branch_data_config=precedence_branch,
967
1085
                                      location_config=precedence_location,
968
1086
                                      location='http://example.com/specific')
969
1087
        self.assertEqual(my_config.get_user_option('option'), 'exact')
970
1088
 
971
 
 
972
 
class TestMailAddressExtraction(TestCase):
 
1089
    def test_get_mail_client(self):
 
1090
        config = self.get_branch_config()
 
1091
        client = config.get_mail_client()
 
1092
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1093
 
 
1094
        # Specific clients
 
1095
        config.set_user_option('mail_client', 'evolution')
 
1096
        client = config.get_mail_client()
 
1097
        self.assertIsInstance(client, mail_client.Evolution)
 
1098
 
 
1099
        config.set_user_option('mail_client', 'kmail')
 
1100
        client = config.get_mail_client()
 
1101
        self.assertIsInstance(client, mail_client.KMail)
 
1102
 
 
1103
        config.set_user_option('mail_client', 'mutt')
 
1104
        client = config.get_mail_client()
 
1105
        self.assertIsInstance(client, mail_client.Mutt)
 
1106
 
 
1107
        config.set_user_option('mail_client', 'thunderbird')
 
1108
        client = config.get_mail_client()
 
1109
        self.assertIsInstance(client, mail_client.Thunderbird)
 
1110
 
 
1111
        # Generic options
 
1112
        config.set_user_option('mail_client', 'default')
 
1113
        client = config.get_mail_client()
 
1114
        self.assertIsInstance(client, mail_client.DefaultMail)
 
1115
 
 
1116
        config.set_user_option('mail_client', 'editor')
 
1117
        client = config.get_mail_client()
 
1118
        self.assertIsInstance(client, mail_client.Editor)
 
1119
 
 
1120
        config.set_user_option('mail_client', 'mapi')
 
1121
        client = config.get_mail_client()
 
1122
        self.assertIsInstance(client, mail_client.MAPIClient)
 
1123
 
 
1124
        config.set_user_option('mail_client', 'xdg-email')
 
1125
        client = config.get_mail_client()
 
1126
        self.assertIsInstance(client, mail_client.XDGEmail)
 
1127
 
 
1128
        config.set_user_option('mail_client', 'firebird')
 
1129
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
 
1130
 
 
1131
 
 
1132
class TestMailAddressExtraction(tests.TestCase):
973
1133
 
974
1134
    def test_extract_email_address(self):
975
1135
        self.assertEqual('jane@test.com',
976
1136
                         config.extract_email_address('Jane <jane@test.com>'))
977
1137
        self.assertRaises(errors.NoEmailInUsername,
978
1138
                          config.extract_email_address, 'Jane Tester')
 
1139
 
 
1140
    def test_parse_username(self):
 
1141
        self.assertEqual(('', 'jdoe@example.com'),
 
1142
                         config.parse_username('jdoe@example.com'))
 
1143
        self.assertEqual(('', 'jdoe@example.com'),
 
1144
                         config.parse_username('<jdoe@example.com>'))
 
1145
        self.assertEqual(('John Doe', 'jdoe@example.com'),
 
1146
                         config.parse_username('John Doe <jdoe@example.com>'))
 
1147
        self.assertEqual(('John Doe', ''),
 
1148
                         config.parse_username('John Doe'))
 
1149
        self.assertEqual(('John Doe', 'jdoe@example.com'),
 
1150
                         config.parse_username('John Doe jdoe@example.com'))
 
1151
 
 
1152
class TestTreeConfig(tests.TestCaseWithTransport):
 
1153
 
 
1154
    def test_get_value(self):
 
1155
        """Test that retreiving a value from a section is possible"""
 
1156
        branch = self.make_branch('.')
 
1157
        tree_config = config.TreeConfig(branch)
 
1158
        tree_config.set_option('value', 'key', 'SECTION')
 
1159
        tree_config.set_option('value2', 'key2')
 
1160
        tree_config.set_option('value3-top', 'key3')
 
1161
        tree_config.set_option('value3-section', 'key3', 'SECTION')
 
1162
        value = tree_config.get_option('key', 'SECTION')
 
1163
        self.assertEqual(value, 'value')
 
1164
        value = tree_config.get_option('key2')
 
1165
        self.assertEqual(value, 'value2')
 
1166
        self.assertEqual(tree_config.get_option('non-existant'), None)
 
1167
        value = tree_config.get_option('non-existant', 'SECTION')
 
1168
        self.assertEqual(value, None)
 
1169
        value = tree_config.get_option('non-existant', default='default')
 
1170
        self.assertEqual(value, 'default')
 
1171
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
 
1172
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
 
1173
        self.assertEqual(value, 'default')
 
1174
        value = tree_config.get_option('key3')
 
1175
        self.assertEqual(value, 'value3-top')
 
1176
        value = tree_config.get_option('key3', 'SECTION')
 
1177
        self.assertEqual(value, 'value3-section')
 
1178
 
 
1179
 
 
1180
class TestTransportConfig(tests.TestCaseWithTransport):
 
1181
 
 
1182
    def test_get_value(self):
 
1183
        """Test that retreiving a value from a section is possible"""
 
1184
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
 
1185
                                               'control.conf')
 
1186
        bzrdir_config.set_option('value', 'key', 'SECTION')
 
1187
        bzrdir_config.set_option('value2', 'key2')
 
1188
        bzrdir_config.set_option('value3-top', 'key3')
 
1189
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
 
1190
        value = bzrdir_config.get_option('key', 'SECTION')
 
1191
        self.assertEqual(value, 'value')
 
1192
        value = bzrdir_config.get_option('key2')
 
1193
        self.assertEqual(value, 'value2')
 
1194
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
 
1195
        value = bzrdir_config.get_option('non-existant', 'SECTION')
 
1196
        self.assertEqual(value, None)
 
1197
        value = bzrdir_config.get_option('non-existant', default='default')
 
1198
        self.assertEqual(value, 'default')
 
1199
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
 
1200
        value = bzrdir_config.get_option('key2', 'NOSECTION',
 
1201
                                         default='default')
 
1202
        self.assertEqual(value, 'default')
 
1203
        value = bzrdir_config.get_option('key3')
 
1204
        self.assertEqual(value, 'value3-top')
 
1205
        value = bzrdir_config.get_option('key3', 'SECTION')
 
1206
        self.assertEqual(value, 'value3-section')
 
1207
 
 
1208
    def test_set_unset_default_stack_on(self):
 
1209
        my_dir = self.make_bzrdir('.')
 
1210
        bzrdir_config = config.BzrDirConfig(my_dir.transport)
 
1211
        self.assertIs(None, bzrdir_config.get_default_stack_on())
 
1212
        bzrdir_config.set_default_stack_on('Foo')
 
1213
        self.assertEqual('Foo', bzrdir_config._config.get_option(
 
1214
                         'default_stack_on'))
 
1215
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
 
1216
        bzrdir_config.set_default_stack_on(None)
 
1217
        self.assertIs(None, bzrdir_config.get_default_stack_on())
 
1218
 
 
1219
 
 
1220
class TestAuthenticationConfigFile(tests.TestCase):
 
1221
    """Test the authentication.conf file matching"""
 
1222
 
 
1223
    def _got_user_passwd(self, expected_user, expected_password,
 
1224
                         config, *args, **kwargs):
 
1225
        credentials = config.get_credentials(*args, **kwargs)
 
1226
        if credentials is None:
 
1227
            user = None
 
1228
            password = None
 
1229
        else:
 
1230
            user = credentials['user']
 
1231
            password = credentials['password']
 
1232
        self.assertEquals(expected_user, user)
 
1233
        self.assertEquals(expected_password, password)
 
1234
 
 
1235
    def test_empty_config(self):
 
1236
        conf = config.AuthenticationConfig(_file=StringIO())
 
1237
        self.assertEquals({}, conf._get_config())
 
1238
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
 
1239
 
 
1240
    def test_missing_auth_section_header(self):
 
1241
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
 
1242
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1243
 
 
1244
    def test_auth_section_header_not_closed(self):
 
1245
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
 
1246
        self.assertRaises(errors.ParseConfigError, conf._get_config)
 
1247
 
 
1248
    def test_auth_value_not_boolean(self):
 
1249
        conf = config.AuthenticationConfig(_file=StringIO(
 
1250
                """[broken]
 
1251
scheme=ftp
 
1252
user=joe
 
1253
verify_certificates=askme # Error: Not a boolean
 
1254
"""))
 
1255
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1256
 
 
1257
    def test_auth_value_not_int(self):
 
1258
        conf = config.AuthenticationConfig(_file=StringIO(
 
1259
                """[broken]
 
1260
scheme=ftp
 
1261
user=joe
 
1262
port=port # Error: Not an int
 
1263
"""))
 
1264
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
 
1265
 
 
1266
    def test_credentials_for_scheme_host(self):
 
1267
        conf = config.AuthenticationConfig(_file=StringIO(
 
1268
                """# Identity on foo.net
 
1269
[ftp definition]
 
1270
scheme=ftp
 
1271
host=foo.net
 
1272
user=joe
 
1273
password=secret-pass
 
1274
"""))
 
1275
        # Basic matching
 
1276
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
 
1277
        # different scheme
 
1278
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
 
1279
        # different host
 
1280
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
 
1281
 
 
1282
    def test_credentials_for_host_port(self):
 
1283
        conf = config.AuthenticationConfig(_file=StringIO(
 
1284
                """# Identity on foo.net
 
1285
[ftp definition]
 
1286
scheme=ftp
 
1287
port=10021
 
1288
host=foo.net
 
1289
user=joe
 
1290
password=secret-pass
 
1291
"""))
 
1292
        # No port
 
1293
        self._got_user_passwd('joe', 'secret-pass',
 
1294
                              conf, 'ftp', 'foo.net', port=10021)
 
1295
        # different port
 
1296
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
 
1297
 
 
1298
    def test_for_matching_host(self):
 
1299
        conf = config.AuthenticationConfig(_file=StringIO(
 
1300
                """# Identity on foo.net
 
1301
[sourceforge]
 
1302
scheme=bzr
 
1303
host=bzr.sf.net
 
1304
user=joe
 
1305
password=joepass
 
1306
[sourceforge domain]
 
1307
scheme=bzr
 
1308
host=.bzr.sf.net
 
1309
user=georges
 
1310
password=bendover
 
1311
"""))
 
1312
        # matching domain
 
1313
        self._got_user_passwd('georges', 'bendover',
 
1314
                              conf, 'bzr', 'foo.bzr.sf.net')
 
1315
        # phishing attempt
 
1316
        self._got_user_passwd(None, None,
 
1317
                              conf, 'bzr', 'bbzr.sf.net')
 
1318
 
 
1319
    def test_for_matching_host_None(self):
 
1320
        conf = config.AuthenticationConfig(_file=StringIO(
 
1321
                """# Identity on foo.net
 
1322
[catchup bzr]
 
1323
scheme=bzr
 
1324
user=joe
 
1325
password=joepass
 
1326
[DEFAULT]
 
1327
user=georges
 
1328
password=bendover
 
1329
"""))
 
1330
        # match no host
 
1331
        self._got_user_passwd('joe', 'joepass',
 
1332
                              conf, 'bzr', 'quux.net')
 
1333
        # no host but different scheme
 
1334
        self._got_user_passwd('georges', 'bendover',
 
1335
                              conf, 'ftp', 'quux.net')
 
1336
 
 
1337
    def test_credentials_for_path(self):
 
1338
        conf = config.AuthenticationConfig(_file=StringIO(
 
1339
                """
 
1340
[http dir1]
 
1341
scheme=http
 
1342
host=bar.org
 
1343
path=/dir1
 
1344
user=jim
 
1345
password=jimpass
 
1346
[http dir2]
 
1347
scheme=http
 
1348
host=bar.org
 
1349
path=/dir2
 
1350
user=georges
 
1351
password=bendover
 
1352
"""))
 
1353
        # no path no dice
 
1354
        self._got_user_passwd(None, None,
 
1355
                              conf, 'http', host='bar.org', path='/dir3')
 
1356
        # matching path
 
1357
        self._got_user_passwd('georges', 'bendover',
 
1358
                              conf, 'http', host='bar.org', path='/dir2')
 
1359
        # matching subdir
 
1360
        self._got_user_passwd('jim', 'jimpass',
 
1361
                              conf, 'http', host='bar.org',path='/dir1/subdir')
 
1362
 
 
1363
    def test_credentials_for_user(self):
 
1364
        conf = config.AuthenticationConfig(_file=StringIO(
 
1365
                """
 
1366
[with user]
 
1367
scheme=http
 
1368
host=bar.org
 
1369
user=jim
 
1370
password=jimpass
 
1371
"""))
 
1372
        # Get user
 
1373
        self._got_user_passwd('jim', 'jimpass',
 
1374
                              conf, 'http', 'bar.org')
 
1375
        # Get same user
 
1376
        self._got_user_passwd('jim', 'jimpass',
 
1377
                              conf, 'http', 'bar.org', user='jim')
 
1378
        # Don't get a different user if one is specified
 
1379
        self._got_user_passwd(None, None,
 
1380
                              conf, 'http', 'bar.org', user='georges')
 
1381
 
 
1382
    def test_credentials_for_user_without_password(self):
 
1383
        conf = config.AuthenticationConfig(_file=StringIO(
 
1384
                """
 
1385
[without password]
 
1386
scheme=http
 
1387
host=bar.org
 
1388
user=jim
 
1389
"""))
 
1390
        # Get user but no password
 
1391
        self._got_user_passwd('jim', None,
 
1392
                              conf, 'http', 'bar.org')
 
1393
 
 
1394
    def test_verify_certificates(self):
 
1395
        conf = config.AuthenticationConfig(_file=StringIO(
 
1396
                """
 
1397
[self-signed]
 
1398
scheme=https
 
1399
host=bar.org
 
1400
user=jim
 
1401
password=jimpass
 
1402
verify_certificates=False
 
1403
[normal]
 
1404
scheme=https
 
1405
host=foo.net
 
1406
user=georges
 
1407
password=bendover
 
1408
"""))
 
1409
        credentials = conf.get_credentials('https', 'bar.org')
 
1410
        self.assertEquals(False, credentials.get('verify_certificates'))
 
1411
        credentials = conf.get_credentials('https', 'foo.net')
 
1412
        self.assertEquals(True, credentials.get('verify_certificates'))
 
1413
 
 
1414
 
 
1415
class TestAuthenticationConfig(tests.TestCase):
 
1416
    """Test AuthenticationConfig behaviour"""
 
1417
 
 
1418
    def _check_default_prompt(self, expected_prompt_format, scheme,
 
1419
                              host=None, port=None, realm=None, path=None):
 
1420
        if host is None:
 
1421
            host = 'bar.org'
 
1422
        user, password = 'jim', 'precious'
 
1423
        expected_prompt = expected_prompt_format % {
 
1424
            'scheme': scheme, 'host': host, 'port': port,
 
1425
            'user': user, 'realm': realm}
 
1426
 
 
1427
        stdout = tests.StringIOWrapper()
 
1428
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
 
1429
                                            stdout=stdout)
 
1430
        # We use an empty conf so that the user is always prompted
 
1431
        conf = config.AuthenticationConfig()
 
1432
        self.assertEquals(password,
 
1433
                          conf.get_password(scheme, host, user, port=port,
 
1434
                                            realm=realm, path=path))
 
1435
        self.assertEquals(stdout.getvalue(), expected_prompt)
 
1436
 
 
1437
    def test_default_prompts(self):
 
1438
        # HTTP prompts can't be tested here, see test_http.py
 
1439
        self._check_default_prompt('FTP %(user)s@%(host)s password: ', 'ftp')
 
1440
        self._check_default_prompt('FTP %(user)s@%(host)s:%(port)d password: ',
 
1441
                                   'ftp', port=10020)
 
1442
 
 
1443
        self._check_default_prompt('SSH %(user)s@%(host)s:%(port)d password: ',
 
1444
                                   'ssh', port=12345)
 
1445
        # SMTP port handling is a bit special (it's handled if embedded in the
 
1446
        # host too)
 
1447
        # FIXME: should we: forbid that, extend it to other schemes, leave
 
1448
        # things as they are that's fine thank you ?
 
1449
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
 
1450
                                   'smtp')
 
1451
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
 
1452
                                   'smtp', host='bar.org:10025')
 
1453
        self._check_default_prompt(
 
1454
            'SMTP %(user)s@%(host)s:%(port)d password: ',
 
1455
            'smtp', port=10025)
 
1456
 
 
1457
    def test_ssh_password_emits_warning(self):
 
1458
        conf = config.AuthenticationConfig(_file=StringIO(
 
1459
                """
 
1460
[ssh with password]
 
1461
scheme=ssh
 
1462
host=bar.org
 
1463
user=jim
 
1464
password=jimpass
 
1465
"""))
 
1466
        entered_password = 'typed-by-hand'
 
1467
        stdout = tests.StringIOWrapper()
 
1468
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
 
1469
                                            stdout=stdout)
 
1470
 
 
1471
        # Since the password defined in the authentication config is ignored,
 
1472
        # the user is prompted
 
1473
        self.assertEquals(entered_password,
 
1474
                          conf.get_password('ssh', 'bar.org', user='jim'))
 
1475
        self.assertContainsRe(
 
1476
            self._get_log(keep_log_file=True),
 
1477
            'password ignored in section \[ssh with password\]')
 
1478
 
 
1479
    def test_ssh_without_password_doesnt_emit_warning(self):
 
1480
        conf = config.AuthenticationConfig(_file=StringIO(
 
1481
                """
 
1482
[ssh with password]
 
1483
scheme=ssh
 
1484
host=bar.org
 
1485
user=jim
 
1486
"""))
 
1487
        entered_password = 'typed-by-hand'
 
1488
        stdout = tests.StringIOWrapper()
 
1489
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
 
1490
                                            stdout=stdout)
 
1491
 
 
1492
        # Since the password defined in the authentication config is ignored,
 
1493
        # the user is prompted
 
1494
        self.assertEquals(entered_password,
 
1495
                          conf.get_password('ssh', 'bar.org', user='jim'))
 
1496
        # No warning shoud be emitted since there is no password. We are only
 
1497
        # providing "user".
 
1498
        self.assertNotContainsRe(
 
1499
            self._get_log(keep_log_file=True),
 
1500
            'password ignored in section \[ssh with password\]')
 
1501
 
 
1502
 
 
1503
# FIXME: Once we have a way to declare authentication to all test servers, we
 
1504
# can implement generic tests.
 
1505
# test_user_password_in_url
 
1506
# test_user_in_url_password_from_config
 
1507
# test_user_in_url_password_prompted
 
1508
# test_user_in_config
 
1509
# test_user_getpass.getuser
 
1510
# test_user_prompted ?
 
1511
class TestAuthenticationRing(tests.TestCaseWithTransport):
 
1512
    pass