~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Ian Clatworthy
  • Date: 2007-08-14 02:48:36 UTC
  • mto: (2733.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 2734.
  • Revision ID: ian.clatworthy@internode.on.net-20070814024836-xvzzxgu6iu0qb2xa
Ensure doc hierarchy is setup correctly for the Windows installer

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
#   Authors: Robert Collins <robert.collins@canonical.com>
2
3
#
3
4
# This program is free software; you can redistribute it and/or modify
4
5
# it under the terms of the GNU General Public License as published by
12
13
#
13
14
# You should have received a copy of the GNU General Public License
14
15
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
 
17
18
"""Tests for finding and reading the bzr config file[s]."""
18
19
# import system imports here
 
20
from bzrlib.util.configobj.configobj import ConfigObj, ConfigObjError
19
21
from cStringIO import StringIO
20
22
import os
21
23
import sys
22
24
 
23
25
#import bzrlib specific imports here
24
26
from bzrlib import (
25
 
    branch,
26
 
    bzrdir,
27
27
    config,
28
 
    diff,
29
28
    errors,
30
29
    osutils,
31
 
    mail_client,
32
 
    ui,
33
30
    urlutils,
34
 
    tests,
35
31
    trace,
36
 
    transport,
37
32
    )
38
 
from bzrlib.util.configobj import configobj
 
33
from bzrlib.branch import Branch
 
34
from bzrlib.bzrdir import BzrDir
 
35
from bzrlib.tests import TestCase, TestCaseInTempDir, TestCaseWithTransport
39
36
 
40
37
 
41
38
sample_long_alias="log -r-15..-1 --line"
43
40
[DEFAULT]
44
41
email=Erik B\u00e5gfors <erik@bagfors.nu>
45
42
editor=vim
46
 
change_editor=vimdiff -of @new_path @old_path
47
43
gpg_signing_command=gnome-gpg
48
44
log_format=short
49
45
user_global_option=something
148
144
            self.base = "http://example.com/branches/demo"
149
145
        else:
150
146
            self.base = base
151
 
        self._transport = self.control_files = \
152
 
            FakeControlFilesAndTransport(user_id=user_id)
153
 
 
154
 
    def _get_config(self):
155
 
        return config.TransportConfig(self._transport, 'branch.conf')
 
147
        self.control_files = FakeControlFiles(user_id=user_id)
156
148
 
157
149
    def lock_write(self):
158
150
        pass
161
153
        pass
162
154
 
163
155
 
164
 
class FakeControlFilesAndTransport(object):
 
156
class FakeControlFiles(object):
165
157
 
166
158
    def __init__(self, user_id=None):
 
159
        self.email = user_id
167
160
        self.files = {}
168
 
        if user_id:
169
 
            self.files['email'] = user_id
170
 
        self._transport = self
171
161
 
172
162
    def get_utf8(self, filename):
173
 
        # from LockableFiles
174
 
        raise AssertionError("get_utf8 should no longer be used")
 
163
        if filename != 'email':
 
164
            raise NotImplementedError
 
165
        if self.email is not None:
 
166
            return StringIO(self.email)
 
167
        raise errors.NoSuchFile(filename)
175
168
 
176
169
    def get(self, filename):
177
 
        # from Transport
178
170
        try:
179
171
            return StringIO(self.files[filename])
180
172
        except KeyError:
181
173
            raise errors.NoSuchFile(filename)
182
174
 
183
 
    def get_bytes(self, filename):
184
 
        # from Transport
185
 
        try:
186
 
            return self.files[filename]
187
 
        except KeyError:
188
 
            raise errors.NoSuchFile(filename)
189
 
 
190
175
    def put(self, filename, fileobj):
191
176
        self.files[filename] = fileobj.read()
192
177
 
193
 
    def put_file(self, filename, fileobj):
194
 
        return self.put(filename, fileobj)
195
 
 
196
178
 
197
179
class InstrumentedConfig(config.Config):
198
180
    """An instrumented config that supplies stubs for template methods."""
199
 
 
 
181
    
200
182
    def __init__(self):
201
183
        super(InstrumentedConfig, self).__init__()
202
184
        self._calls = []
210
192
        self._calls.append('_get_signature_checking')
211
193
        return self._signatures
212
194
 
213
 
    def _get_change_editor(self):
214
 
        self._calls.append('_get_change_editor')
215
 
        return 'vimdiff -fo @new_path @old_path'
216
 
 
217
195
 
218
196
bool_config = """[DEFAULT]
219
197
active = true
222
200
active = True
223
201
nonactive = False
224
202
"""
225
 
 
226
 
 
227
 
class TestConfigObj(tests.TestCase):
228
 
 
 
203
class TestConfigObj(TestCase):
229
204
    def test_get_bool(self):
230
 
        co = config.ConfigObj(StringIO(bool_config))
 
205
        from bzrlib.config import ConfigObj
 
206
        co = ConfigObj(StringIO(bool_config))
231
207
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
232
208
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
233
209
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
234
210
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
235
211
 
236
 
    def test_hash_sign_in_value(self):
237
 
        """
238
 
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
239
 
        treated as comments when read in again. (#86838)
240
 
        """
241
 
        co = config.ConfigObj()
242
 
        co['test'] = 'foo#bar'
243
 
        lines = co.write()
244
 
        self.assertEqual(lines, ['test = "foo#bar"'])
245
 
        co2 = config.ConfigObj(lines)
246
 
        self.assertEqual(co2['test'], 'foo#bar')
247
 
 
248
 
 
249
 
erroneous_config = """[section] # line 1
250
 
good=good # line 2
251
 
[section] # line 3
252
 
whocares=notme # line 4
253
 
"""
254
 
 
255
 
 
256
 
class TestConfigObjErrors(tests.TestCase):
257
 
 
258
 
    def test_duplicate_section_name_error_line(self):
259
 
        try:
260
 
            co = configobj.ConfigObj(StringIO(erroneous_config),
261
 
                                     raise_errors=True)
262
 
        except config.configobj.DuplicateError, e:
263
 
            self.assertEqual(3, e.line_number)
264
 
        else:
265
 
            self.fail('Error in config file not detected')
266
 
 
267
 
 
268
 
class TestConfig(tests.TestCase):
 
212
 
 
213
class TestConfig(TestCase):
269
214
 
270
215
    def test_constructs(self):
271
216
        config.Config()
272
 
 
 
217
 
273
218
    def test_no_default_editor(self):
274
219
        self.assertRaises(NotImplementedError, config.Config().get_editor)
275
220
 
320
265
        my_config = config.Config()
321
266
        self.assertEqual('long', my_config.log_format())
322
267
 
323
 
    def test_get_change_editor(self):
324
 
        my_config = InstrumentedConfig()
325
 
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
326
 
        self.assertEqual(['_get_change_editor'], my_config._calls)
327
 
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
328
 
        self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
329
 
                         change_editor.command_template)
330
 
 
331
 
 
332
 
class TestConfigPath(tests.TestCase):
 
268
 
 
269
class TestConfigPath(TestCase):
333
270
 
334
271
    def setUp(self):
335
272
        super(TestConfigPath, self).setUp()
336
273
        os.environ['HOME'] = '/home/bogus'
337
 
        os.environ['XDG_CACHE_DIR'] = ''
338
274
        if sys.platform == 'win32':
339
275
            os.environ['BZR_HOME'] = \
340
276
                r'C:\Documents and Settings\bogus\Application Data'
341
 
            self.bzr_home = \
342
 
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
343
 
        else:
344
 
            self.bzr_home = '/home/bogus/.bazaar'
345
277
 
346
278
    def test_config_dir(self):
347
 
        self.assertEqual(config.config_dir(), self.bzr_home)
 
279
        if sys.platform == 'win32':
 
280
            self.assertEqual(config.config_dir(), 
 
281
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0')
 
282
        else:
 
283
            self.assertEqual(config.config_dir(), '/home/bogus/.bazaar')
348
284
 
349
285
    def test_config_filename(self):
350
 
        self.assertEqual(config.config_filename(),
351
 
                         self.bzr_home + '/bazaar.conf')
 
286
        if sys.platform == 'win32':
 
287
            self.assertEqual(config.config_filename(), 
 
288
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/bazaar.conf')
 
289
        else:
 
290
            self.assertEqual(config.config_filename(),
 
291
                             '/home/bogus/.bazaar/bazaar.conf')
352
292
 
353
293
    def test_branches_config_filename(self):
354
 
        self.assertEqual(config.branches_config_filename(),
355
 
                         self.bzr_home + '/branches.conf')
 
294
        if sys.platform == 'win32':
 
295
            self.assertEqual(config.branches_config_filename(), 
 
296
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/branches.conf')
 
297
        else:
 
298
            self.assertEqual(config.branches_config_filename(),
 
299
                             '/home/bogus/.bazaar/branches.conf')
356
300
 
357
301
    def test_locations_config_filename(self):
358
 
        self.assertEqual(config.locations_config_filename(),
359
 
                         self.bzr_home + '/locations.conf')
360
 
 
361
 
    def test_authentication_config_filename(self):
362
 
        self.assertEqual(config.authentication_config_filename(),
363
 
                         self.bzr_home + '/authentication.conf')
364
 
 
365
 
    def test_xdg_cache_dir(self):
366
 
        self.assertEqual(config.xdg_cache_dir(),
367
 
            '/home/bogus/.cache')
368
 
 
369
 
 
370
 
class TestIniConfig(tests.TestCase):
371
 
 
372
 
    def make_config_parser(self, s):
373
 
        conf = config.IniBasedConfig(None)
374
 
        parser = conf._get_parser(file=StringIO(s.encode('utf-8')))
375
 
        return conf, parser
376
 
 
377
 
 
378
 
class TestIniConfigBuilding(TestIniConfig):
 
302
        if sys.platform == 'win32':
 
303
            self.assertEqual(config.locations_config_filename(), 
 
304
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/locations.conf')
 
305
        else:
 
306
            self.assertEqual(config.locations_config_filename(),
 
307
                             '/home/bogus/.bazaar/locations.conf')
 
308
 
 
309
class TestIniConfig(TestCase):
379
310
 
380
311
    def test_contructs(self):
381
312
        my_config = config.IniBasedConfig("nothing")
385
316
        my_config = config.IniBasedConfig(None)
386
317
        self.failUnless(
387
318
            isinstance(my_config._get_parser(file=config_file),
388
 
                        configobj.ConfigObj))
 
319
                        ConfigObj))
389
320
 
390
321
    def test_cached(self):
391
322
        config_file = StringIO(sample_config_text.encode('utf-8'))
394
325
        self.failUnless(my_config._get_parser() is parser)
395
326
 
396
327
 
397
 
class TestGetUserOptionAs(TestIniConfig):
398
 
 
399
 
    def test_get_user_option_as_bool(self):
400
 
        conf, parser = self.make_config_parser("""
401
 
a_true_bool = true
402
 
a_false_bool = 0
403
 
an_invalid_bool = maybe
404
 
a_list = hmm, who knows ? # This is interpreted as a list !
405
 
""")
406
 
        get_bool = conf.get_user_option_as_bool
407
 
        self.assertEqual(True, get_bool('a_true_bool'))
408
 
        self.assertEqual(False, get_bool('a_false_bool'))
409
 
        self.assertIs(None, get_bool('an_invalid_bool'))
410
 
        self.assertIs(None, get_bool('not_defined_in_this_config'))
411
 
 
412
 
 
413
 
    def test_get_user_option_as_list(self):
414
 
        conf, parser = self.make_config_parser("""
415
 
a_list = a,b,c
416
 
length_1 = 1,
417
 
one_item = x
418
 
""")
419
 
        get_list = conf.get_user_option_as_list
420
 
        self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
421
 
        self.assertEqual(['1'], get_list('length_1'))
422
 
        self.assertEqual('x', conf.get_user_option('one_item'))
423
 
        # automatically cast to list
424
 
        self.assertEqual(['x'], get_list('one_item'))
425
 
 
426
 
 
427
 
class TestSupressWarning(TestIniConfig):
428
 
 
429
 
    def make_warnings_config(self, s):
430
 
        conf, parser = self.make_config_parser(s)
431
 
        return conf.suppress_warning
432
 
 
433
 
    def test_suppress_warning_unknown(self):
434
 
        suppress_warning = self.make_warnings_config('')
435
 
        self.assertEqual(False, suppress_warning('unknown_warning'))
436
 
 
437
 
    def test_suppress_warning_known(self):
438
 
        suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
439
 
        self.assertEqual(False, suppress_warning('c'))
440
 
        self.assertEqual(True, suppress_warning('a'))
441
 
        self.assertEqual(True, suppress_warning('b'))
442
 
 
443
 
 
444
 
class TestGetConfig(tests.TestCase):
 
328
class TestGetConfig(TestCase):
445
329
 
446
330
    def test_constructs(self):
447
331
        my_config = config.GlobalConfig()
448
332
 
449
333
    def test_calls_read_filenames(self):
450
 
        # replace the class that is constructed, to check its parameters
 
334
        # replace the class that is constructured, to check its parameters
451
335
        oldparserclass = config.ConfigObj
452
336
        config.ConfigObj = InstrumentedConfigObj
453
337
        my_config = config.GlobalConfig()
460
344
                                          'utf-8')])
461
345
 
462
346
 
463
 
class TestBranchConfig(tests.TestCaseWithTransport):
 
347
class TestBranchConfig(TestCaseWithTransport):
464
348
 
465
349
    def test_constructs(self):
466
350
        branch = FakeBranch()
476
360
 
477
361
    def test_get_config(self):
478
362
        """The Branch.get_config method works properly"""
479
 
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
 
363
        b = BzrDir.create_standalone_workingtree('.').branch
480
364
        my_config = b.get_config()
481
365
        self.assertIs(my_config.get_user_option('wacky'), None)
482
366
        my_config.set_user_option('wacky', 'unlikely')
483
367
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
484
368
 
485
369
        # Ensure we get the same thing if we start again
486
 
        b2 = branch.Branch.open('.')
 
370
        b2 = Branch.open('.')
487
371
        my_config2 = b2.get_config()
488
372
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
489
373
 
501
385
        locations = config.locations_config_filename()
502
386
        config.ensure_config_dir_exists()
503
387
        local_url = urlutils.local_path_to_url('branch')
504
 
        open(locations, 'wb').write('[%s]\nnickname = foobar'
 
388
        open(locations, 'wb').write('[%s]\nnickname = foobar' 
505
389
                                    % (local_url,))
506
390
        self.assertEqual('foobar', branch.nick)
507
391
 
512
396
 
513
397
        locations = config.locations_config_filename()
514
398
        config.ensure_config_dir_exists()
515
 
        open(locations, 'wb').write('[%s/branch]\nnickname = barry'
 
399
        open(locations, 'wb').write('[%s/branch]\nnickname = barry' 
516
400
                                    % (osutils.getcwd().encode('utf8'),))
517
401
        self.assertEqual('barry', branch.nick)
518
402
 
524
408
        local_path = osutils.getcwd().encode('utf8')
525
409
        # Surprisingly ConfigObj doesn't create a trailing newline
526
410
        self.check_file_contents(locations,
527
 
                                 '[%s/branch]\n'
528
 
                                 'push_location = http://foobar\n'
529
 
                                 'push_location:policy = norecurse\n'
530
 
                                 % (local_path,))
 
411
            '[%s/branch]\npush_location = http://foobar\npush_location:policy = norecurse' % (local_path,))
531
412
 
532
413
    def test_autonick_urlencoded(self):
533
414
        b = self.make_branch('!repo')
571
452
            trace.warning = _warning
572
453
 
573
454
 
574
 
class TestGlobalConfigItems(tests.TestCase):
 
455
class TestGlobalConfigItems(TestCase):
575
456
 
576
457
    def test_user_id(self):
577
458
        config_file = StringIO(sample_config_text.encode('utf-8'))
651
532
        my_config = self._get_sample_config()
652
533
        self.assertEqual("something",
653
534
                         my_config.get_user_option('user_global_option'))
654
 
 
 
535
        
655
536
    def test_post_commit_default(self):
656
537
        my_config = self._get_sample_config()
657
538
        self.assertEqual(None, my_config.post_commit())
664
545
        my_config = self._get_sample_config()
665
546
        self.assertEqual('help', my_config.get_alias('h'))
666
547
 
667
 
    def test_get_aliases(self):
668
 
        my_config = self._get_sample_config()
669
 
        aliases = my_config.get_aliases()
670
 
        self.assertEqual(2, len(aliases))
671
 
        sorted_keys = sorted(aliases)
672
 
        self.assertEqual('help', aliases[sorted_keys[0]])
673
 
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
674
 
 
675
548
    def test_get_no_alias(self):
676
549
        my_config = self._get_sample_config()
677
550
        self.assertEqual(None, my_config.get_alias('foo'))
680
553
        my_config = self._get_sample_config()
681
554
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
682
555
 
683
 
    def test_get_change_editor(self):
684
 
        my_config = self._get_sample_config()
685
 
        change_editor = my_config.get_change_editor('old', 'new')
686
 
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
687
 
        self.assertEqual('vimdiff -of @new_path @old_path',
688
 
                         ' '.join(change_editor.command_template))
689
 
 
690
 
    def test_get_no_change_editor(self):
691
 
        my_config = self._get_empty_config()
692
 
        change_editor = my_config.get_change_editor('old', 'new')
693
 
        self.assertIs(None, change_editor)
694
 
 
695
 
 
696
 
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
697
 
 
698
 
    def test_empty(self):
699
 
        my_config = config.GlobalConfig()
700
 
        self.assertEqual(0, len(my_config.get_aliases()))
701
 
 
702
 
    def test_set_alias(self):
703
 
        my_config = config.GlobalConfig()
704
 
        alias_value = 'commit --strict'
705
 
        my_config.set_alias('commit', alias_value)
706
 
        new_config = config.GlobalConfig()
707
 
        self.assertEqual(alias_value, new_config.get_alias('commit'))
708
 
 
709
 
    def test_remove_alias(self):
710
 
        my_config = config.GlobalConfig()
711
 
        my_config.set_alias('commit', 'commit --strict')
712
 
        # Now remove the alias again.
713
 
        my_config.unset_alias('commit')
714
 
        new_config = config.GlobalConfig()
715
 
        self.assertIs(None, new_config.get_alias('commit'))
716
 
 
717
 
 
718
 
class TestLocationConfig(tests.TestCaseInTempDir):
 
556
 
 
557
class TestLocationConfig(TestCaseInTempDir):
719
558
 
720
559
    def test_constructs(self):
721
560
        my_config = config.LocationConfig('http://example.com')
725
564
        # This is testing the correct file names are provided.
726
565
        # TODO: consolidate with the test for GlobalConfigs filename checks.
727
566
        #
728
 
        # replace the class that is constructed, to check its parameters
 
567
        # replace the class that is constructured, to check its parameters
729
568
        oldparserclass = config.ConfigObj
730
569
        config.ConfigObj = InstrumentedConfigObj
731
570
        try:
759
598
    def test__get_matching_sections_no_match(self):
760
599
        self.get_branch_config('/')
761
600
        self.assertEqual([], self.my_location_config._get_matching_sections())
762
 
 
 
601
        
763
602
    def test__get_matching_sections_exact(self):
764
603
        self.get_branch_config('http://www.example.com')
765
604
        self.assertEqual([('http://www.example.com', '')],
766
605
                         self.my_location_config._get_matching_sections())
767
 
 
 
606
   
768
607
    def test__get_matching_sections_suffix_does_not(self):
769
608
        self.get_branch_config('http://www.example.com-com')
770
609
        self.assertEqual([], self.my_location_config._get_matching_sections())
782
621
    def test__get_matching_sections_ignoreparent_subdir(self):
783
622
        self.get_branch_config(
784
623
            'http://www.example.com/ignoreparent/childbranch')
785
 
        self.assertEqual([('http://www.example.com/ignoreparent',
786
 
                           'childbranch')],
 
624
        self.assertEqual([('http://www.example.com/ignoreparent', 'childbranch')],
787
625
                         self.my_location_config._get_matching_sections())
788
626
 
789
627
    def test__get_matching_sections_subdir_trailing_slash(self):
869
707
        self.get_branch_config('/a/c')
870
708
        self.assertEqual(config.CHECK_NEVER,
871
709
                         self.my_config.signature_checking())
872
 
 
 
710
        
873
711
    def test_signatures_when_available(self):
874
712
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
875
713
        self.assertEqual(config.CHECK_IF_POSSIBLE,
876
714
                         self.my_config.signature_checking())
877
 
 
 
715
        
878
716
    def test_signatures_always(self):
879
717
        self.get_branch_config('/b')
880
718
        self.assertEqual(config.CHECK_ALWAYS,
881
719
                         self.my_config.signature_checking())
882
 
 
 
720
        
883
721
    def test_gpg_signing_command(self):
884
722
        self.get_branch_config('/b')
885
723
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
1039
877
        self.assertIs(self.my_config.get_user_option('foo'), None)
1040
878
        self.my_config.set_user_option('foo', 'bar')
1041
879
        self.assertEqual(
1042
 
            self.my_config.branch.control_files.files['branch.conf'].strip(),
 
880
            self.my_config.branch.control_files.files['branch.conf'], 
1043
881
            'foo = bar')
1044
882
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
1045
883
        self.my_config.set_user_option('foo', 'baz',
1047
885
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1048
886
        self.my_config.set_user_option('foo', 'qux')
1049
887
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1050
 
 
1051
 
    def test_get_bzr_remote_path(self):
1052
 
        my_config = config.LocationConfig('/a/c')
1053
 
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1054
 
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1055
 
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1056
 
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
1057
 
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1058
 
 
 
888
        
1059
889
 
1060
890
precedence_global = 'option = global'
1061
891
precedence_branch = 'option = branch'
1068
898
"""
1069
899
 
1070
900
 
1071
 
class TestBranchConfigItems(tests.TestCaseInTempDir):
 
901
class TestBranchConfigItems(TestCaseInTempDir):
1072
902
 
1073
 
    def get_branch_config(self, global_config=None, location=None,
 
903
    def get_branch_config(self, global_config=None, location=None, 
1074
904
                          location_config=None, branch_data_config=None):
1075
905
        my_config = config.BranchConfig(FakeBranch(location))
1076
906
        if global_config is not None:
1090
920
        my_config = config.BranchConfig(branch)
1091
921
        self.assertEqual("Robert Collins <robertc@example.net>",
1092
922
                         my_config.username())
1093
 
        my_config.branch.control_files.files['email'] = "John"
1094
 
        my_config.set_user_option('email',
 
923
        branch.control_files.email = "John"
 
924
        my_config.set_user_option('email', 
1095
925
                                  "Robert Collins <robertc@example.org>")
1096
926
        self.assertEqual("John", my_config.username())
1097
 
        del my_config.branch.control_files.files['email']
 
927
        branch.control_files.email = None
1098
928
        self.assertEqual("Robert Collins <robertc@example.org>",
1099
929
                         my_config.username())
1100
930
 
1101
931
    def test_not_set_in_branch(self):
1102
932
        my_config = self.get_branch_config(sample_config_text)
 
933
        my_config.branch.control_files.email = None
1103
934
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1104
935
                         my_config._get_user_id())
1105
 
        my_config.branch.control_files.files['email'] = "John"
 
936
        my_config.branch.control_files.email = "John"
1106
937
        self.assertEqual("John", my_config._get_user_id())
1107
938
 
1108
939
    def test_BZR_EMAIL_OVERRIDES(self):
1111
942
        my_config = config.BranchConfig(branch)
1112
943
        self.assertEqual("Robert Collins <robertc@example.org>",
1113
944
                         my_config.username())
1114
 
 
 
945
    
1115
946
    def test_signatures_forced(self):
1116
947
        my_config = self.get_branch_config(
1117
948
            global_config=sample_always_signatures)
1161
992
    def test_config_precedence(self):
1162
993
        my_config = self.get_branch_config(global_config=precedence_global)
1163
994
        self.assertEqual(my_config.get_user_option('option'), 'global')
1164
 
        my_config = self.get_branch_config(global_config=precedence_global,
 
995
        my_config = self.get_branch_config(global_config=precedence_global, 
1165
996
                                      branch_data_config=precedence_branch)
1166
997
        self.assertEqual(my_config.get_user_option('option'), 'branch')
1167
 
        my_config = self.get_branch_config(global_config=precedence_global,
 
998
        my_config = self.get_branch_config(global_config=precedence_global, 
1168
999
                                      branch_data_config=precedence_branch,
1169
1000
                                      location_config=precedence_location)
1170
1001
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
1171
 
        my_config = self.get_branch_config(global_config=precedence_global,
 
1002
        my_config = self.get_branch_config(global_config=precedence_global, 
1172
1003
                                      branch_data_config=precedence_branch,
1173
1004
                                      location_config=precedence_location,
1174
1005
                                      location='http://example.com/specific')
1175
1006
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1176
1007
 
1177
 
    def test_get_mail_client(self):
1178
 
        config = self.get_branch_config()
1179
 
        client = config.get_mail_client()
1180
 
        self.assertIsInstance(client, mail_client.DefaultMail)
1181
 
 
1182
 
        # Specific clients
1183
 
        config.set_user_option('mail_client', 'evolution')
1184
 
        client = config.get_mail_client()
1185
 
        self.assertIsInstance(client, mail_client.Evolution)
1186
 
 
1187
 
        config.set_user_option('mail_client', 'kmail')
1188
 
        client = config.get_mail_client()
1189
 
        self.assertIsInstance(client, mail_client.KMail)
1190
 
 
1191
 
        config.set_user_option('mail_client', 'mutt')
1192
 
        client = config.get_mail_client()
1193
 
        self.assertIsInstance(client, mail_client.Mutt)
1194
 
 
1195
 
        config.set_user_option('mail_client', 'thunderbird')
1196
 
        client = config.get_mail_client()
1197
 
        self.assertIsInstance(client, mail_client.Thunderbird)
1198
 
 
1199
 
        # Generic options
1200
 
        config.set_user_option('mail_client', 'default')
1201
 
        client = config.get_mail_client()
1202
 
        self.assertIsInstance(client, mail_client.DefaultMail)
1203
 
 
1204
 
        config.set_user_option('mail_client', 'editor')
1205
 
        client = config.get_mail_client()
1206
 
        self.assertIsInstance(client, mail_client.Editor)
1207
 
 
1208
 
        config.set_user_option('mail_client', 'mapi')
1209
 
        client = config.get_mail_client()
1210
 
        self.assertIsInstance(client, mail_client.MAPIClient)
1211
 
 
1212
 
        config.set_user_option('mail_client', 'xdg-email')
1213
 
        client = config.get_mail_client()
1214
 
        self.assertIsInstance(client, mail_client.XDGEmail)
1215
 
 
1216
 
        config.set_user_option('mail_client', 'firebird')
1217
 
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1218
 
 
1219
 
 
1220
 
class TestMailAddressExtraction(tests.TestCase):
 
1008
 
 
1009
class TestMailAddressExtraction(TestCase):
1221
1010
 
1222
1011
    def test_extract_email_address(self):
1223
1012
        self.assertEqual('jane@test.com',
1225
1014
        self.assertRaises(errors.NoEmailInUsername,
1226
1015
                          config.extract_email_address, 'Jane Tester')
1227
1016
 
1228
 
    def test_parse_username(self):
1229
 
        self.assertEqual(('', 'jdoe@example.com'),
1230
 
                         config.parse_username('jdoe@example.com'))
1231
 
        self.assertEqual(('', 'jdoe@example.com'),
1232
 
                         config.parse_username('<jdoe@example.com>'))
1233
 
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1234
 
                         config.parse_username('John Doe <jdoe@example.com>'))
1235
 
        self.assertEqual(('John Doe', ''),
1236
 
                         config.parse_username('John Doe'))
1237
 
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1238
 
                         config.parse_username('John Doe jdoe@example.com'))
1239
1017
 
1240
 
class TestTreeConfig(tests.TestCaseWithTransport):
 
1018
class TestTreeConfig(TestCaseWithTransport):
1241
1019
 
1242
1020
    def test_get_value(self):
1243
1021
        """Test that retreiving a value from a section is possible"""
1263
1041
        self.assertEqual(value, 'value3-top')
1264
1042
        value = tree_config.get_option('key3', 'SECTION')
1265
1043
        self.assertEqual(value, 'value3-section')
1266
 
 
1267
 
 
1268
 
class TestTransportConfig(tests.TestCaseWithTransport):
1269
 
 
1270
 
    def test_get_value(self):
1271
 
        """Test that retreiving a value from a section is possible"""
1272
 
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1273
 
                                               'control.conf')
1274
 
        bzrdir_config.set_option('value', 'key', 'SECTION')
1275
 
        bzrdir_config.set_option('value2', 'key2')
1276
 
        bzrdir_config.set_option('value3-top', 'key3')
1277
 
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1278
 
        value = bzrdir_config.get_option('key', 'SECTION')
1279
 
        self.assertEqual(value, 'value')
1280
 
        value = bzrdir_config.get_option('key2')
1281
 
        self.assertEqual(value, 'value2')
1282
 
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1283
 
        value = bzrdir_config.get_option('non-existant', 'SECTION')
1284
 
        self.assertEqual(value, None)
1285
 
        value = bzrdir_config.get_option('non-existant', default='default')
1286
 
        self.assertEqual(value, 'default')
1287
 
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1288
 
        value = bzrdir_config.get_option('key2', 'NOSECTION',
1289
 
                                         default='default')
1290
 
        self.assertEqual(value, 'default')
1291
 
        value = bzrdir_config.get_option('key3')
1292
 
        self.assertEqual(value, 'value3-top')
1293
 
        value = bzrdir_config.get_option('key3', 'SECTION')
1294
 
        self.assertEqual(value, 'value3-section')
1295
 
 
1296
 
    def test_set_unset_default_stack_on(self):
1297
 
        my_dir = self.make_bzrdir('.')
1298
 
        bzrdir_config = config.BzrDirConfig(my_dir)
1299
 
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1300
 
        bzrdir_config.set_default_stack_on('Foo')
1301
 
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1302
 
                         'default_stack_on'))
1303
 
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1304
 
        bzrdir_config.set_default_stack_on(None)
1305
 
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1306
 
 
1307
 
 
1308
 
class TestAuthenticationConfigFile(tests.TestCase):
1309
 
    """Test the authentication.conf file matching"""
1310
 
 
1311
 
    def _got_user_passwd(self, expected_user, expected_password,
1312
 
                         config, *args, **kwargs):
1313
 
        credentials = config.get_credentials(*args, **kwargs)
1314
 
        if credentials is None:
1315
 
            user = None
1316
 
            password = None
1317
 
        else:
1318
 
            user = credentials['user']
1319
 
            password = credentials['password']
1320
 
        self.assertEquals(expected_user, user)
1321
 
        self.assertEquals(expected_password, password)
1322
 
 
1323
 
    def test_empty_config(self):
1324
 
        conf = config.AuthenticationConfig(_file=StringIO())
1325
 
        self.assertEquals({}, conf._get_config())
1326
 
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1327
 
 
1328
 
    def test_missing_auth_section_header(self):
1329
 
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1330
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1331
 
 
1332
 
    def test_auth_section_header_not_closed(self):
1333
 
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1334
 
        self.assertRaises(errors.ParseConfigError, conf._get_config)
1335
 
 
1336
 
    def test_auth_value_not_boolean(self):
1337
 
        conf = config.AuthenticationConfig(_file=StringIO(
1338
 
                """[broken]
1339
 
scheme=ftp
1340
 
user=joe
1341
 
verify_certificates=askme # Error: Not a boolean
1342
 
"""))
1343
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1344
 
 
1345
 
    def test_auth_value_not_int(self):
1346
 
        conf = config.AuthenticationConfig(_file=StringIO(
1347
 
                """[broken]
1348
 
scheme=ftp
1349
 
user=joe
1350
 
port=port # Error: Not an int
1351
 
"""))
1352
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1353
 
 
1354
 
    def test_unknown_password_encoding(self):
1355
 
        conf = config.AuthenticationConfig(_file=StringIO(
1356
 
                """[broken]
1357
 
scheme=ftp
1358
 
user=joe
1359
 
password_encoding=unknown
1360
 
"""))
1361
 
        self.assertRaises(ValueError, conf.get_password,
1362
 
                          'ftp', 'foo.net', 'joe')
1363
 
 
1364
 
    def test_credentials_for_scheme_host(self):
1365
 
        conf = config.AuthenticationConfig(_file=StringIO(
1366
 
                """# Identity on foo.net
1367
 
[ftp definition]
1368
 
scheme=ftp
1369
 
host=foo.net
1370
 
user=joe
1371
 
password=secret-pass
1372
 
"""))
1373
 
        # Basic matching
1374
 
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1375
 
        # different scheme
1376
 
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1377
 
        # different host
1378
 
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1379
 
 
1380
 
    def test_credentials_for_host_port(self):
1381
 
        conf = config.AuthenticationConfig(_file=StringIO(
1382
 
                """# Identity on foo.net
1383
 
[ftp definition]
1384
 
scheme=ftp
1385
 
port=10021
1386
 
host=foo.net
1387
 
user=joe
1388
 
password=secret-pass
1389
 
"""))
1390
 
        # No port
1391
 
        self._got_user_passwd('joe', 'secret-pass',
1392
 
                              conf, 'ftp', 'foo.net', port=10021)
1393
 
        # different port
1394
 
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1395
 
 
1396
 
    def test_for_matching_host(self):
1397
 
        conf = config.AuthenticationConfig(_file=StringIO(
1398
 
                """# Identity on foo.net
1399
 
[sourceforge]
1400
 
scheme=bzr
1401
 
host=bzr.sf.net
1402
 
user=joe
1403
 
password=joepass
1404
 
[sourceforge domain]
1405
 
scheme=bzr
1406
 
host=.bzr.sf.net
1407
 
user=georges
1408
 
password=bendover
1409
 
"""))
1410
 
        # matching domain
1411
 
        self._got_user_passwd('georges', 'bendover',
1412
 
                              conf, 'bzr', 'foo.bzr.sf.net')
1413
 
        # phishing attempt
1414
 
        self._got_user_passwd(None, None,
1415
 
                              conf, 'bzr', 'bbzr.sf.net')
1416
 
 
1417
 
    def test_for_matching_host_None(self):
1418
 
        conf = config.AuthenticationConfig(_file=StringIO(
1419
 
                """# Identity on foo.net
1420
 
[catchup bzr]
1421
 
scheme=bzr
1422
 
user=joe
1423
 
password=joepass
1424
 
[DEFAULT]
1425
 
user=georges
1426
 
password=bendover
1427
 
"""))
1428
 
        # match no host
1429
 
        self._got_user_passwd('joe', 'joepass',
1430
 
                              conf, 'bzr', 'quux.net')
1431
 
        # no host but different scheme
1432
 
        self._got_user_passwd('georges', 'bendover',
1433
 
                              conf, 'ftp', 'quux.net')
1434
 
 
1435
 
    def test_credentials_for_path(self):
1436
 
        conf = config.AuthenticationConfig(_file=StringIO(
1437
 
                """
1438
 
[http dir1]
1439
 
scheme=http
1440
 
host=bar.org
1441
 
path=/dir1
1442
 
user=jim
1443
 
password=jimpass
1444
 
[http dir2]
1445
 
scheme=http
1446
 
host=bar.org
1447
 
path=/dir2
1448
 
user=georges
1449
 
password=bendover
1450
 
"""))
1451
 
        # no path no dice
1452
 
        self._got_user_passwd(None, None,
1453
 
                              conf, 'http', host='bar.org', path='/dir3')
1454
 
        # matching path
1455
 
        self._got_user_passwd('georges', 'bendover',
1456
 
                              conf, 'http', host='bar.org', path='/dir2')
1457
 
        # matching subdir
1458
 
        self._got_user_passwd('jim', 'jimpass',
1459
 
                              conf, 'http', host='bar.org',path='/dir1/subdir')
1460
 
 
1461
 
    def test_credentials_for_user(self):
1462
 
        conf = config.AuthenticationConfig(_file=StringIO(
1463
 
                """
1464
 
[with user]
1465
 
scheme=http
1466
 
host=bar.org
1467
 
user=jim
1468
 
password=jimpass
1469
 
"""))
1470
 
        # Get user
1471
 
        self._got_user_passwd('jim', 'jimpass',
1472
 
                              conf, 'http', 'bar.org')
1473
 
        # Get same user
1474
 
        self._got_user_passwd('jim', 'jimpass',
1475
 
                              conf, 'http', 'bar.org', user='jim')
1476
 
        # Don't get a different user if one is specified
1477
 
        self._got_user_passwd(None, None,
1478
 
                              conf, 'http', 'bar.org', user='georges')
1479
 
 
1480
 
    def test_credentials_for_user_without_password(self):
1481
 
        conf = config.AuthenticationConfig(_file=StringIO(
1482
 
                """
1483
 
[without password]
1484
 
scheme=http
1485
 
host=bar.org
1486
 
user=jim
1487
 
"""))
1488
 
        # Get user but no password
1489
 
        self._got_user_passwd('jim', None,
1490
 
                              conf, 'http', 'bar.org')
1491
 
 
1492
 
    def test_verify_certificates(self):
1493
 
        conf = config.AuthenticationConfig(_file=StringIO(
1494
 
                """
1495
 
[self-signed]
1496
 
scheme=https
1497
 
host=bar.org
1498
 
user=jim
1499
 
password=jimpass
1500
 
verify_certificates=False
1501
 
[normal]
1502
 
scheme=https
1503
 
host=foo.net
1504
 
user=georges
1505
 
password=bendover
1506
 
"""))
1507
 
        credentials = conf.get_credentials('https', 'bar.org')
1508
 
        self.assertEquals(False, credentials.get('verify_certificates'))
1509
 
        credentials = conf.get_credentials('https', 'foo.net')
1510
 
        self.assertEquals(True, credentials.get('verify_certificates'))
1511
 
 
1512
 
 
1513
 
class TestAuthenticationStorage(tests.TestCaseInTempDir):
1514
 
 
1515
 
    def test_set_credentials(self):
1516
 
        conf = config.AuthenticationConfig()
1517
 
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
1518
 
        99, path='/foo', verify_certificates=False, realm='realm')
1519
 
        credentials = conf.get_credentials(host='host', scheme='scheme',
1520
 
                                           port=99, path='/foo',
1521
 
                                           realm='realm')
1522
 
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
1523
 
                       'verify_certificates': False, 'scheme': 'scheme', 
1524
 
                       'host': 'host', 'port': 99, 'path': '/foo', 
1525
 
                       'realm': 'realm'}
1526
 
        self.assertEqual(CREDENTIALS, credentials)
1527
 
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
1528
 
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
1529
 
        self.assertEqual(CREDENTIALS, credentials_from_disk)
1530
 
 
1531
 
    def test_reset_credentials_different_name(self):
1532
 
        conf = config.AuthenticationConfig()
1533
 
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
1534
 
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
1535
 
        self.assertIs(None, conf._get_config().get('name'))
1536
 
        credentials = conf.get_credentials(host='host', scheme='scheme')
1537
 
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
1538
 
                       'password', 'verify_certificates': True, 
1539
 
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
1540
 
                       'path': None, 'realm': None}
1541
 
        self.assertEqual(CREDENTIALS, credentials)
1542
 
 
1543
 
 
1544
 
class TestAuthenticationConfig(tests.TestCase):
1545
 
    """Test AuthenticationConfig behaviour"""
1546
 
 
1547
 
    def _check_default_password_prompt(self, expected_prompt_format, scheme,
1548
 
                                       host=None, port=None, realm=None,
1549
 
                                       path=None):
1550
 
        if host is None:
1551
 
            host = 'bar.org'
1552
 
        user, password = 'jim', 'precious'
1553
 
        expected_prompt = expected_prompt_format % {
1554
 
            'scheme': scheme, 'host': host, 'port': port,
1555
 
            'user': user, 'realm': realm}
1556
 
 
1557
 
        stdout = tests.StringIOWrapper()
1558
 
        stderr = tests.StringIOWrapper()
1559
 
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
1560
 
                                            stdout=stdout, stderr=stderr)
1561
 
        # We use an empty conf so that the user is always prompted
1562
 
        conf = config.AuthenticationConfig()
1563
 
        self.assertEquals(password,
1564
 
                          conf.get_password(scheme, host, user, port=port,
1565
 
                                            realm=realm, path=path))
1566
 
        self.assertEquals(expected_prompt, stderr.getvalue())
1567
 
        self.assertEquals('', stdout.getvalue())
1568
 
 
1569
 
    def _check_default_username_prompt(self, expected_prompt_format, scheme,
1570
 
                                       host=None, port=None, realm=None,
1571
 
                                       path=None):
1572
 
        if host is None:
1573
 
            host = 'bar.org'
1574
 
        username = 'jim'
1575
 
        expected_prompt = expected_prompt_format % {
1576
 
            'scheme': scheme, 'host': host, 'port': port,
1577
 
            'realm': realm}
1578
 
        stdout = tests.StringIOWrapper()
1579
 
        stderr = tests.StringIOWrapper()
1580
 
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
1581
 
                                            stdout=stdout, stderr=stderr)
1582
 
        # We use an empty conf so that the user is always prompted
1583
 
        conf = config.AuthenticationConfig()
1584
 
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
1585
 
                          realm=realm, path=path, ask=True))
1586
 
        self.assertEquals(expected_prompt, stderr.getvalue())
1587
 
        self.assertEquals('', stdout.getvalue())
1588
 
 
1589
 
    def test_username_defaults_prompts(self):
1590
 
        # HTTP prompts can't be tested here, see test_http.py
1591
 
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
1592
 
        self._check_default_username_prompt(
1593
 
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
1594
 
        self._check_default_username_prompt(
1595
 
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1596
 
 
1597
 
    def test_username_default_no_prompt(self):
1598
 
        conf = config.AuthenticationConfig()
1599
 
        self.assertEquals(None,
1600
 
            conf.get_user('ftp', 'example.com'))
1601
 
        self.assertEquals("explicitdefault",
1602
 
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
1603
 
 
1604
 
    def test_password_default_prompts(self):
1605
 
        # HTTP prompts can't be tested here, see test_http.py
1606
 
        self._check_default_password_prompt(
1607
 
            'FTP %(user)s@%(host)s password: ', 'ftp')
1608
 
        self._check_default_password_prompt(
1609
 
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
1610
 
        self._check_default_password_prompt(
1611
 
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
1612
 
        # SMTP port handling is a bit special (it's handled if embedded in the
1613
 
        # host too)
1614
 
        # FIXME: should we: forbid that, extend it to other schemes, leave
1615
 
        # things as they are that's fine thank you ?
1616
 
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
1617
 
                                            'smtp')
1618
 
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
1619
 
                                            'smtp', host='bar.org:10025')
1620
 
        self._check_default_password_prompt(
1621
 
            'SMTP %(user)s@%(host)s:%(port)d password: ',
1622
 
            'smtp', port=10025)
1623
 
 
1624
 
    def test_ssh_password_emits_warning(self):
1625
 
        conf = config.AuthenticationConfig(_file=StringIO(
1626
 
                """
1627
 
[ssh with password]
1628
 
scheme=ssh
1629
 
host=bar.org
1630
 
user=jim
1631
 
password=jimpass
1632
 
"""))
1633
 
        entered_password = 'typed-by-hand'
1634
 
        stdout = tests.StringIOWrapper()
1635
 
        stderr = tests.StringIOWrapper()
1636
 
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
1637
 
                                            stdout=stdout, stderr=stderr)
1638
 
 
1639
 
        # Since the password defined in the authentication config is ignored,
1640
 
        # the user is prompted
1641
 
        self.assertEquals(entered_password,
1642
 
                          conf.get_password('ssh', 'bar.org', user='jim'))
1643
 
        self.assertContainsRe(
1644
 
            self.get_log(),
1645
 
            'password ignored in section \[ssh with password\]')
1646
 
 
1647
 
    def test_ssh_without_password_doesnt_emit_warning(self):
1648
 
        conf = config.AuthenticationConfig(_file=StringIO(
1649
 
                """
1650
 
[ssh with password]
1651
 
scheme=ssh
1652
 
host=bar.org
1653
 
user=jim
1654
 
"""))
1655
 
        entered_password = 'typed-by-hand'
1656
 
        stdout = tests.StringIOWrapper()
1657
 
        stderr = tests.StringIOWrapper()
1658
 
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
1659
 
                                            stdout=stdout,
1660
 
                                            stderr=stderr)
1661
 
 
1662
 
        # Since the password defined in the authentication config is ignored,
1663
 
        # the user is prompted
1664
 
        self.assertEquals(entered_password,
1665
 
                          conf.get_password('ssh', 'bar.org', user='jim'))
1666
 
        # No warning shoud be emitted since there is no password. We are only
1667
 
        # providing "user".
1668
 
        self.assertNotContainsRe(
1669
 
            self.get_log(),
1670
 
            'password ignored in section \[ssh with password\]')
1671
 
 
1672
 
    def test_uses_fallback_stores(self):
1673
 
        self._old_cs_registry = config.credential_store_registry
1674
 
        def restore():
1675
 
            config.credential_store_registry = self._old_cs_registry
1676
 
        self.addCleanup(restore)
1677
 
        config.credential_store_registry = config.CredentialStoreRegistry()
1678
 
        store = StubCredentialStore()
1679
 
        store.add_credentials("http", "example.com", "joe", "secret")
1680
 
        config.credential_store_registry.register("stub", store, fallback=True)
1681
 
        conf = config.AuthenticationConfig(_file=StringIO())
1682
 
        creds = conf.get_credentials("http", "example.com")
1683
 
        self.assertEquals("joe", creds["user"])
1684
 
        self.assertEquals("secret", creds["password"])
1685
 
 
1686
 
 
1687
 
class StubCredentialStore(config.CredentialStore):
1688
 
 
1689
 
    def __init__(self):
1690
 
        self._username = {}
1691
 
        self._password = {}
1692
 
 
1693
 
    def add_credentials(self, scheme, host, user, password=None):
1694
 
        self._username[(scheme, host)] = user
1695
 
        self._password[(scheme, host)] = password
1696
 
 
1697
 
    def get_credentials(self, scheme, host, port=None, user=None,
1698
 
        path=None, realm=None):
1699
 
        key = (scheme, host)
1700
 
        if not key in self._username:
1701
 
            return None
1702
 
        return { "scheme": scheme, "host": host, "port": port,
1703
 
                "user": self._username[key], "password": self._password[key]}
1704
 
 
1705
 
 
1706
 
class CountingCredentialStore(config.CredentialStore):
1707
 
 
1708
 
    def __init__(self):
1709
 
        self._calls = 0
1710
 
 
1711
 
    def get_credentials(self, scheme, host, port=None, user=None,
1712
 
        path=None, realm=None):
1713
 
        self._calls += 1
1714
 
        return None
1715
 
 
1716
 
 
1717
 
class TestCredentialStoreRegistry(tests.TestCase):
1718
 
 
1719
 
    def _get_cs_registry(self):
1720
 
        return config.credential_store_registry
1721
 
 
1722
 
    def test_default_credential_store(self):
1723
 
        r = self._get_cs_registry()
1724
 
        default = r.get_credential_store(None)
1725
 
        self.assertIsInstance(default, config.PlainTextCredentialStore)
1726
 
 
1727
 
    def test_unknown_credential_store(self):
1728
 
        r = self._get_cs_registry()
1729
 
        # It's hard to imagine someone creating a credential store named
1730
 
        # 'unknown' so we use that as an never registered key.
1731
 
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
1732
 
 
1733
 
    def test_fallback_none_registered(self):
1734
 
        r = config.CredentialStoreRegistry()
1735
 
        self.assertEquals(None,
1736
 
                          r.get_fallback_credentials("http", "example.com"))
1737
 
 
1738
 
    def test_register(self):
1739
 
        r = config.CredentialStoreRegistry()
1740
 
        r.register("stub", StubCredentialStore(), fallback=False)
1741
 
        r.register("another", StubCredentialStore(), fallback=True)
1742
 
        self.assertEquals(["another", "stub"], r.keys())
1743
 
 
1744
 
    def test_register_lazy(self):
1745
 
        r = config.CredentialStoreRegistry()
1746
 
        r.register_lazy("stub", "bzrlib.tests.test_config",
1747
 
                        "StubCredentialStore", fallback=False)
1748
 
        self.assertEquals(["stub"], r.keys())
1749
 
        self.assertIsInstance(r.get_credential_store("stub"),
1750
 
                              StubCredentialStore)
1751
 
 
1752
 
    def test_is_fallback(self):
1753
 
        r = config.CredentialStoreRegistry()
1754
 
        r.register("stub1", None, fallback=False)
1755
 
        r.register("stub2", None, fallback=True)
1756
 
        self.assertEquals(False, r.is_fallback("stub1"))
1757
 
        self.assertEquals(True, r.is_fallback("stub2"))
1758
 
 
1759
 
    def test_no_fallback(self):
1760
 
        r = config.CredentialStoreRegistry()
1761
 
        store = CountingCredentialStore()
1762
 
        r.register("count", store, fallback=False)
1763
 
        self.assertEquals(None,
1764
 
                          r.get_fallback_credentials("http", "example.com"))
1765
 
        self.assertEquals(0, store._calls)
1766
 
 
1767
 
    def test_fallback_credentials(self):
1768
 
        r = config.CredentialStoreRegistry()
1769
 
        store = StubCredentialStore()
1770
 
        store.add_credentials("http", "example.com",
1771
 
                              "somebody", "geheim")
1772
 
        r.register("stub", store, fallback=True)
1773
 
        creds = r.get_fallback_credentials("http", "example.com")
1774
 
        self.assertEquals("somebody", creds["user"])
1775
 
        self.assertEquals("geheim", creds["password"])
1776
 
 
1777
 
    def test_fallback_first_wins(self):
1778
 
        r = config.CredentialStoreRegistry()
1779
 
        stub1 = StubCredentialStore()
1780
 
        stub1.add_credentials("http", "example.com",
1781
 
                              "somebody", "stub1")
1782
 
        r.register("stub1", stub1, fallback=True)
1783
 
        stub2 = StubCredentialStore()
1784
 
        stub2.add_credentials("http", "example.com",
1785
 
                              "somebody", "stub2")
1786
 
        r.register("stub2", stub1, fallback=True)
1787
 
        creds = r.get_fallback_credentials("http", "example.com")
1788
 
        self.assertEquals("somebody", creds["user"])
1789
 
        self.assertEquals("stub1", creds["password"])
1790
 
 
1791
 
 
1792
 
class TestPlainTextCredentialStore(tests.TestCase):
1793
 
 
1794
 
    def test_decode_password(self):
1795
 
        r = config.credential_store_registry
1796
 
        plain_text = r.get_credential_store()
1797
 
        decoded = plain_text.decode_password(dict(password='secret'))
1798
 
        self.assertEquals('secret', decoded)
1799
 
 
1800
 
 
1801
 
# FIXME: Once we have a way to declare authentication to all test servers, we
1802
 
# can implement generic tests.
1803
 
# test_user_password_in_url
1804
 
# test_user_in_url_password_from_config
1805
 
# test_user_in_url_password_prompted
1806
 
# test_user_in_config
1807
 
# test_user_getpass.getuser
1808
 
# test_user_prompted ?
1809
 
class TestAuthenticationRing(tests.TestCaseWithTransport):
1810
 
    pass