1
# Copyright (C) 2005, 2006, 2008, 2009 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Tests for finding and reading the bzr config file[s]."""
18
# import system imports here
19
from cStringIO import StringIO
23
#import bzrlib specific imports here
37
from bzrlib.util.configobj import configobj
40
sample_long_alias="log -r-15..-1 --line"
41
sample_config_text = u"""
43
email=Erik B\u00e5gfors <erik@bagfors.nu>
45
gpg_signing_command=gnome-gpg
47
user_global_option=something
50
ll=""" + sample_long_alias + "\n"
53
sample_always_signatures = """
55
check_signatures=ignore
56
create_signatures=always
59
sample_ignore_signatures = """
61
check_signatures=require
62
create_signatures=never
65
sample_maybe_signatures = """
67
check_signatures=ignore
68
create_signatures=when-required
71
sample_branches_text = """
72
[http://www.example.com]
74
email=Robert Collins <robertc@example.org>
75
normal_option = normal
76
appendpath_option = append
77
appendpath_option:policy = appendpath
78
norecurse_option = norecurse
79
norecurse_option:policy = norecurse
80
[http://www.example.com/ignoreparent]
81
# different project: ignore parent dir config
83
[http://www.example.com/norecurse]
84
# configuration items that only apply to this dir
86
normal_option = norecurse
87
[http://www.example.com/dir]
88
appendpath_option = normal
90
check_signatures=require
91
# test trailing / matching with no children
93
check_signatures=check-available
94
gpg_signing_command=false
95
user_local_option=local
96
# test trailing / matching
98
#subdirs will match but not the parent
100
check_signatures=ignore
101
post_commit=bzrlib.tests.test_config.post_commit
102
#testing explicit beats globs
106
class InstrumentedConfigObj(object):
107
"""A config obj look-enough-alike to record calls made to it."""
109
def __contains__(self, thing):
110
self._calls.append(('__contains__', thing))
113
def __getitem__(self, key):
114
self._calls.append(('__getitem__', key))
117
def __init__(self, input, encoding=None):
118
self._calls = [('__init__', input, encoding)]
120
def __setitem__(self, key, value):
121
self._calls.append(('__setitem__', key, value))
123
def __delitem__(self, key):
124
self._calls.append(('__delitem__', key))
127
self._calls.append(('keys',))
130
def write(self, arg):
131
self._calls.append(('write',))
133
def as_bool(self, value):
134
self._calls.append(('as_bool', value))
137
def get_value(self, section, name):
138
self._calls.append(('get_value', section, name))
142
class FakeBranch(object):
144
def __init__(self, base=None, user_id=None):
146
self.base = "http://example.com/branches/demo"
149
self._transport = self.control_files = \
150
FakeControlFilesAndTransport(user_id=user_id)
152
def _get_config(self):
153
return config.TransportConfig(self._transport, 'branch.conf')
155
def lock_write(self):
162
class FakeControlFilesAndTransport(object):
164
def __init__(self, user_id=None):
167
self.files['email'] = user_id
168
self._transport = self
170
def get_utf8(self, filename):
172
raise AssertionError("get_utf8 should no longer be used")
174
def get(self, filename):
177
return StringIO(self.files[filename])
179
raise errors.NoSuchFile(filename)
181
def get_bytes(self, filename):
184
return self.files[filename]
186
raise errors.NoSuchFile(filename)
188
def put(self, filename, fileobj):
189
self.files[filename] = fileobj.read()
191
def put_file(self, filename, fileobj):
192
return self.put(filename, fileobj)
195
class InstrumentedConfig(config.Config):
196
"""An instrumented config that supplies stubs for template methods."""
199
super(InstrumentedConfig, self).__init__()
201
self._signatures = config.CHECK_NEVER
203
def _get_user_id(self):
204
self._calls.append('_get_user_id')
205
return "Robert Collins <robert.collins@example.org>"
207
def _get_signature_checking(self):
208
self._calls.append('_get_signature_checking')
209
return self._signatures
212
bool_config = """[DEFAULT]
221
class TestConfigObj(tests.TestCase):
223
def test_get_bool(self):
224
co = config.ConfigObj(StringIO(bool_config))
225
self.assertIs(co.get_bool('DEFAULT', 'active'), True)
226
self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
227
self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
228
self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
230
def test_hash_sign_in_value(self):
232
Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
233
treated as comments when read in again. (#86838)
235
co = config.ConfigObj()
236
co['test'] = 'foo#bar'
238
self.assertEqual(lines, ['test = "foo#bar"'])
239
co2 = config.ConfigObj(lines)
240
self.assertEqual(co2['test'], 'foo#bar')
243
erroneous_config = """[section] # line 1
246
whocares=notme # line 4
250
class TestConfigObjErrors(tests.TestCase):
252
def test_duplicate_section_name_error_line(self):
254
co = configobj.ConfigObj(StringIO(erroneous_config),
256
except config.configobj.DuplicateError, e:
257
self.assertEqual(3, e.line_number)
259
self.fail('Error in config file not detected')
262
class TestConfig(tests.TestCase):
264
def test_constructs(self):
267
def test_no_default_editor(self):
268
self.assertRaises(NotImplementedError, config.Config().get_editor)
270
def test_user_email(self):
271
my_config = InstrumentedConfig()
272
self.assertEqual('robert.collins@example.org', my_config.user_email())
273
self.assertEqual(['_get_user_id'], my_config._calls)
275
def test_username(self):
276
my_config = InstrumentedConfig()
277
self.assertEqual('Robert Collins <robert.collins@example.org>',
278
my_config.username())
279
self.assertEqual(['_get_user_id'], my_config._calls)
281
def test_signatures_default(self):
282
my_config = config.Config()
283
self.assertFalse(my_config.signature_needed())
284
self.assertEqual(config.CHECK_IF_POSSIBLE,
285
my_config.signature_checking())
286
self.assertEqual(config.SIGN_WHEN_REQUIRED,
287
my_config.signing_policy())
289
def test_signatures_template_method(self):
290
my_config = InstrumentedConfig()
291
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
292
self.assertEqual(['_get_signature_checking'], my_config._calls)
294
def test_signatures_template_method_none(self):
295
my_config = InstrumentedConfig()
296
my_config._signatures = None
297
self.assertEqual(config.CHECK_IF_POSSIBLE,
298
my_config.signature_checking())
299
self.assertEqual(['_get_signature_checking'], my_config._calls)
301
def test_gpg_signing_command_default(self):
302
my_config = config.Config()
303
self.assertEqual('gpg', my_config.gpg_signing_command())
305
def test_get_user_option_default(self):
306
my_config = config.Config()
307
self.assertEqual(None, my_config.get_user_option('no_option'))
309
def test_post_commit_default(self):
310
my_config = config.Config()
311
self.assertEqual(None, my_config.post_commit())
313
def test_log_format_default(self):
314
my_config = config.Config()
315
self.assertEqual('long', my_config.log_format())
318
class TestConfigPath(tests.TestCase):
321
super(TestConfigPath, self).setUp()
322
os.environ['HOME'] = '/home/bogus'
323
if sys.platform == 'win32':
324
os.environ['BZR_HOME'] = \
325
r'C:\Documents and Settings\bogus\Application Data'
327
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
329
self.bzr_home = '/home/bogus/.bazaar'
331
def test_config_dir(self):
332
self.assertEqual(config.config_dir(), self.bzr_home)
334
def test_config_filename(self):
335
self.assertEqual(config.config_filename(),
336
self.bzr_home + '/bazaar.conf')
338
def test_branches_config_filename(self):
339
self.assertEqual(config.branches_config_filename(),
340
self.bzr_home + '/branches.conf')
342
def test_locations_config_filename(self):
343
self.assertEqual(config.locations_config_filename(),
344
self.bzr_home + '/locations.conf')
346
def test_authentication_config_filename(self):
347
self.assertEqual(config.authentication_config_filename(),
348
self.bzr_home + '/authentication.conf')
351
class TestIniConfig(tests.TestCase):
353
def test_contructs(self):
354
my_config = config.IniBasedConfig("nothing")
356
def test_from_fp(self):
357
config_file = StringIO(sample_config_text.encode('utf-8'))
358
my_config = config.IniBasedConfig(None)
360
isinstance(my_config._get_parser(file=config_file),
361
configobj.ConfigObj))
363
def test_cached(self):
364
config_file = StringIO(sample_config_text.encode('utf-8'))
365
my_config = config.IniBasedConfig(None)
366
parser = my_config._get_parser(file=config_file)
367
self.failUnless(my_config._get_parser() is parser)
370
class TestGetConfig(tests.TestCase):
372
def test_constructs(self):
373
my_config = config.GlobalConfig()
375
def test_calls_read_filenames(self):
376
# replace the class that is constructed, to check its parameters
377
oldparserclass = config.ConfigObj
378
config.ConfigObj = InstrumentedConfigObj
379
my_config = config.GlobalConfig()
381
parser = my_config._get_parser()
383
config.ConfigObj = oldparserclass
384
self.failUnless(isinstance(parser, InstrumentedConfigObj))
385
self.assertEqual(parser._calls, [('__init__', config.config_filename(),
389
class TestBranchConfig(tests.TestCaseWithTransport):
391
def test_constructs(self):
392
branch = FakeBranch()
393
my_config = config.BranchConfig(branch)
394
self.assertRaises(TypeError, config.BranchConfig)
396
def test_get_location_config(self):
397
branch = FakeBranch()
398
my_config = config.BranchConfig(branch)
399
location_config = my_config._get_location_config()
400
self.assertEqual(branch.base, location_config.location)
401
self.failUnless(location_config is my_config._get_location_config())
403
def test_get_config(self):
404
"""The Branch.get_config method works properly"""
405
b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
406
my_config = b.get_config()
407
self.assertIs(my_config.get_user_option('wacky'), None)
408
my_config.set_user_option('wacky', 'unlikely')
409
self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
411
# Ensure we get the same thing if we start again
412
b2 = branch.Branch.open('.')
413
my_config2 = b2.get_config()
414
self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
416
def test_has_explicit_nickname(self):
417
b = self.make_branch('.')
418
self.assertFalse(b.get_config().has_explicit_nickname())
420
self.assertTrue(b.get_config().has_explicit_nickname())
422
def test_config_url(self):
423
"""The Branch.get_config will use section that uses a local url"""
424
branch = self.make_branch('branch')
425
self.assertEqual('branch', branch.nick)
427
locations = config.locations_config_filename()
428
config.ensure_config_dir_exists()
429
local_url = urlutils.local_path_to_url('branch')
430
open(locations, 'wb').write('[%s]\nnickname = foobar'
432
self.assertEqual('foobar', branch.nick)
434
def test_config_local_path(self):
435
"""The Branch.get_config will use a local system path"""
436
branch = self.make_branch('branch')
437
self.assertEqual('branch', branch.nick)
439
locations = config.locations_config_filename()
440
config.ensure_config_dir_exists()
441
open(locations, 'wb').write('[%s/branch]\nnickname = barry'
442
% (osutils.getcwd().encode('utf8'),))
443
self.assertEqual('barry', branch.nick)
445
def test_config_creates_local(self):
446
"""Creating a new entry in config uses a local path."""
447
branch = self.make_branch('branch', format='knit')
448
branch.set_push_location('http://foobar')
449
locations = config.locations_config_filename()
450
local_path = osutils.getcwd().encode('utf8')
451
# Surprisingly ConfigObj doesn't create a trailing newline
452
self.check_file_contents(locations,
454
'push_location = http://foobar\n'
455
'push_location:policy = norecurse\n'
458
def test_autonick_urlencoded(self):
459
b = self.make_branch('!repo')
460
self.assertEqual('!repo', b.get_config().get_nickname())
462
def test_warn_if_masked(self):
463
_warning = trace.warning
466
warnings.append(args[0] % args[1:])
468
def set_option(store, warn_masked=True):
470
conf.set_user_option('example_option', repr(store), store=store,
471
warn_masked=warn_masked)
472
def assertWarning(warning):
474
self.assertEqual(0, len(warnings))
476
self.assertEqual(1, len(warnings))
477
self.assertEqual(warning, warnings[0])
478
trace.warning = warning
480
branch = self.make_branch('.')
481
conf = branch.get_config()
482
set_option(config.STORE_GLOBAL)
484
set_option(config.STORE_BRANCH)
486
set_option(config.STORE_GLOBAL)
487
assertWarning('Value "4" is masked by "3" from branch.conf')
488
set_option(config.STORE_GLOBAL, warn_masked=False)
490
set_option(config.STORE_LOCATION)
492
set_option(config.STORE_BRANCH)
493
assertWarning('Value "3" is masked by "0" from locations.conf')
494
set_option(config.STORE_BRANCH, warn_masked=False)
497
trace.warning = _warning
500
class TestGlobalConfigItems(tests.TestCase):
502
def test_user_id(self):
503
config_file = StringIO(sample_config_text.encode('utf-8'))
504
my_config = config.GlobalConfig()
505
my_config._parser = my_config._get_parser(file=config_file)
506
self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
507
my_config._get_user_id())
509
def test_absent_user_id(self):
510
config_file = StringIO("")
511
my_config = config.GlobalConfig()
512
my_config._parser = my_config._get_parser(file=config_file)
513
self.assertEqual(None, my_config._get_user_id())
515
def test_configured_editor(self):
516
config_file = StringIO(sample_config_text.encode('utf-8'))
517
my_config = config.GlobalConfig()
518
my_config._parser = my_config._get_parser(file=config_file)
519
self.assertEqual("vim", my_config.get_editor())
521
def test_signatures_always(self):
522
config_file = StringIO(sample_always_signatures)
523
my_config = config.GlobalConfig()
524
my_config._parser = my_config._get_parser(file=config_file)
525
self.assertEqual(config.CHECK_NEVER,
526
my_config.signature_checking())
527
self.assertEqual(config.SIGN_ALWAYS,
528
my_config.signing_policy())
529
self.assertEqual(True, my_config.signature_needed())
531
def test_signatures_if_possible(self):
532
config_file = StringIO(sample_maybe_signatures)
533
my_config = config.GlobalConfig()
534
my_config._parser = my_config._get_parser(file=config_file)
535
self.assertEqual(config.CHECK_NEVER,
536
my_config.signature_checking())
537
self.assertEqual(config.SIGN_WHEN_REQUIRED,
538
my_config.signing_policy())
539
self.assertEqual(False, my_config.signature_needed())
541
def test_signatures_ignore(self):
542
config_file = StringIO(sample_ignore_signatures)
543
my_config = config.GlobalConfig()
544
my_config._parser = my_config._get_parser(file=config_file)
545
self.assertEqual(config.CHECK_ALWAYS,
546
my_config.signature_checking())
547
self.assertEqual(config.SIGN_NEVER,
548
my_config.signing_policy())
549
self.assertEqual(False, my_config.signature_needed())
551
def _get_sample_config(self):
552
config_file = StringIO(sample_config_text.encode('utf-8'))
553
my_config = config.GlobalConfig()
554
my_config._parser = my_config._get_parser(file=config_file)
557
def test_gpg_signing_command(self):
558
my_config = self._get_sample_config()
559
self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
560
self.assertEqual(False, my_config.signature_needed())
562
def _get_empty_config(self):
563
config_file = StringIO("")
564
my_config = config.GlobalConfig()
565
my_config._parser = my_config._get_parser(file=config_file)
568
def test_gpg_signing_command_unset(self):
569
my_config = self._get_empty_config()
570
self.assertEqual("gpg", my_config.gpg_signing_command())
572
def test_get_user_option_default(self):
573
my_config = self._get_empty_config()
574
self.assertEqual(None, my_config.get_user_option('no_option'))
576
def test_get_user_option_global(self):
577
my_config = self._get_sample_config()
578
self.assertEqual("something",
579
my_config.get_user_option('user_global_option'))
581
def test_post_commit_default(self):
582
my_config = self._get_sample_config()
583
self.assertEqual(None, my_config.post_commit())
585
def test_configured_logformat(self):
586
my_config = self._get_sample_config()
587
self.assertEqual("short", my_config.log_format())
589
def test_get_alias(self):
590
my_config = self._get_sample_config()
591
self.assertEqual('help', my_config.get_alias('h'))
593
def test_get_aliases(self):
594
my_config = self._get_sample_config()
595
aliases = my_config.get_aliases()
596
self.assertEqual(2, len(aliases))
597
sorted_keys = sorted(aliases)
598
self.assertEqual('help', aliases[sorted_keys[0]])
599
self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
601
def test_get_no_alias(self):
602
my_config = self._get_sample_config()
603
self.assertEqual(None, my_config.get_alias('foo'))
605
def test_get_long_alias(self):
606
my_config = self._get_sample_config()
607
self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
610
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
612
def test_empty(self):
613
my_config = config.GlobalConfig()
614
self.assertEqual(0, len(my_config.get_aliases()))
616
def test_set_alias(self):
617
my_config = config.GlobalConfig()
618
alias_value = 'commit --strict'
619
my_config.set_alias('commit', alias_value)
620
new_config = config.GlobalConfig()
621
self.assertEqual(alias_value, new_config.get_alias('commit'))
623
def test_remove_alias(self):
624
my_config = config.GlobalConfig()
625
my_config.set_alias('commit', 'commit --strict')
626
# Now remove the alias again.
627
my_config.unset_alias('commit')
628
new_config = config.GlobalConfig()
629
self.assertIs(None, new_config.get_alias('commit'))
632
class TestLocationConfig(tests.TestCaseInTempDir):
634
def test_constructs(self):
635
my_config = config.LocationConfig('http://example.com')
636
self.assertRaises(TypeError, config.LocationConfig)
638
def test_branch_calls_read_filenames(self):
639
# This is testing the correct file names are provided.
640
# TODO: consolidate with the test for GlobalConfigs filename checks.
642
# replace the class that is constructed, to check its parameters
643
oldparserclass = config.ConfigObj
644
config.ConfigObj = InstrumentedConfigObj
646
my_config = config.LocationConfig('http://www.example.com')
647
parser = my_config._get_parser()
649
config.ConfigObj = oldparserclass
650
self.failUnless(isinstance(parser, InstrumentedConfigObj))
651
self.assertEqual(parser._calls,
652
[('__init__', config.locations_config_filename(),
654
config.ensure_config_dir_exists()
655
#os.mkdir(config.config_dir())
656
f = file(config.branches_config_filename(), 'wb')
659
oldparserclass = config.ConfigObj
660
config.ConfigObj = InstrumentedConfigObj
662
my_config = config.LocationConfig('http://www.example.com')
663
parser = my_config._get_parser()
665
config.ConfigObj = oldparserclass
667
def test_get_global_config(self):
668
my_config = config.BranchConfig(FakeBranch('http://example.com'))
669
global_config = my_config._get_global_config()
670
self.failUnless(isinstance(global_config, config.GlobalConfig))
671
self.failUnless(global_config is my_config._get_global_config())
673
def test__get_matching_sections_no_match(self):
674
self.get_branch_config('/')
675
self.assertEqual([], self.my_location_config._get_matching_sections())
677
def test__get_matching_sections_exact(self):
678
self.get_branch_config('http://www.example.com')
679
self.assertEqual([('http://www.example.com', '')],
680
self.my_location_config._get_matching_sections())
682
def test__get_matching_sections_suffix_does_not(self):
683
self.get_branch_config('http://www.example.com-com')
684
self.assertEqual([], self.my_location_config._get_matching_sections())
686
def test__get_matching_sections_subdir_recursive(self):
687
self.get_branch_config('http://www.example.com/com')
688
self.assertEqual([('http://www.example.com', 'com')],
689
self.my_location_config._get_matching_sections())
691
def test__get_matching_sections_ignoreparent(self):
692
self.get_branch_config('http://www.example.com/ignoreparent')
693
self.assertEqual([('http://www.example.com/ignoreparent', '')],
694
self.my_location_config._get_matching_sections())
696
def test__get_matching_sections_ignoreparent_subdir(self):
697
self.get_branch_config(
698
'http://www.example.com/ignoreparent/childbranch')
699
self.assertEqual([('http://www.example.com/ignoreparent',
701
self.my_location_config._get_matching_sections())
703
def test__get_matching_sections_subdir_trailing_slash(self):
704
self.get_branch_config('/b')
705
self.assertEqual([('/b/', '')],
706
self.my_location_config._get_matching_sections())
708
def test__get_matching_sections_subdir_child(self):
709
self.get_branch_config('/a/foo')
710
self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
711
self.my_location_config._get_matching_sections())
713
def test__get_matching_sections_subdir_child_child(self):
714
self.get_branch_config('/a/foo/bar')
715
self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
716
self.my_location_config._get_matching_sections())
718
def test__get_matching_sections_trailing_slash_with_children(self):
719
self.get_branch_config('/a/')
720
self.assertEqual([('/a/', '')],
721
self.my_location_config._get_matching_sections())
723
def test__get_matching_sections_explicit_over_glob(self):
724
# XXX: 2006-09-08 jamesh
725
# This test only passes because ord('c') > ord('*'). If there
726
# was a config section for '/a/?', it would get precedence
728
self.get_branch_config('/a/c')
729
self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
730
self.my_location_config._get_matching_sections())
732
def test__get_option_policy_normal(self):
733
self.get_branch_config('http://www.example.com')
735
self.my_location_config._get_config_policy(
736
'http://www.example.com', 'normal_option'),
739
def test__get_option_policy_norecurse(self):
740
self.get_branch_config('http://www.example.com')
742
self.my_location_config._get_option_policy(
743
'http://www.example.com', 'norecurse_option'),
744
config.POLICY_NORECURSE)
745
# Test old recurse=False setting:
747
self.my_location_config._get_option_policy(
748
'http://www.example.com/norecurse', 'normal_option'),
749
config.POLICY_NORECURSE)
751
def test__get_option_policy_normal(self):
752
self.get_branch_config('http://www.example.com')
754
self.my_location_config._get_option_policy(
755
'http://www.example.com', 'appendpath_option'),
756
config.POLICY_APPENDPATH)
758
def test_location_without_username(self):
759
self.get_branch_config('http://www.example.com/ignoreparent')
760
self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
761
self.my_config.username())
763
def test_location_not_listed(self):
764
"""Test that the global username is used when no location matches"""
765
self.get_branch_config('/home/robertc/sources')
766
self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
767
self.my_config.username())
769
def test_overriding_location(self):
770
self.get_branch_config('http://www.example.com/foo')
771
self.assertEqual('Robert Collins <robertc@example.org>',
772
self.my_config.username())
774
def test_signatures_not_set(self):
775
self.get_branch_config('http://www.example.com',
776
global_config=sample_ignore_signatures)
777
self.assertEqual(config.CHECK_ALWAYS,
778
self.my_config.signature_checking())
779
self.assertEqual(config.SIGN_NEVER,
780
self.my_config.signing_policy())
782
def test_signatures_never(self):
783
self.get_branch_config('/a/c')
784
self.assertEqual(config.CHECK_NEVER,
785
self.my_config.signature_checking())
787
def test_signatures_when_available(self):
788
self.get_branch_config('/a/', global_config=sample_ignore_signatures)
789
self.assertEqual(config.CHECK_IF_POSSIBLE,
790
self.my_config.signature_checking())
792
def test_signatures_always(self):
793
self.get_branch_config('/b')
794
self.assertEqual(config.CHECK_ALWAYS,
795
self.my_config.signature_checking())
797
def test_gpg_signing_command(self):
798
self.get_branch_config('/b')
799
self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
801
def test_gpg_signing_command_missing(self):
802
self.get_branch_config('/a')
803
self.assertEqual("false", self.my_config.gpg_signing_command())
805
def test_get_user_option_global(self):
806
self.get_branch_config('/a')
807
self.assertEqual('something',
808
self.my_config.get_user_option('user_global_option'))
810
def test_get_user_option_local(self):
811
self.get_branch_config('/a')
812
self.assertEqual('local',
813
self.my_config.get_user_option('user_local_option'))
815
def test_get_user_option_appendpath(self):
816
# returned as is for the base path:
817
self.get_branch_config('http://www.example.com')
818
self.assertEqual('append',
819
self.my_config.get_user_option('appendpath_option'))
820
# Extra path components get appended:
821
self.get_branch_config('http://www.example.com/a/b/c')
822
self.assertEqual('append/a/b/c',
823
self.my_config.get_user_option('appendpath_option'))
824
# Overriden for http://www.example.com/dir, where it is a
826
self.get_branch_config('http://www.example.com/dir/a/b/c')
827
self.assertEqual('normal',
828
self.my_config.get_user_option('appendpath_option'))
830
def test_get_user_option_norecurse(self):
831
self.get_branch_config('http://www.example.com')
832
self.assertEqual('norecurse',
833
self.my_config.get_user_option('norecurse_option'))
834
self.get_branch_config('http://www.example.com/dir')
835
self.assertEqual(None,
836
self.my_config.get_user_option('norecurse_option'))
837
# http://www.example.com/norecurse is a recurse=False section
838
# that redefines normal_option. Subdirectories do not pick up
840
self.get_branch_config('http://www.example.com/norecurse')
841
self.assertEqual('norecurse',
842
self.my_config.get_user_option('normal_option'))
843
self.get_branch_config('http://www.example.com/norecurse/subdir')
844
self.assertEqual('normal',
845
self.my_config.get_user_option('normal_option'))
847
def test_set_user_option_norecurse(self):
848
self.get_branch_config('http://www.example.com')
849
self.my_config.set_user_option('foo', 'bar',
850
store=config.STORE_LOCATION_NORECURSE)
852
self.my_location_config._get_option_policy(
853
'http://www.example.com', 'foo'),
854
config.POLICY_NORECURSE)
856
def test_set_user_option_appendpath(self):
857
self.get_branch_config('http://www.example.com')
858
self.my_config.set_user_option('foo', 'bar',
859
store=config.STORE_LOCATION_APPENDPATH)
861
self.my_location_config._get_option_policy(
862
'http://www.example.com', 'foo'),
863
config.POLICY_APPENDPATH)
865
def test_set_user_option_change_policy(self):
866
self.get_branch_config('http://www.example.com')
867
self.my_config.set_user_option('norecurse_option', 'normal',
868
store=config.STORE_LOCATION)
870
self.my_location_config._get_option_policy(
871
'http://www.example.com', 'norecurse_option'),
874
def test_set_user_option_recurse_false_section(self):
875
# The following section has recurse=False set. The test is to
876
# make sure that a normal option can be added to the section,
877
# converting recurse=False to the norecurse policy.
878
self.get_branch_config('http://www.example.com/norecurse')
879
self.callDeprecated(['The recurse option is deprecated as of 0.14. '
880
'The section "http://www.example.com/norecurse" '
881
'has been converted to use policies.'],
882
self.my_config.set_user_option,
883
'foo', 'bar', store=config.STORE_LOCATION)
885
self.my_location_config._get_option_policy(
886
'http://www.example.com/norecurse', 'foo'),
888
# The previously existing option is still norecurse:
890
self.my_location_config._get_option_policy(
891
'http://www.example.com/norecurse', 'normal_option'),
892
config.POLICY_NORECURSE)
894
def test_post_commit_default(self):
895
self.get_branch_config('/a/c')
896
self.assertEqual('bzrlib.tests.test_config.post_commit',
897
self.my_config.post_commit())
899
def get_branch_config(self, location, global_config=None):
900
if global_config is None:
901
global_file = StringIO(sample_config_text.encode('utf-8'))
903
global_file = StringIO(global_config.encode('utf-8'))
904
branches_file = StringIO(sample_branches_text.encode('utf-8'))
905
self.my_config = config.BranchConfig(FakeBranch(location))
906
# Force location config to use specified file
907
self.my_location_config = self.my_config._get_location_config()
908
self.my_location_config._get_parser(branches_file)
909
# Force global config to use specified file
910
self.my_config._get_global_config()._get_parser(global_file)
912
def test_set_user_setting_sets_and_saves(self):
913
self.get_branch_config('/a/c')
914
record = InstrumentedConfigObj("foo")
915
self.my_location_config._parser = record
917
real_mkdir = os.mkdir
919
def checked_mkdir(path, mode=0777):
920
self.log('making directory: %s', path)
921
real_mkdir(path, mode)
924
os.mkdir = checked_mkdir
926
self.callDeprecated(['The recurse option is deprecated as of '
927
'0.14. The section "/a/c" has been '
928
'converted to use policies.'],
929
self.my_config.set_user_option,
930
'foo', 'bar', store=config.STORE_LOCATION)
932
os.mkdir = real_mkdir
934
self.failUnless(self.created, 'Failed to create ~/.bazaar')
935
self.assertEqual([('__contains__', '/a/c'),
936
('__contains__', '/a/c/'),
937
('__setitem__', '/a/c', {}),
938
('__getitem__', '/a/c'),
939
('__setitem__', 'foo', 'bar'),
940
('__getitem__', '/a/c'),
941
('as_bool', 'recurse'),
942
('__getitem__', '/a/c'),
943
('__delitem__', 'recurse'),
944
('__getitem__', '/a/c'),
946
('__getitem__', '/a/c'),
947
('__contains__', 'foo:policy'),
951
def test_set_user_setting_sets_and_saves2(self):
952
self.get_branch_config('/a/c')
953
self.assertIs(self.my_config.get_user_option('foo'), None)
954
self.my_config.set_user_option('foo', 'bar')
956
self.my_config.branch.control_files.files['branch.conf'].strip(),
958
self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
959
self.my_config.set_user_option('foo', 'baz',
960
store=config.STORE_LOCATION)
961
self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
962
self.my_config.set_user_option('foo', 'qux')
963
self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
965
def test_get_bzr_remote_path(self):
966
my_config = config.LocationConfig('/a/c')
967
self.assertEqual('bzr', my_config.get_bzr_remote_path())
968
my_config.set_user_option('bzr_remote_path', '/path-bzr')
969
self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
970
os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
971
self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
974
precedence_global = 'option = global'
975
precedence_branch = 'option = branch'
976
precedence_location = """
980
[http://example.com/specific]
985
class TestBranchConfigItems(tests.TestCaseInTempDir):
987
def get_branch_config(self, global_config=None, location=None,
988
location_config=None, branch_data_config=None):
989
my_config = config.BranchConfig(FakeBranch(location))
990
if global_config is not None:
991
global_file = StringIO(global_config.encode('utf-8'))
992
my_config._get_global_config()._get_parser(global_file)
993
self.my_location_config = my_config._get_location_config()
994
if location_config is not None:
995
location_file = StringIO(location_config.encode('utf-8'))
996
self.my_location_config._get_parser(location_file)
997
if branch_data_config is not None:
998
my_config.branch.control_files.files['branch.conf'] = \
1002
def test_user_id(self):
1003
branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
1004
my_config = config.BranchConfig(branch)
1005
self.assertEqual("Robert Collins <robertc@example.net>",
1006
my_config.username())
1007
my_config.branch.control_files.files['email'] = "John"
1008
my_config.set_user_option('email',
1009
"Robert Collins <robertc@example.org>")
1010
self.assertEqual("John", my_config.username())
1011
del my_config.branch.control_files.files['email']
1012
self.assertEqual("Robert Collins <robertc@example.org>",
1013
my_config.username())
1015
def test_not_set_in_branch(self):
1016
my_config = self.get_branch_config(sample_config_text)
1017
self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1018
my_config._get_user_id())
1019
my_config.branch.control_files.files['email'] = "John"
1020
self.assertEqual("John", my_config._get_user_id())
1022
def test_BZR_EMAIL_OVERRIDES(self):
1023
os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
1024
branch = FakeBranch()
1025
my_config = config.BranchConfig(branch)
1026
self.assertEqual("Robert Collins <robertc@example.org>",
1027
my_config.username())
1029
def test_signatures_forced(self):
1030
my_config = self.get_branch_config(
1031
global_config=sample_always_signatures)
1032
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1033
self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1034
self.assertTrue(my_config.signature_needed())
1036
def test_signatures_forced_branch(self):
1037
my_config = self.get_branch_config(
1038
global_config=sample_ignore_signatures,
1039
branch_data_config=sample_always_signatures)
1040
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1041
self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1042
self.assertTrue(my_config.signature_needed())
1044
def test_gpg_signing_command(self):
1045
my_config = self.get_branch_config(
1046
# branch data cannot set gpg_signing_command
1047
branch_data_config="gpg_signing_command=pgp")
1048
config_file = StringIO(sample_config_text.encode('utf-8'))
1049
my_config._get_global_config()._get_parser(config_file)
1050
self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1052
def test_get_user_option_global(self):
1053
branch = FakeBranch()
1054
my_config = config.BranchConfig(branch)
1055
config_file = StringIO(sample_config_text.encode('utf-8'))
1056
(my_config._get_global_config()._get_parser(config_file))
1057
self.assertEqual('something',
1058
my_config.get_user_option('user_global_option'))
1060
def test_post_commit_default(self):
1061
branch = FakeBranch()
1062
my_config = self.get_branch_config(sample_config_text, '/a/c',
1063
sample_branches_text)
1064
self.assertEqual(my_config.branch.base, '/a/c')
1065
self.assertEqual('bzrlib.tests.test_config.post_commit',
1066
my_config.post_commit())
1067
my_config.set_user_option('post_commit', 'rmtree_root')
1068
# post-commit is ignored when bresent in branch data
1069
self.assertEqual('bzrlib.tests.test_config.post_commit',
1070
my_config.post_commit())
1071
my_config.set_user_option('post_commit', 'rmtree_root',
1072
store=config.STORE_LOCATION)
1073
self.assertEqual('rmtree_root', my_config.post_commit())
1075
def test_config_precedence(self):
1076
my_config = self.get_branch_config(global_config=precedence_global)
1077
self.assertEqual(my_config.get_user_option('option'), 'global')
1078
my_config = self.get_branch_config(global_config=precedence_global,
1079
branch_data_config=precedence_branch)
1080
self.assertEqual(my_config.get_user_option('option'), 'branch')
1081
my_config = self.get_branch_config(global_config=precedence_global,
1082
branch_data_config=precedence_branch,
1083
location_config=precedence_location)
1084
self.assertEqual(my_config.get_user_option('option'), 'recurse')
1085
my_config = self.get_branch_config(global_config=precedence_global,
1086
branch_data_config=precedence_branch,
1087
location_config=precedence_location,
1088
location='http://example.com/specific')
1089
self.assertEqual(my_config.get_user_option('option'), 'exact')
1091
def test_get_mail_client(self):
1092
config = self.get_branch_config()
1093
client = config.get_mail_client()
1094
self.assertIsInstance(client, mail_client.DefaultMail)
1097
config.set_user_option('mail_client', 'evolution')
1098
client = config.get_mail_client()
1099
self.assertIsInstance(client, mail_client.Evolution)
1101
config.set_user_option('mail_client', 'kmail')
1102
client = config.get_mail_client()
1103
self.assertIsInstance(client, mail_client.KMail)
1105
config.set_user_option('mail_client', 'mutt')
1106
client = config.get_mail_client()
1107
self.assertIsInstance(client, mail_client.Mutt)
1109
config.set_user_option('mail_client', 'thunderbird')
1110
client = config.get_mail_client()
1111
self.assertIsInstance(client, mail_client.Thunderbird)
1114
config.set_user_option('mail_client', 'default')
1115
client = config.get_mail_client()
1116
self.assertIsInstance(client, mail_client.DefaultMail)
1118
config.set_user_option('mail_client', 'editor')
1119
client = config.get_mail_client()
1120
self.assertIsInstance(client, mail_client.Editor)
1122
config.set_user_option('mail_client', 'mapi')
1123
client = config.get_mail_client()
1124
self.assertIsInstance(client, mail_client.MAPIClient)
1126
config.set_user_option('mail_client', 'xdg-email')
1127
client = config.get_mail_client()
1128
self.assertIsInstance(client, mail_client.XDGEmail)
1130
config.set_user_option('mail_client', 'firebird')
1131
self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1134
class TestMailAddressExtraction(tests.TestCase):
1136
def test_extract_email_address(self):
1137
self.assertEqual('jane@test.com',
1138
config.extract_email_address('Jane <jane@test.com>'))
1139
self.assertRaises(errors.NoEmailInUsername,
1140
config.extract_email_address, 'Jane Tester')
1142
def test_parse_username(self):
1143
self.assertEqual(('', 'jdoe@example.com'),
1144
config.parse_username('jdoe@example.com'))
1145
self.assertEqual(('', 'jdoe@example.com'),
1146
config.parse_username('<jdoe@example.com>'))
1147
self.assertEqual(('John Doe', 'jdoe@example.com'),
1148
config.parse_username('John Doe <jdoe@example.com>'))
1149
self.assertEqual(('John Doe', ''),
1150
config.parse_username('John Doe'))
1151
self.assertEqual(('John Doe', 'jdoe@example.com'),
1152
config.parse_username('John Doe jdoe@example.com'))
1154
class TestTreeConfig(tests.TestCaseWithTransport):
1156
def test_get_value(self):
1157
"""Test that retreiving a value from a section is possible"""
1158
branch = self.make_branch('.')
1159
tree_config = config.TreeConfig(branch)
1160
tree_config.set_option('value', 'key', 'SECTION')
1161
tree_config.set_option('value2', 'key2')
1162
tree_config.set_option('value3-top', 'key3')
1163
tree_config.set_option('value3-section', 'key3', 'SECTION')
1164
value = tree_config.get_option('key', 'SECTION')
1165
self.assertEqual(value, 'value')
1166
value = tree_config.get_option('key2')
1167
self.assertEqual(value, 'value2')
1168
self.assertEqual(tree_config.get_option('non-existant'), None)
1169
value = tree_config.get_option('non-existant', 'SECTION')
1170
self.assertEqual(value, None)
1171
value = tree_config.get_option('non-existant', default='default')
1172
self.assertEqual(value, 'default')
1173
self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1174
value = tree_config.get_option('key2', 'NOSECTION', default='default')
1175
self.assertEqual(value, 'default')
1176
value = tree_config.get_option('key3')
1177
self.assertEqual(value, 'value3-top')
1178
value = tree_config.get_option('key3', 'SECTION')
1179
self.assertEqual(value, 'value3-section')
1182
class TestTransportConfig(tests.TestCaseWithTransport):
1184
def test_get_value(self):
1185
"""Test that retreiving a value from a section is possible"""
1186
bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1188
bzrdir_config.set_option('value', 'key', 'SECTION')
1189
bzrdir_config.set_option('value2', 'key2')
1190
bzrdir_config.set_option('value3-top', 'key3')
1191
bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1192
value = bzrdir_config.get_option('key', 'SECTION')
1193
self.assertEqual(value, 'value')
1194
value = bzrdir_config.get_option('key2')
1195
self.assertEqual(value, 'value2')
1196
self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1197
value = bzrdir_config.get_option('non-existant', 'SECTION')
1198
self.assertEqual(value, None)
1199
value = bzrdir_config.get_option('non-existant', default='default')
1200
self.assertEqual(value, 'default')
1201
self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1202
value = bzrdir_config.get_option('key2', 'NOSECTION',
1204
self.assertEqual(value, 'default')
1205
value = bzrdir_config.get_option('key3')
1206
self.assertEqual(value, 'value3-top')
1207
value = bzrdir_config.get_option('key3', 'SECTION')
1208
self.assertEqual(value, 'value3-section')
1210
def test_set_unset_default_stack_on(self):
1211
my_dir = self.make_bzrdir('.')
1212
bzrdir_config = config.BzrDirConfig(my_dir)
1213
self.assertIs(None, bzrdir_config.get_default_stack_on())
1214
bzrdir_config.set_default_stack_on('Foo')
1215
self.assertEqual('Foo', bzrdir_config._config.get_option(
1216
'default_stack_on'))
1217
self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1218
bzrdir_config.set_default_stack_on(None)
1219
self.assertIs(None, bzrdir_config.get_default_stack_on())
1222
class TestAuthenticationConfigFile(tests.TestCase):
1223
"""Test the authentication.conf file matching"""
1225
def _got_user_passwd(self, expected_user, expected_password,
1226
config, *args, **kwargs):
1227
credentials = config.get_credentials(*args, **kwargs)
1228
if credentials is None:
1232
user = credentials['user']
1233
password = credentials['password']
1234
self.assertEquals(expected_user, user)
1235
self.assertEquals(expected_password, password)
1237
def test_empty_config(self):
1238
conf = config.AuthenticationConfig(_file=StringIO())
1239
self.assertEquals({}, conf._get_config())
1240
self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1242
def test_missing_auth_section_header(self):
1243
conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1244
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1246
def test_auth_section_header_not_closed(self):
1247
conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1248
self.assertRaises(errors.ParseConfigError, conf._get_config)
1250
def test_auth_value_not_boolean(self):
1251
conf = config.AuthenticationConfig(_file=StringIO(
1255
verify_certificates=askme # Error: Not a boolean
1257
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1259
def test_auth_value_not_int(self):
1260
conf = config.AuthenticationConfig(_file=StringIO(
1264
port=port # Error: Not an int
1266
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1268
def test_unknown_password_encoding(self):
1269
conf = config.AuthenticationConfig(_file=StringIO(
1273
password_encoding=unknown
1275
self.assertRaises(ValueError, conf.get_password,
1276
'ftp', 'foo.net', 'joe')
1278
def test_credentials_for_scheme_host(self):
1279
conf = config.AuthenticationConfig(_file=StringIO(
1280
"""# Identity on foo.net
1285
password=secret-pass
1288
self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1290
self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1292
self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1294
def test_credentials_for_host_port(self):
1295
conf = config.AuthenticationConfig(_file=StringIO(
1296
"""# Identity on foo.net
1302
password=secret-pass
1305
self._got_user_passwd('joe', 'secret-pass',
1306
conf, 'ftp', 'foo.net', port=10021)
1308
self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1310
def test_for_matching_host(self):
1311
conf = config.AuthenticationConfig(_file=StringIO(
1312
"""# Identity on foo.net
1318
[sourceforge domain]
1325
self._got_user_passwd('georges', 'bendover',
1326
conf, 'bzr', 'foo.bzr.sf.net')
1328
self._got_user_passwd(None, None,
1329
conf, 'bzr', 'bbzr.sf.net')
1331
def test_for_matching_host_None(self):
1332
conf = config.AuthenticationConfig(_file=StringIO(
1333
"""# Identity on foo.net
1343
self._got_user_passwd('joe', 'joepass',
1344
conf, 'bzr', 'quux.net')
1345
# no host but different scheme
1346
self._got_user_passwd('georges', 'bendover',
1347
conf, 'ftp', 'quux.net')
1349
def test_credentials_for_path(self):
1350
conf = config.AuthenticationConfig(_file=StringIO(
1366
self._got_user_passwd(None, None,
1367
conf, 'http', host='bar.org', path='/dir3')
1369
self._got_user_passwd('georges', 'bendover',
1370
conf, 'http', host='bar.org', path='/dir2')
1372
self._got_user_passwd('jim', 'jimpass',
1373
conf, 'http', host='bar.org',path='/dir1/subdir')
1375
def test_credentials_for_user(self):
1376
conf = config.AuthenticationConfig(_file=StringIO(
1385
self._got_user_passwd('jim', 'jimpass',
1386
conf, 'http', 'bar.org')
1388
self._got_user_passwd('jim', 'jimpass',
1389
conf, 'http', 'bar.org', user='jim')
1390
# Don't get a different user if one is specified
1391
self._got_user_passwd(None, None,
1392
conf, 'http', 'bar.org', user='georges')
1394
def test_credentials_for_user_without_password(self):
1395
conf = config.AuthenticationConfig(_file=StringIO(
1402
# Get user but no password
1403
self._got_user_passwd('jim', None,
1404
conf, 'http', 'bar.org')
1406
def test_verify_certificates(self):
1407
conf = config.AuthenticationConfig(_file=StringIO(
1414
verify_certificates=False
1421
credentials = conf.get_credentials('https', 'bar.org')
1422
self.assertEquals(False, credentials.get('verify_certificates'))
1423
credentials = conf.get_credentials('https', 'foo.net')
1424
self.assertEquals(True, credentials.get('verify_certificates'))
1427
class TestAuthenticationStorage(tests.TestCaseInTempDir):
1429
def test_set_credentials(self):
1430
conf = config.AuthenticationConfig()
1431
conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
1432
99, path='/foo', verify_certificates=False, realm='realm')
1433
credentials = conf.get_credentials(host='host', scheme='scheme',
1434
port=99, path='/foo',
1436
CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
1437
'verify_certificates': False, 'scheme': 'scheme',
1438
'host': 'host', 'port': 99, 'path': '/foo',
1440
self.assertEqual(CREDENTIALS, credentials)
1441
credentials_from_disk = config.AuthenticationConfig().get_credentials(
1442
host='host', scheme='scheme', port=99, path='/foo', realm='realm')
1443
self.assertEqual(CREDENTIALS, credentials_from_disk)
1445
def test_reset_credentials_different_name(self):
1446
conf = config.AuthenticationConfig()
1447
conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
1448
conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
1449
self.assertIs(None, conf._get_config().get('name'))
1450
credentials = conf.get_credentials(host='host', scheme='scheme')
1451
CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
1452
'password', 'verify_certificates': True,
1453
'scheme': 'scheme', 'host': 'host', 'port': None,
1454
'path': None, 'realm': None}
1455
self.assertEqual(CREDENTIALS, credentials)
1458
class TestAuthenticationConfig(tests.TestCase):
1459
"""Test AuthenticationConfig behaviour"""
1461
def _check_default_password_prompt(self, expected_prompt_format, scheme,
1462
host=None, port=None, realm=None,
1466
user, password = 'jim', 'precious'
1467
expected_prompt = expected_prompt_format % {
1468
'scheme': scheme, 'host': host, 'port': port,
1469
'user': user, 'realm': realm}
1471
stdout = tests.StringIOWrapper()
1472
stderr = tests.StringIOWrapper()
1473
ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
1474
stdout=stdout, stderr=stderr)
1475
# We use an empty conf so that the user is always prompted
1476
conf = config.AuthenticationConfig()
1477
self.assertEquals(password,
1478
conf.get_password(scheme, host, user, port=port,
1479
realm=realm, path=path))
1480
self.assertEquals(expected_prompt, stderr.getvalue())
1481
self.assertEquals('', stdout.getvalue())
1483
def _check_default_username_prompt(self, expected_prompt_format, scheme,
1484
host=None, port=None, realm=None,
1489
expected_prompt = expected_prompt_format % {
1490
'scheme': scheme, 'host': host, 'port': port,
1492
stdout = tests.StringIOWrapper()
1493
stderr = tests.StringIOWrapper()
1494
ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
1495
stdout=stdout, stderr=stderr)
1496
# We use an empty conf so that the user is always prompted
1497
conf = config.AuthenticationConfig()
1498
self.assertEquals(username, conf.get_user(scheme, host, port=port,
1499
realm=realm, path=path, ask=True))
1500
self.assertEquals(expected_prompt, stderr.getvalue())
1501
self.assertEquals('', stdout.getvalue())
1503
def test_username_defaults_prompts(self):
1504
# HTTP prompts can't be tested here, see test_http.py
1505
self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
1506
self._check_default_username_prompt(
1507
'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
1508
self._check_default_username_prompt(
1509
'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1511
def test_username_default_no_prompt(self):
1512
conf = config.AuthenticationConfig()
1513
self.assertEquals(None,
1514
conf.get_user('ftp', 'example.com'))
1515
self.assertEquals("explicitdefault",
1516
conf.get_user('ftp', 'example.com', default="explicitdefault"))
1518
def test_password_default_prompts(self):
1519
# HTTP prompts can't be tested here, see test_http.py
1520
self._check_default_password_prompt(
1521
'FTP %(user)s@%(host)s password: ', 'ftp')
1522
self._check_default_password_prompt(
1523
'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
1524
self._check_default_password_prompt(
1525
'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
1526
# SMTP port handling is a bit special (it's handled if embedded in the
1528
# FIXME: should we: forbid that, extend it to other schemes, leave
1529
# things as they are that's fine thank you ?
1530
self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
1532
self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
1533
'smtp', host='bar.org:10025')
1534
self._check_default_password_prompt(
1535
'SMTP %(user)s@%(host)s:%(port)d password: ',
1538
def test_ssh_password_emits_warning(self):
1539
conf = config.AuthenticationConfig(_file=StringIO(
1547
entered_password = 'typed-by-hand'
1548
stdout = tests.StringIOWrapper()
1549
stderr = tests.StringIOWrapper()
1550
ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
1551
stdout=stdout, stderr=stderr)
1553
# Since the password defined in the authentication config is ignored,
1554
# the user is prompted
1555
self.assertEquals(entered_password,
1556
conf.get_password('ssh', 'bar.org', user='jim'))
1557
self.assertContainsRe(
1558
self._get_log(keep_log_file=True),
1559
'password ignored in section \[ssh with password\]')
1561
def test_ssh_without_password_doesnt_emit_warning(self):
1562
conf = config.AuthenticationConfig(_file=StringIO(
1569
entered_password = 'typed-by-hand'
1570
stdout = tests.StringIOWrapper()
1571
stderr = tests.StringIOWrapper()
1572
ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
1576
# Since the password defined in the authentication config is ignored,
1577
# the user is prompted
1578
self.assertEquals(entered_password,
1579
conf.get_password('ssh', 'bar.org', user='jim'))
1580
# No warning shoud be emitted since there is no password. We are only
1582
self.assertNotContainsRe(
1583
self._get_log(keep_log_file=True),
1584
'password ignored in section \[ssh with password\]')
1586
def test_uses_fallback_stores(self):
1587
self._old_cs_registry = config.credential_store_registry
1589
config.credential_store_registry = self._old_cs_registry
1590
self.addCleanup(restore)
1591
config.credential_store_registry = config.CredentialStoreRegistry()
1592
store = StubCredentialStore()
1593
store.add_credentials("http", "example.com", "joe", "secret")
1594
config.credential_store_registry.register("stub", store, fallback=True)
1595
conf = config.AuthenticationConfig(_file=StringIO())
1596
creds = conf.get_credentials("http", "example.com")
1597
self.assertEquals("joe", creds["user"])
1598
self.assertEquals("secret", creds["password"])
1601
class StubCredentialStore(config.CredentialStore):
1607
def add_credentials(self, scheme, host, user, password=None):
1608
self._username[(scheme, host)] = user
1609
self._password[(scheme, host)] = password
1611
def get_credentials(self, scheme, host, port=None, user=None,
1612
path=None, realm=None):
1613
key = (scheme, host)
1614
if not key in self._username:
1616
return { "scheme": scheme, "host": host, "port": port,
1617
"user": self._username[key], "password": self._password[key]}
1620
class CountingCredentialStore(config.CredentialStore):
1625
def get_credentials(self, scheme, host, port=None, user=None,
1626
path=None, realm=None):
1631
class TestCredentialStoreRegistry(tests.TestCase):
1633
def _get_cs_registry(self):
1634
return config.credential_store_registry
1636
def test_default_credential_store(self):
1637
r = self._get_cs_registry()
1638
default = r.get_credential_store(None)
1639
self.assertIsInstance(default, config.PlainTextCredentialStore)
1641
def test_unknown_credential_store(self):
1642
r = self._get_cs_registry()
1643
# It's hard to imagine someone creating a credential store named
1644
# 'unknown' so we use that as an never registered key.
1645
self.assertRaises(KeyError, r.get_credential_store, 'unknown')
1647
def test_fallback_none_registered(self):
1648
r = config.CredentialStoreRegistry()
1649
self.assertEquals(None,
1650
r.get_fallback_credentials("http", "example.com"))
1652
def test_register(self):
1653
r = config.CredentialStoreRegistry()
1654
r.register("stub", StubCredentialStore(), fallback=False)
1655
r.register("another", StubCredentialStore(), fallback=True)
1656
self.assertEquals(["another", "stub"], r.keys())
1658
def test_register_lazy(self):
1659
r = config.CredentialStoreRegistry()
1660
r.register_lazy("stub", "bzrlib.tests.test_config",
1661
"StubCredentialStore", fallback=False)
1662
self.assertEquals(["stub"], r.keys())
1663
self.assertIsInstance(r.get_credential_store("stub"),
1664
StubCredentialStore)
1666
def test_is_fallback(self):
1667
r = config.CredentialStoreRegistry()
1668
r.register("stub1", None, fallback=False)
1669
r.register("stub2", None, fallback=True)
1670
self.assertEquals(False, r.is_fallback("stub1"))
1671
self.assertEquals(True, r.is_fallback("stub2"))
1673
def test_no_fallback(self):
1674
r = config.CredentialStoreRegistry()
1675
store = CountingCredentialStore()
1676
r.register("count", store, fallback=False)
1677
self.assertEquals(None,
1678
r.get_fallback_credentials("http", "example.com"))
1679
self.assertEquals(0, store._calls)
1681
def test_fallback_credentials(self):
1682
r = config.CredentialStoreRegistry()
1683
store = StubCredentialStore()
1684
store.add_credentials("http", "example.com",
1685
"somebody", "geheim")
1686
r.register("stub", store, fallback=True)
1687
creds = r.get_fallback_credentials("http", "example.com")
1688
self.assertEquals("somebody", creds["user"])
1689
self.assertEquals("geheim", creds["password"])
1691
def test_fallback_first_wins(self):
1692
r = config.CredentialStoreRegistry()
1693
stub1 = StubCredentialStore()
1694
stub1.add_credentials("http", "example.com",
1695
"somebody", "stub1")
1696
r.register("stub1", stub1, fallback=True)
1697
stub2 = StubCredentialStore()
1698
stub2.add_credentials("http", "example.com",
1699
"somebody", "stub2")
1700
r.register("stub2", stub1, fallback=True)
1701
creds = r.get_fallback_credentials("http", "example.com")
1702
self.assertEquals("somebody", creds["user"])
1703
self.assertEquals("stub1", creds["password"])
1706
class TestPlainTextCredentialStore(tests.TestCase):
1708
def test_decode_password(self):
1709
r = config.credential_store_registry
1710
plain_text = r.get_credential_store()
1711
decoded = plain_text.decode_password(dict(password='secret'))
1712
self.assertEquals('secret', decoded)
1715
# FIXME: Once we have a way to declare authentication to all test servers, we
1716
# can implement generic tests.
1717
# test_user_password_in_url
1718
# test_user_in_url_password_from_config
1719
# test_user_in_url_password_prompted
1720
# test_user_in_config
1721
# test_user_getpass.getuser
1722
# test_user_prompted ?
1723
class TestAuthenticationRing(tests.TestCaseWithTransport):