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
38
from bzrlib.util.configobj import configobj
41
sample_long_alias="log -r-15..-1 --line"
42
sample_config_text = u"""
44
email=Erik B\u00e5gfors <erik@bagfors.nu>
46
change_editor=vimdiff -of @new_path @old_path
47
gpg_signing_command=gnome-gpg
49
user_global_option=something
52
ll=""" + sample_long_alias + "\n"
55
sample_always_signatures = """
57
check_signatures=ignore
58
create_signatures=always
61
sample_ignore_signatures = """
63
check_signatures=require
64
create_signatures=never
67
sample_maybe_signatures = """
69
check_signatures=ignore
70
create_signatures=when-required
73
sample_branches_text = """
74
[http://www.example.com]
76
email=Robert Collins <robertc@example.org>
77
normal_option = normal
78
appendpath_option = append
79
appendpath_option:policy = appendpath
80
norecurse_option = norecurse
81
norecurse_option:policy = norecurse
82
[http://www.example.com/ignoreparent]
83
# different project: ignore parent dir config
85
[http://www.example.com/norecurse]
86
# configuration items that only apply to this dir
88
normal_option = norecurse
89
[http://www.example.com/dir]
90
appendpath_option = normal
92
check_signatures=require
93
# test trailing / matching with no children
95
check_signatures=check-available
96
gpg_signing_command=false
97
user_local_option=local
98
# test trailing / matching
100
#subdirs will match but not the parent
102
check_signatures=ignore
103
post_commit=bzrlib.tests.test_config.post_commit
104
#testing explicit beats globs
108
class InstrumentedConfigObj(object):
109
"""A config obj look-enough-alike to record calls made to it."""
111
def __contains__(self, thing):
112
self._calls.append(('__contains__', thing))
115
def __getitem__(self, key):
116
self._calls.append(('__getitem__', key))
119
def __init__(self, input, encoding=None):
120
self._calls = [('__init__', input, encoding)]
122
def __setitem__(self, key, value):
123
self._calls.append(('__setitem__', key, value))
125
def __delitem__(self, key):
126
self._calls.append(('__delitem__', key))
129
self._calls.append(('keys',))
132
def write(self, arg):
133
self._calls.append(('write',))
135
def as_bool(self, value):
136
self._calls.append(('as_bool', value))
139
def get_value(self, section, name):
140
self._calls.append(('get_value', section, name))
144
class FakeBranch(object):
146
def __init__(self, base=None, user_id=None):
148
self.base = "http://example.com/branches/demo"
151
self._transport = self.control_files = \
152
FakeControlFilesAndTransport(user_id=user_id)
154
def _get_config(self):
155
return config.TransportConfig(self._transport, 'branch.conf')
157
def lock_write(self):
164
class FakeControlFilesAndTransport(object):
166
def __init__(self, user_id=None):
169
self.files['email'] = user_id
170
self._transport = self
172
def get_utf8(self, filename):
174
raise AssertionError("get_utf8 should no longer be used")
176
def get(self, filename):
179
return StringIO(self.files[filename])
181
raise errors.NoSuchFile(filename)
183
def get_bytes(self, filename):
186
return self.files[filename]
188
raise errors.NoSuchFile(filename)
190
def put(self, filename, fileobj):
191
self.files[filename] = fileobj.read()
193
def put_file(self, filename, fileobj):
194
return self.put(filename, fileobj)
197
class InstrumentedConfig(config.Config):
198
"""An instrumented config that supplies stubs for template methods."""
201
super(InstrumentedConfig, self).__init__()
203
self._signatures = config.CHECK_NEVER
205
def _get_user_id(self):
206
self._calls.append('_get_user_id')
207
return "Robert Collins <robert.collins@example.org>"
209
def _get_signature_checking(self):
210
self._calls.append('_get_signature_checking')
211
return self._signatures
213
def _get_change_editor(self):
214
self._calls.append('_get_change_editor')
215
return 'vimdiff -fo @new_path @old_path'
218
bool_config = """[DEFAULT]
227
class TestConfigObj(tests.TestCase):
229
def test_get_bool(self):
230
co = config.ConfigObj(StringIO(bool_config))
231
self.assertIs(co.get_bool('DEFAULT', 'active'), True)
232
self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
233
self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
234
self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
236
def test_hash_sign_in_value(self):
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)
241
co = config.ConfigObj()
242
co['test'] = 'foo#bar'
244
self.assertEqual(lines, ['test = "foo#bar"'])
245
co2 = config.ConfigObj(lines)
246
self.assertEqual(co2['test'], 'foo#bar')
249
erroneous_config = """[section] # line 1
252
whocares=notme # line 4
256
class TestConfigObjErrors(tests.TestCase):
258
def test_duplicate_section_name_error_line(self):
260
co = configobj.ConfigObj(StringIO(erroneous_config),
262
except config.configobj.DuplicateError, e:
263
self.assertEqual(3, e.line_number)
265
self.fail('Error in config file not detected')
268
class TestConfig(tests.TestCase):
270
def test_constructs(self):
273
def test_no_default_editor(self):
274
self.assertRaises(NotImplementedError, config.Config().get_editor)
276
def test_user_email(self):
277
my_config = InstrumentedConfig()
278
self.assertEqual('robert.collins@example.org', my_config.user_email())
279
self.assertEqual(['_get_user_id'], my_config._calls)
281
def test_username(self):
282
my_config = InstrumentedConfig()
283
self.assertEqual('Robert Collins <robert.collins@example.org>',
284
my_config.username())
285
self.assertEqual(['_get_user_id'], my_config._calls)
287
def test_signatures_default(self):
288
my_config = config.Config()
289
self.assertFalse(my_config.signature_needed())
290
self.assertEqual(config.CHECK_IF_POSSIBLE,
291
my_config.signature_checking())
292
self.assertEqual(config.SIGN_WHEN_REQUIRED,
293
my_config.signing_policy())
295
def test_signatures_template_method(self):
296
my_config = InstrumentedConfig()
297
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
298
self.assertEqual(['_get_signature_checking'], my_config._calls)
300
def test_signatures_template_method_none(self):
301
my_config = InstrumentedConfig()
302
my_config._signatures = None
303
self.assertEqual(config.CHECK_IF_POSSIBLE,
304
my_config.signature_checking())
305
self.assertEqual(['_get_signature_checking'], my_config._calls)
307
def test_gpg_signing_command_default(self):
308
my_config = config.Config()
309
self.assertEqual('gpg', my_config.gpg_signing_command())
311
def test_get_user_option_default(self):
312
my_config = config.Config()
313
self.assertEqual(None, my_config.get_user_option('no_option'))
315
def test_post_commit_default(self):
316
my_config = config.Config()
317
self.assertEqual(None, my_config.post_commit())
319
def test_log_format_default(self):
320
my_config = config.Config()
321
self.assertEqual('long', my_config.log_format())
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)
332
class TestConfigPath(tests.TestCase):
335
super(TestConfigPath, self).setUp()
336
os.environ['HOME'] = '/home/bogus'
337
os.environ['XDG_CACHE_DIR'] = ''
338
if sys.platform == 'win32':
339
os.environ['BZR_HOME'] = \
340
r'C:\Documents and Settings\bogus\Application Data'
342
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
344
self.bzr_home = '/home/bogus/.bazaar'
346
def test_config_dir(self):
347
self.assertEqual(config.config_dir(), self.bzr_home)
349
def test_config_filename(self):
350
self.assertEqual(config.config_filename(),
351
self.bzr_home + '/bazaar.conf')
353
def test_branches_config_filename(self):
354
self.assertEqual(config.branches_config_filename(),
355
self.bzr_home + '/branches.conf')
357
def test_locations_config_filename(self):
358
self.assertEqual(config.locations_config_filename(),
359
self.bzr_home + '/locations.conf')
361
def test_authentication_config_filename(self):
362
self.assertEqual(config.authentication_config_filename(),
363
self.bzr_home + '/authentication.conf')
365
def test_xdg_cache_dir(self):
366
self.assertEqual(config.xdg_cache_dir(),
367
'/home/bogus/.cache')
370
class TestIniConfig(tests.TestCase):
372
def test_contructs(self):
373
my_config = config.IniBasedConfig("nothing")
375
def test_from_fp(self):
376
config_file = StringIO(sample_config_text.encode('utf-8'))
377
my_config = config.IniBasedConfig(None)
379
isinstance(my_config._get_parser(file=config_file),
380
configobj.ConfigObj))
382
def test_cached(self):
383
config_file = StringIO(sample_config_text.encode('utf-8'))
384
my_config = config.IniBasedConfig(None)
385
parser = my_config._get_parser(file=config_file)
386
self.failUnless(my_config._get_parser() is parser)
388
def test_get_user_option_as_bool(self):
389
config_file = StringIO("""
392
an_invalid_bool = maybe
393
a_list = hmm, who knows ? # This interpreted as a list !
395
my_config = config.IniBasedConfig(None)
396
parser = my_config._get_parser(file=config_file)
397
get_option = my_config.get_user_option_as_bool
398
self.assertEqual(True, get_option('a_true_bool'))
399
self.assertEqual(False, get_option('a_false_bool'))
400
self.assertIs(None, get_option('an_invalid_bool'))
401
self.assertIs(None, get_option('not_defined_in_this_config'))
403
class TestGetConfig(tests.TestCase):
405
def test_constructs(self):
406
my_config = config.GlobalConfig()
408
def test_calls_read_filenames(self):
409
# replace the class that is constructed, to check its parameters
410
oldparserclass = config.ConfigObj
411
config.ConfigObj = InstrumentedConfigObj
412
my_config = config.GlobalConfig()
414
parser = my_config._get_parser()
416
config.ConfigObj = oldparserclass
417
self.failUnless(isinstance(parser, InstrumentedConfigObj))
418
self.assertEqual(parser._calls, [('__init__', config.config_filename(),
422
class TestBranchConfig(tests.TestCaseWithTransport):
424
def test_constructs(self):
425
branch = FakeBranch()
426
my_config = config.BranchConfig(branch)
427
self.assertRaises(TypeError, config.BranchConfig)
429
def test_get_location_config(self):
430
branch = FakeBranch()
431
my_config = config.BranchConfig(branch)
432
location_config = my_config._get_location_config()
433
self.assertEqual(branch.base, location_config.location)
434
self.failUnless(location_config is my_config._get_location_config())
436
def test_get_config(self):
437
"""The Branch.get_config method works properly"""
438
b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
439
my_config = b.get_config()
440
self.assertIs(my_config.get_user_option('wacky'), None)
441
my_config.set_user_option('wacky', 'unlikely')
442
self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
444
# Ensure we get the same thing if we start again
445
b2 = branch.Branch.open('.')
446
my_config2 = b2.get_config()
447
self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
449
def test_has_explicit_nickname(self):
450
b = self.make_branch('.')
451
self.assertFalse(b.get_config().has_explicit_nickname())
453
self.assertTrue(b.get_config().has_explicit_nickname())
455
def test_config_url(self):
456
"""The Branch.get_config will use section that uses a local url"""
457
branch = self.make_branch('branch')
458
self.assertEqual('branch', branch.nick)
460
locations = config.locations_config_filename()
461
config.ensure_config_dir_exists()
462
local_url = urlutils.local_path_to_url('branch')
463
open(locations, 'wb').write('[%s]\nnickname = foobar'
465
self.assertEqual('foobar', branch.nick)
467
def test_config_local_path(self):
468
"""The Branch.get_config will use a local system path"""
469
branch = self.make_branch('branch')
470
self.assertEqual('branch', branch.nick)
472
locations = config.locations_config_filename()
473
config.ensure_config_dir_exists()
474
open(locations, 'wb').write('[%s/branch]\nnickname = barry'
475
% (osutils.getcwd().encode('utf8'),))
476
self.assertEqual('barry', branch.nick)
478
def test_config_creates_local(self):
479
"""Creating a new entry in config uses a local path."""
480
branch = self.make_branch('branch', format='knit')
481
branch.set_push_location('http://foobar')
482
locations = config.locations_config_filename()
483
local_path = osutils.getcwd().encode('utf8')
484
# Surprisingly ConfigObj doesn't create a trailing newline
485
self.check_file_contents(locations,
487
'push_location = http://foobar\n'
488
'push_location:policy = norecurse\n'
491
def test_autonick_urlencoded(self):
492
b = self.make_branch('!repo')
493
self.assertEqual('!repo', b.get_config().get_nickname())
495
def test_warn_if_masked(self):
496
_warning = trace.warning
499
warnings.append(args[0] % args[1:])
501
def set_option(store, warn_masked=True):
503
conf.set_user_option('example_option', repr(store), store=store,
504
warn_masked=warn_masked)
505
def assertWarning(warning):
507
self.assertEqual(0, len(warnings))
509
self.assertEqual(1, len(warnings))
510
self.assertEqual(warning, warnings[0])
511
trace.warning = warning
513
branch = self.make_branch('.')
514
conf = branch.get_config()
515
set_option(config.STORE_GLOBAL)
517
set_option(config.STORE_BRANCH)
519
set_option(config.STORE_GLOBAL)
520
assertWarning('Value "4" is masked by "3" from branch.conf')
521
set_option(config.STORE_GLOBAL, warn_masked=False)
523
set_option(config.STORE_LOCATION)
525
set_option(config.STORE_BRANCH)
526
assertWarning('Value "3" is masked by "0" from locations.conf')
527
set_option(config.STORE_BRANCH, warn_masked=False)
530
trace.warning = _warning
533
class TestGlobalConfigItems(tests.TestCase):
535
def test_user_id(self):
536
config_file = StringIO(sample_config_text.encode('utf-8'))
537
my_config = config.GlobalConfig()
538
my_config._parser = my_config._get_parser(file=config_file)
539
self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
540
my_config._get_user_id())
542
def test_absent_user_id(self):
543
config_file = StringIO("")
544
my_config = config.GlobalConfig()
545
my_config._parser = my_config._get_parser(file=config_file)
546
self.assertEqual(None, my_config._get_user_id())
548
def test_configured_editor(self):
549
config_file = StringIO(sample_config_text.encode('utf-8'))
550
my_config = config.GlobalConfig()
551
my_config._parser = my_config._get_parser(file=config_file)
552
self.assertEqual("vim", my_config.get_editor())
554
def test_signatures_always(self):
555
config_file = StringIO(sample_always_signatures)
556
my_config = config.GlobalConfig()
557
my_config._parser = my_config._get_parser(file=config_file)
558
self.assertEqual(config.CHECK_NEVER,
559
my_config.signature_checking())
560
self.assertEqual(config.SIGN_ALWAYS,
561
my_config.signing_policy())
562
self.assertEqual(True, my_config.signature_needed())
564
def test_signatures_if_possible(self):
565
config_file = StringIO(sample_maybe_signatures)
566
my_config = config.GlobalConfig()
567
my_config._parser = my_config._get_parser(file=config_file)
568
self.assertEqual(config.CHECK_NEVER,
569
my_config.signature_checking())
570
self.assertEqual(config.SIGN_WHEN_REQUIRED,
571
my_config.signing_policy())
572
self.assertEqual(False, my_config.signature_needed())
574
def test_signatures_ignore(self):
575
config_file = StringIO(sample_ignore_signatures)
576
my_config = config.GlobalConfig()
577
my_config._parser = my_config._get_parser(file=config_file)
578
self.assertEqual(config.CHECK_ALWAYS,
579
my_config.signature_checking())
580
self.assertEqual(config.SIGN_NEVER,
581
my_config.signing_policy())
582
self.assertEqual(False, my_config.signature_needed())
584
def _get_sample_config(self):
585
config_file = StringIO(sample_config_text.encode('utf-8'))
586
my_config = config.GlobalConfig()
587
my_config._parser = my_config._get_parser(file=config_file)
590
def test_gpg_signing_command(self):
591
my_config = self._get_sample_config()
592
self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
593
self.assertEqual(False, my_config.signature_needed())
595
def _get_empty_config(self):
596
config_file = StringIO("")
597
my_config = config.GlobalConfig()
598
my_config._parser = my_config._get_parser(file=config_file)
601
def test_gpg_signing_command_unset(self):
602
my_config = self._get_empty_config()
603
self.assertEqual("gpg", my_config.gpg_signing_command())
605
def test_get_user_option_default(self):
606
my_config = self._get_empty_config()
607
self.assertEqual(None, my_config.get_user_option('no_option'))
609
def test_get_user_option_global(self):
610
my_config = self._get_sample_config()
611
self.assertEqual("something",
612
my_config.get_user_option('user_global_option'))
614
def test_post_commit_default(self):
615
my_config = self._get_sample_config()
616
self.assertEqual(None, my_config.post_commit())
618
def test_configured_logformat(self):
619
my_config = self._get_sample_config()
620
self.assertEqual("short", my_config.log_format())
622
def test_get_alias(self):
623
my_config = self._get_sample_config()
624
self.assertEqual('help', my_config.get_alias('h'))
626
def test_get_aliases(self):
627
my_config = self._get_sample_config()
628
aliases = my_config.get_aliases()
629
self.assertEqual(2, len(aliases))
630
sorted_keys = sorted(aliases)
631
self.assertEqual('help', aliases[sorted_keys[0]])
632
self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
634
def test_get_no_alias(self):
635
my_config = self._get_sample_config()
636
self.assertEqual(None, my_config.get_alias('foo'))
638
def test_get_long_alias(self):
639
my_config = self._get_sample_config()
640
self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
642
def test_get_change_editor(self):
643
my_config = self._get_sample_config()
644
change_editor = my_config.get_change_editor('old', 'new')
645
self.assertIs(diff.DiffFromTool, change_editor.__class__)
646
self.assertEqual('vimdiff -of @new_path @old_path',
647
' '.join(change_editor.command_template))
649
def test_get_no_change_editor(self):
650
my_config = self._get_empty_config()
651
change_editor = my_config.get_change_editor('old', 'new')
652
self.assertIs(None, change_editor)
655
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
657
def test_empty(self):
658
my_config = config.GlobalConfig()
659
self.assertEqual(0, len(my_config.get_aliases()))
661
def test_set_alias(self):
662
my_config = config.GlobalConfig()
663
alias_value = 'commit --strict'
664
my_config.set_alias('commit', alias_value)
665
new_config = config.GlobalConfig()
666
self.assertEqual(alias_value, new_config.get_alias('commit'))
668
def test_remove_alias(self):
669
my_config = config.GlobalConfig()
670
my_config.set_alias('commit', 'commit --strict')
671
# Now remove the alias again.
672
my_config.unset_alias('commit')
673
new_config = config.GlobalConfig()
674
self.assertIs(None, new_config.get_alias('commit'))
677
class TestLocationConfig(tests.TestCaseInTempDir):
679
def test_constructs(self):
680
my_config = config.LocationConfig('http://example.com')
681
self.assertRaises(TypeError, config.LocationConfig)
683
def test_branch_calls_read_filenames(self):
684
# This is testing the correct file names are provided.
685
# TODO: consolidate with the test for GlobalConfigs filename checks.
687
# replace the class that is constructed, to check its parameters
688
oldparserclass = config.ConfigObj
689
config.ConfigObj = InstrumentedConfigObj
691
my_config = config.LocationConfig('http://www.example.com')
692
parser = my_config._get_parser()
694
config.ConfigObj = oldparserclass
695
self.failUnless(isinstance(parser, InstrumentedConfigObj))
696
self.assertEqual(parser._calls,
697
[('__init__', config.locations_config_filename(),
699
config.ensure_config_dir_exists()
700
#os.mkdir(config.config_dir())
701
f = file(config.branches_config_filename(), 'wb')
704
oldparserclass = config.ConfigObj
705
config.ConfigObj = InstrumentedConfigObj
707
my_config = config.LocationConfig('http://www.example.com')
708
parser = my_config._get_parser()
710
config.ConfigObj = oldparserclass
712
def test_get_global_config(self):
713
my_config = config.BranchConfig(FakeBranch('http://example.com'))
714
global_config = my_config._get_global_config()
715
self.failUnless(isinstance(global_config, config.GlobalConfig))
716
self.failUnless(global_config is my_config._get_global_config())
718
def test__get_matching_sections_no_match(self):
719
self.get_branch_config('/')
720
self.assertEqual([], self.my_location_config._get_matching_sections())
722
def test__get_matching_sections_exact(self):
723
self.get_branch_config('http://www.example.com')
724
self.assertEqual([('http://www.example.com', '')],
725
self.my_location_config._get_matching_sections())
727
def test__get_matching_sections_suffix_does_not(self):
728
self.get_branch_config('http://www.example.com-com')
729
self.assertEqual([], self.my_location_config._get_matching_sections())
731
def test__get_matching_sections_subdir_recursive(self):
732
self.get_branch_config('http://www.example.com/com')
733
self.assertEqual([('http://www.example.com', 'com')],
734
self.my_location_config._get_matching_sections())
736
def test__get_matching_sections_ignoreparent(self):
737
self.get_branch_config('http://www.example.com/ignoreparent')
738
self.assertEqual([('http://www.example.com/ignoreparent', '')],
739
self.my_location_config._get_matching_sections())
741
def test__get_matching_sections_ignoreparent_subdir(self):
742
self.get_branch_config(
743
'http://www.example.com/ignoreparent/childbranch')
744
self.assertEqual([('http://www.example.com/ignoreparent',
746
self.my_location_config._get_matching_sections())
748
def test__get_matching_sections_subdir_trailing_slash(self):
749
self.get_branch_config('/b')
750
self.assertEqual([('/b/', '')],
751
self.my_location_config._get_matching_sections())
753
def test__get_matching_sections_subdir_child(self):
754
self.get_branch_config('/a/foo')
755
self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
756
self.my_location_config._get_matching_sections())
758
def test__get_matching_sections_subdir_child_child(self):
759
self.get_branch_config('/a/foo/bar')
760
self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
761
self.my_location_config._get_matching_sections())
763
def test__get_matching_sections_trailing_slash_with_children(self):
764
self.get_branch_config('/a/')
765
self.assertEqual([('/a/', '')],
766
self.my_location_config._get_matching_sections())
768
def test__get_matching_sections_explicit_over_glob(self):
769
# XXX: 2006-09-08 jamesh
770
# This test only passes because ord('c') > ord('*'). If there
771
# was a config section for '/a/?', it would get precedence
773
self.get_branch_config('/a/c')
774
self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
775
self.my_location_config._get_matching_sections())
777
def test__get_option_policy_normal(self):
778
self.get_branch_config('http://www.example.com')
780
self.my_location_config._get_config_policy(
781
'http://www.example.com', 'normal_option'),
784
def test__get_option_policy_norecurse(self):
785
self.get_branch_config('http://www.example.com')
787
self.my_location_config._get_option_policy(
788
'http://www.example.com', 'norecurse_option'),
789
config.POLICY_NORECURSE)
790
# Test old recurse=False setting:
792
self.my_location_config._get_option_policy(
793
'http://www.example.com/norecurse', 'normal_option'),
794
config.POLICY_NORECURSE)
796
def test__get_option_policy_normal(self):
797
self.get_branch_config('http://www.example.com')
799
self.my_location_config._get_option_policy(
800
'http://www.example.com', 'appendpath_option'),
801
config.POLICY_APPENDPATH)
803
def test_location_without_username(self):
804
self.get_branch_config('http://www.example.com/ignoreparent')
805
self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
806
self.my_config.username())
808
def test_location_not_listed(self):
809
"""Test that the global username is used when no location matches"""
810
self.get_branch_config('/home/robertc/sources')
811
self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
812
self.my_config.username())
814
def test_overriding_location(self):
815
self.get_branch_config('http://www.example.com/foo')
816
self.assertEqual('Robert Collins <robertc@example.org>',
817
self.my_config.username())
819
def test_signatures_not_set(self):
820
self.get_branch_config('http://www.example.com',
821
global_config=sample_ignore_signatures)
822
self.assertEqual(config.CHECK_ALWAYS,
823
self.my_config.signature_checking())
824
self.assertEqual(config.SIGN_NEVER,
825
self.my_config.signing_policy())
827
def test_signatures_never(self):
828
self.get_branch_config('/a/c')
829
self.assertEqual(config.CHECK_NEVER,
830
self.my_config.signature_checking())
832
def test_signatures_when_available(self):
833
self.get_branch_config('/a/', global_config=sample_ignore_signatures)
834
self.assertEqual(config.CHECK_IF_POSSIBLE,
835
self.my_config.signature_checking())
837
def test_signatures_always(self):
838
self.get_branch_config('/b')
839
self.assertEqual(config.CHECK_ALWAYS,
840
self.my_config.signature_checking())
842
def test_gpg_signing_command(self):
843
self.get_branch_config('/b')
844
self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
846
def test_gpg_signing_command_missing(self):
847
self.get_branch_config('/a')
848
self.assertEqual("false", self.my_config.gpg_signing_command())
850
def test_get_user_option_global(self):
851
self.get_branch_config('/a')
852
self.assertEqual('something',
853
self.my_config.get_user_option('user_global_option'))
855
def test_get_user_option_local(self):
856
self.get_branch_config('/a')
857
self.assertEqual('local',
858
self.my_config.get_user_option('user_local_option'))
860
def test_get_user_option_appendpath(self):
861
# returned as is for the base path:
862
self.get_branch_config('http://www.example.com')
863
self.assertEqual('append',
864
self.my_config.get_user_option('appendpath_option'))
865
# Extra path components get appended:
866
self.get_branch_config('http://www.example.com/a/b/c')
867
self.assertEqual('append/a/b/c',
868
self.my_config.get_user_option('appendpath_option'))
869
# Overriden for http://www.example.com/dir, where it is a
871
self.get_branch_config('http://www.example.com/dir/a/b/c')
872
self.assertEqual('normal',
873
self.my_config.get_user_option('appendpath_option'))
875
def test_get_user_option_norecurse(self):
876
self.get_branch_config('http://www.example.com')
877
self.assertEqual('norecurse',
878
self.my_config.get_user_option('norecurse_option'))
879
self.get_branch_config('http://www.example.com/dir')
880
self.assertEqual(None,
881
self.my_config.get_user_option('norecurse_option'))
882
# http://www.example.com/norecurse is a recurse=False section
883
# that redefines normal_option. Subdirectories do not pick up
885
self.get_branch_config('http://www.example.com/norecurse')
886
self.assertEqual('norecurse',
887
self.my_config.get_user_option('normal_option'))
888
self.get_branch_config('http://www.example.com/norecurse/subdir')
889
self.assertEqual('normal',
890
self.my_config.get_user_option('normal_option'))
892
def test_set_user_option_norecurse(self):
893
self.get_branch_config('http://www.example.com')
894
self.my_config.set_user_option('foo', 'bar',
895
store=config.STORE_LOCATION_NORECURSE)
897
self.my_location_config._get_option_policy(
898
'http://www.example.com', 'foo'),
899
config.POLICY_NORECURSE)
901
def test_set_user_option_appendpath(self):
902
self.get_branch_config('http://www.example.com')
903
self.my_config.set_user_option('foo', 'bar',
904
store=config.STORE_LOCATION_APPENDPATH)
906
self.my_location_config._get_option_policy(
907
'http://www.example.com', 'foo'),
908
config.POLICY_APPENDPATH)
910
def test_set_user_option_change_policy(self):
911
self.get_branch_config('http://www.example.com')
912
self.my_config.set_user_option('norecurse_option', 'normal',
913
store=config.STORE_LOCATION)
915
self.my_location_config._get_option_policy(
916
'http://www.example.com', 'norecurse_option'),
919
def test_set_user_option_recurse_false_section(self):
920
# The following section has recurse=False set. The test is to
921
# make sure that a normal option can be added to the section,
922
# converting recurse=False to the norecurse policy.
923
self.get_branch_config('http://www.example.com/norecurse')
924
self.callDeprecated(['The recurse option is deprecated as of 0.14. '
925
'The section "http://www.example.com/norecurse" '
926
'has been converted to use policies.'],
927
self.my_config.set_user_option,
928
'foo', 'bar', store=config.STORE_LOCATION)
930
self.my_location_config._get_option_policy(
931
'http://www.example.com/norecurse', 'foo'),
933
# The previously existing option is still norecurse:
935
self.my_location_config._get_option_policy(
936
'http://www.example.com/norecurse', 'normal_option'),
937
config.POLICY_NORECURSE)
939
def test_post_commit_default(self):
940
self.get_branch_config('/a/c')
941
self.assertEqual('bzrlib.tests.test_config.post_commit',
942
self.my_config.post_commit())
944
def get_branch_config(self, location, global_config=None):
945
if global_config is None:
946
global_file = StringIO(sample_config_text.encode('utf-8'))
948
global_file = StringIO(global_config.encode('utf-8'))
949
branches_file = StringIO(sample_branches_text.encode('utf-8'))
950
self.my_config = config.BranchConfig(FakeBranch(location))
951
# Force location config to use specified file
952
self.my_location_config = self.my_config._get_location_config()
953
self.my_location_config._get_parser(branches_file)
954
# Force global config to use specified file
955
self.my_config._get_global_config()._get_parser(global_file)
957
def test_set_user_setting_sets_and_saves(self):
958
self.get_branch_config('/a/c')
959
record = InstrumentedConfigObj("foo")
960
self.my_location_config._parser = record
962
real_mkdir = os.mkdir
964
def checked_mkdir(path, mode=0777):
965
self.log('making directory: %s', path)
966
real_mkdir(path, mode)
969
os.mkdir = checked_mkdir
971
self.callDeprecated(['The recurse option is deprecated as of '
972
'0.14. The section "/a/c" has been '
973
'converted to use policies.'],
974
self.my_config.set_user_option,
975
'foo', 'bar', store=config.STORE_LOCATION)
977
os.mkdir = real_mkdir
979
self.failUnless(self.created, 'Failed to create ~/.bazaar')
980
self.assertEqual([('__contains__', '/a/c'),
981
('__contains__', '/a/c/'),
982
('__setitem__', '/a/c', {}),
983
('__getitem__', '/a/c'),
984
('__setitem__', 'foo', 'bar'),
985
('__getitem__', '/a/c'),
986
('as_bool', 'recurse'),
987
('__getitem__', '/a/c'),
988
('__delitem__', 'recurse'),
989
('__getitem__', '/a/c'),
991
('__getitem__', '/a/c'),
992
('__contains__', 'foo:policy'),
996
def test_set_user_setting_sets_and_saves2(self):
997
self.get_branch_config('/a/c')
998
self.assertIs(self.my_config.get_user_option('foo'), None)
999
self.my_config.set_user_option('foo', 'bar')
1001
self.my_config.branch.control_files.files['branch.conf'].strip(),
1003
self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
1004
self.my_config.set_user_option('foo', 'baz',
1005
store=config.STORE_LOCATION)
1006
self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1007
self.my_config.set_user_option('foo', 'qux')
1008
self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1010
def test_get_bzr_remote_path(self):
1011
my_config = config.LocationConfig('/a/c')
1012
self.assertEqual('bzr', my_config.get_bzr_remote_path())
1013
my_config.set_user_option('bzr_remote_path', '/path-bzr')
1014
self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1015
os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
1016
self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1019
precedence_global = 'option = global'
1020
precedence_branch = 'option = branch'
1021
precedence_location = """
1025
[http://example.com/specific]
1030
class TestBranchConfigItems(tests.TestCaseInTempDir):
1032
def get_branch_config(self, global_config=None, location=None,
1033
location_config=None, branch_data_config=None):
1034
my_config = config.BranchConfig(FakeBranch(location))
1035
if global_config is not None:
1036
global_file = StringIO(global_config.encode('utf-8'))
1037
my_config._get_global_config()._get_parser(global_file)
1038
self.my_location_config = my_config._get_location_config()
1039
if location_config is not None:
1040
location_file = StringIO(location_config.encode('utf-8'))
1041
self.my_location_config._get_parser(location_file)
1042
if branch_data_config is not None:
1043
my_config.branch.control_files.files['branch.conf'] = \
1047
def test_user_id(self):
1048
branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
1049
my_config = config.BranchConfig(branch)
1050
self.assertEqual("Robert Collins <robertc@example.net>",
1051
my_config.username())
1052
my_config.branch.control_files.files['email'] = "John"
1053
my_config.set_user_option('email',
1054
"Robert Collins <robertc@example.org>")
1055
self.assertEqual("John", my_config.username())
1056
del my_config.branch.control_files.files['email']
1057
self.assertEqual("Robert Collins <robertc@example.org>",
1058
my_config.username())
1060
def test_not_set_in_branch(self):
1061
my_config = self.get_branch_config(sample_config_text)
1062
self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1063
my_config._get_user_id())
1064
my_config.branch.control_files.files['email'] = "John"
1065
self.assertEqual("John", my_config._get_user_id())
1067
def test_BZR_EMAIL_OVERRIDES(self):
1068
os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
1069
branch = FakeBranch()
1070
my_config = config.BranchConfig(branch)
1071
self.assertEqual("Robert Collins <robertc@example.org>",
1072
my_config.username())
1074
def test_signatures_forced(self):
1075
my_config = self.get_branch_config(
1076
global_config=sample_always_signatures)
1077
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1078
self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1079
self.assertTrue(my_config.signature_needed())
1081
def test_signatures_forced_branch(self):
1082
my_config = self.get_branch_config(
1083
global_config=sample_ignore_signatures,
1084
branch_data_config=sample_always_signatures)
1085
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1086
self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1087
self.assertTrue(my_config.signature_needed())
1089
def test_gpg_signing_command(self):
1090
my_config = self.get_branch_config(
1091
# branch data cannot set gpg_signing_command
1092
branch_data_config="gpg_signing_command=pgp")
1093
config_file = StringIO(sample_config_text.encode('utf-8'))
1094
my_config._get_global_config()._get_parser(config_file)
1095
self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1097
def test_get_user_option_global(self):
1098
branch = FakeBranch()
1099
my_config = config.BranchConfig(branch)
1100
config_file = StringIO(sample_config_text.encode('utf-8'))
1101
(my_config._get_global_config()._get_parser(config_file))
1102
self.assertEqual('something',
1103
my_config.get_user_option('user_global_option'))
1105
def test_post_commit_default(self):
1106
branch = FakeBranch()
1107
my_config = self.get_branch_config(sample_config_text, '/a/c',
1108
sample_branches_text)
1109
self.assertEqual(my_config.branch.base, '/a/c')
1110
self.assertEqual('bzrlib.tests.test_config.post_commit',
1111
my_config.post_commit())
1112
my_config.set_user_option('post_commit', 'rmtree_root')
1113
# post-commit is ignored when bresent in branch data
1114
self.assertEqual('bzrlib.tests.test_config.post_commit',
1115
my_config.post_commit())
1116
my_config.set_user_option('post_commit', 'rmtree_root',
1117
store=config.STORE_LOCATION)
1118
self.assertEqual('rmtree_root', my_config.post_commit())
1120
def test_config_precedence(self):
1121
my_config = self.get_branch_config(global_config=precedence_global)
1122
self.assertEqual(my_config.get_user_option('option'), 'global')
1123
my_config = self.get_branch_config(global_config=precedence_global,
1124
branch_data_config=precedence_branch)
1125
self.assertEqual(my_config.get_user_option('option'), 'branch')
1126
my_config = self.get_branch_config(global_config=precedence_global,
1127
branch_data_config=precedence_branch,
1128
location_config=precedence_location)
1129
self.assertEqual(my_config.get_user_option('option'), 'recurse')
1130
my_config = self.get_branch_config(global_config=precedence_global,
1131
branch_data_config=precedence_branch,
1132
location_config=precedence_location,
1133
location='http://example.com/specific')
1134
self.assertEqual(my_config.get_user_option('option'), 'exact')
1136
def test_get_mail_client(self):
1137
config = self.get_branch_config()
1138
client = config.get_mail_client()
1139
self.assertIsInstance(client, mail_client.DefaultMail)
1142
config.set_user_option('mail_client', 'evolution')
1143
client = config.get_mail_client()
1144
self.assertIsInstance(client, mail_client.Evolution)
1146
config.set_user_option('mail_client', 'kmail')
1147
client = config.get_mail_client()
1148
self.assertIsInstance(client, mail_client.KMail)
1150
config.set_user_option('mail_client', 'mutt')
1151
client = config.get_mail_client()
1152
self.assertIsInstance(client, mail_client.Mutt)
1154
config.set_user_option('mail_client', 'thunderbird')
1155
client = config.get_mail_client()
1156
self.assertIsInstance(client, mail_client.Thunderbird)
1159
config.set_user_option('mail_client', 'default')
1160
client = config.get_mail_client()
1161
self.assertIsInstance(client, mail_client.DefaultMail)
1163
config.set_user_option('mail_client', 'editor')
1164
client = config.get_mail_client()
1165
self.assertIsInstance(client, mail_client.Editor)
1167
config.set_user_option('mail_client', 'mapi')
1168
client = config.get_mail_client()
1169
self.assertIsInstance(client, mail_client.MAPIClient)
1171
config.set_user_option('mail_client', 'xdg-email')
1172
client = config.get_mail_client()
1173
self.assertIsInstance(client, mail_client.XDGEmail)
1175
config.set_user_option('mail_client', 'firebird')
1176
self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1179
class TestMailAddressExtraction(tests.TestCase):
1181
def test_extract_email_address(self):
1182
self.assertEqual('jane@test.com',
1183
config.extract_email_address('Jane <jane@test.com>'))
1184
self.assertRaises(errors.NoEmailInUsername,
1185
config.extract_email_address, 'Jane Tester')
1187
def test_parse_username(self):
1188
self.assertEqual(('', 'jdoe@example.com'),
1189
config.parse_username('jdoe@example.com'))
1190
self.assertEqual(('', 'jdoe@example.com'),
1191
config.parse_username('<jdoe@example.com>'))
1192
self.assertEqual(('John Doe', 'jdoe@example.com'),
1193
config.parse_username('John Doe <jdoe@example.com>'))
1194
self.assertEqual(('John Doe', ''),
1195
config.parse_username('John Doe'))
1196
self.assertEqual(('John Doe', 'jdoe@example.com'),
1197
config.parse_username('John Doe jdoe@example.com'))
1199
class TestTreeConfig(tests.TestCaseWithTransport):
1201
def test_get_value(self):
1202
"""Test that retreiving a value from a section is possible"""
1203
branch = self.make_branch('.')
1204
tree_config = config.TreeConfig(branch)
1205
tree_config.set_option('value', 'key', 'SECTION')
1206
tree_config.set_option('value2', 'key2')
1207
tree_config.set_option('value3-top', 'key3')
1208
tree_config.set_option('value3-section', 'key3', 'SECTION')
1209
value = tree_config.get_option('key', 'SECTION')
1210
self.assertEqual(value, 'value')
1211
value = tree_config.get_option('key2')
1212
self.assertEqual(value, 'value2')
1213
self.assertEqual(tree_config.get_option('non-existant'), None)
1214
value = tree_config.get_option('non-existant', 'SECTION')
1215
self.assertEqual(value, None)
1216
value = tree_config.get_option('non-existant', default='default')
1217
self.assertEqual(value, 'default')
1218
self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1219
value = tree_config.get_option('key2', 'NOSECTION', default='default')
1220
self.assertEqual(value, 'default')
1221
value = tree_config.get_option('key3')
1222
self.assertEqual(value, 'value3-top')
1223
value = tree_config.get_option('key3', 'SECTION')
1224
self.assertEqual(value, 'value3-section')
1227
class TestTransportConfig(tests.TestCaseWithTransport):
1229
def test_get_value(self):
1230
"""Test that retreiving a value from a section is possible"""
1231
bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1233
bzrdir_config.set_option('value', 'key', 'SECTION')
1234
bzrdir_config.set_option('value2', 'key2')
1235
bzrdir_config.set_option('value3-top', 'key3')
1236
bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1237
value = bzrdir_config.get_option('key', 'SECTION')
1238
self.assertEqual(value, 'value')
1239
value = bzrdir_config.get_option('key2')
1240
self.assertEqual(value, 'value2')
1241
self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1242
value = bzrdir_config.get_option('non-existant', 'SECTION')
1243
self.assertEqual(value, None)
1244
value = bzrdir_config.get_option('non-existant', default='default')
1245
self.assertEqual(value, 'default')
1246
self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1247
value = bzrdir_config.get_option('key2', 'NOSECTION',
1249
self.assertEqual(value, 'default')
1250
value = bzrdir_config.get_option('key3')
1251
self.assertEqual(value, 'value3-top')
1252
value = bzrdir_config.get_option('key3', 'SECTION')
1253
self.assertEqual(value, 'value3-section')
1255
def test_set_unset_default_stack_on(self):
1256
my_dir = self.make_bzrdir('.')
1257
bzrdir_config = config.BzrDirConfig(my_dir)
1258
self.assertIs(None, bzrdir_config.get_default_stack_on())
1259
bzrdir_config.set_default_stack_on('Foo')
1260
self.assertEqual('Foo', bzrdir_config._config.get_option(
1261
'default_stack_on'))
1262
self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1263
bzrdir_config.set_default_stack_on(None)
1264
self.assertIs(None, bzrdir_config.get_default_stack_on())
1267
class TestAuthenticationConfigFile(tests.TestCase):
1268
"""Test the authentication.conf file matching"""
1270
def _got_user_passwd(self, expected_user, expected_password,
1271
config, *args, **kwargs):
1272
credentials = config.get_credentials(*args, **kwargs)
1273
if credentials is None:
1277
user = credentials['user']
1278
password = credentials['password']
1279
self.assertEquals(expected_user, user)
1280
self.assertEquals(expected_password, password)
1282
def test_empty_config(self):
1283
conf = config.AuthenticationConfig(_file=StringIO())
1284
self.assertEquals({}, conf._get_config())
1285
self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1287
def test_missing_auth_section_header(self):
1288
conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1289
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1291
def test_auth_section_header_not_closed(self):
1292
conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1293
self.assertRaises(errors.ParseConfigError, conf._get_config)
1295
def test_auth_value_not_boolean(self):
1296
conf = config.AuthenticationConfig(_file=StringIO(
1300
verify_certificates=askme # Error: Not a boolean
1302
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1304
def test_auth_value_not_int(self):
1305
conf = config.AuthenticationConfig(_file=StringIO(
1309
port=port # Error: Not an int
1311
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1313
def test_unknown_password_encoding(self):
1314
conf = config.AuthenticationConfig(_file=StringIO(
1318
password_encoding=unknown
1320
self.assertRaises(ValueError, conf.get_password,
1321
'ftp', 'foo.net', 'joe')
1323
def test_credentials_for_scheme_host(self):
1324
conf = config.AuthenticationConfig(_file=StringIO(
1325
"""# Identity on foo.net
1330
password=secret-pass
1333
self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1335
self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1337
self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1339
def test_credentials_for_host_port(self):
1340
conf = config.AuthenticationConfig(_file=StringIO(
1341
"""# Identity on foo.net
1347
password=secret-pass
1350
self._got_user_passwd('joe', 'secret-pass',
1351
conf, 'ftp', 'foo.net', port=10021)
1353
self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1355
def test_for_matching_host(self):
1356
conf = config.AuthenticationConfig(_file=StringIO(
1357
"""# Identity on foo.net
1363
[sourceforge domain]
1370
self._got_user_passwd('georges', 'bendover',
1371
conf, 'bzr', 'foo.bzr.sf.net')
1373
self._got_user_passwd(None, None,
1374
conf, 'bzr', 'bbzr.sf.net')
1376
def test_for_matching_host_None(self):
1377
conf = config.AuthenticationConfig(_file=StringIO(
1378
"""# Identity on foo.net
1388
self._got_user_passwd('joe', 'joepass',
1389
conf, 'bzr', 'quux.net')
1390
# no host but different scheme
1391
self._got_user_passwd('georges', 'bendover',
1392
conf, 'ftp', 'quux.net')
1394
def test_credentials_for_path(self):
1395
conf = config.AuthenticationConfig(_file=StringIO(
1411
self._got_user_passwd(None, None,
1412
conf, 'http', host='bar.org', path='/dir3')
1414
self._got_user_passwd('georges', 'bendover',
1415
conf, 'http', host='bar.org', path='/dir2')
1417
self._got_user_passwd('jim', 'jimpass',
1418
conf, 'http', host='bar.org',path='/dir1/subdir')
1420
def test_credentials_for_user(self):
1421
conf = config.AuthenticationConfig(_file=StringIO(
1430
self._got_user_passwd('jim', 'jimpass',
1431
conf, 'http', 'bar.org')
1433
self._got_user_passwd('jim', 'jimpass',
1434
conf, 'http', 'bar.org', user='jim')
1435
# Don't get a different user if one is specified
1436
self._got_user_passwd(None, None,
1437
conf, 'http', 'bar.org', user='georges')
1439
def test_credentials_for_user_without_password(self):
1440
conf = config.AuthenticationConfig(_file=StringIO(
1447
# Get user but no password
1448
self._got_user_passwd('jim', None,
1449
conf, 'http', 'bar.org')
1451
def test_verify_certificates(self):
1452
conf = config.AuthenticationConfig(_file=StringIO(
1459
verify_certificates=False
1466
credentials = conf.get_credentials('https', 'bar.org')
1467
self.assertEquals(False, credentials.get('verify_certificates'))
1468
credentials = conf.get_credentials('https', 'foo.net')
1469
self.assertEquals(True, credentials.get('verify_certificates'))
1472
class TestAuthenticationStorage(tests.TestCaseInTempDir):
1474
def test_set_credentials(self):
1475
conf = config.AuthenticationConfig()
1476
conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
1477
99, path='/foo', verify_certificates=False, realm='realm')
1478
credentials = conf.get_credentials(host='host', scheme='scheme',
1479
port=99, path='/foo',
1481
CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
1482
'verify_certificates': False, 'scheme': 'scheme',
1483
'host': 'host', 'port': 99, 'path': '/foo',
1485
self.assertEqual(CREDENTIALS, credentials)
1486
credentials_from_disk = config.AuthenticationConfig().get_credentials(
1487
host='host', scheme='scheme', port=99, path='/foo', realm='realm')
1488
self.assertEqual(CREDENTIALS, credentials_from_disk)
1490
def test_reset_credentials_different_name(self):
1491
conf = config.AuthenticationConfig()
1492
conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
1493
conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
1494
self.assertIs(None, conf._get_config().get('name'))
1495
credentials = conf.get_credentials(host='host', scheme='scheme')
1496
CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
1497
'password', 'verify_certificates': True,
1498
'scheme': 'scheme', 'host': 'host', 'port': None,
1499
'path': None, 'realm': None}
1500
self.assertEqual(CREDENTIALS, credentials)
1503
class TestAuthenticationConfig(tests.TestCase):
1504
"""Test AuthenticationConfig behaviour"""
1506
def _check_default_password_prompt(self, expected_prompt_format, scheme,
1507
host=None, port=None, realm=None,
1511
user, password = 'jim', 'precious'
1512
expected_prompt = expected_prompt_format % {
1513
'scheme': scheme, 'host': host, 'port': port,
1514
'user': user, 'realm': realm}
1516
stdout = tests.StringIOWrapper()
1517
stderr = tests.StringIOWrapper()
1518
ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
1519
stdout=stdout, stderr=stderr)
1520
# We use an empty conf so that the user is always prompted
1521
conf = config.AuthenticationConfig()
1522
self.assertEquals(password,
1523
conf.get_password(scheme, host, user, port=port,
1524
realm=realm, path=path))
1525
self.assertEquals(expected_prompt, stderr.getvalue())
1526
self.assertEquals('', stdout.getvalue())
1528
def _check_default_username_prompt(self, expected_prompt_format, scheme,
1529
host=None, port=None, realm=None,
1534
expected_prompt = expected_prompt_format % {
1535
'scheme': scheme, 'host': host, 'port': port,
1537
stdout = tests.StringIOWrapper()
1538
stderr = tests.StringIOWrapper()
1539
ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
1540
stdout=stdout, stderr=stderr)
1541
# We use an empty conf so that the user is always prompted
1542
conf = config.AuthenticationConfig()
1543
self.assertEquals(username, conf.get_user(scheme, host, port=port,
1544
realm=realm, path=path, ask=True))
1545
self.assertEquals(expected_prompt, stderr.getvalue())
1546
self.assertEquals('', stdout.getvalue())
1548
def test_username_defaults_prompts(self):
1549
# HTTP prompts can't be tested here, see test_http.py
1550
self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
1551
self._check_default_username_prompt(
1552
'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
1553
self._check_default_username_prompt(
1554
'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1556
def test_username_default_no_prompt(self):
1557
conf = config.AuthenticationConfig()
1558
self.assertEquals(None,
1559
conf.get_user('ftp', 'example.com'))
1560
self.assertEquals("explicitdefault",
1561
conf.get_user('ftp', 'example.com', default="explicitdefault"))
1563
def test_password_default_prompts(self):
1564
# HTTP prompts can't be tested here, see test_http.py
1565
self._check_default_password_prompt(
1566
'FTP %(user)s@%(host)s password: ', 'ftp')
1567
self._check_default_password_prompt(
1568
'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
1569
self._check_default_password_prompt(
1570
'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
1571
# SMTP port handling is a bit special (it's handled if embedded in the
1573
# FIXME: should we: forbid that, extend it to other schemes, leave
1574
# things as they are that's fine thank you ?
1575
self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
1577
self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
1578
'smtp', host='bar.org:10025')
1579
self._check_default_password_prompt(
1580
'SMTP %(user)s@%(host)s:%(port)d password: ',
1583
def test_ssh_password_emits_warning(self):
1584
conf = config.AuthenticationConfig(_file=StringIO(
1592
entered_password = 'typed-by-hand'
1593
stdout = tests.StringIOWrapper()
1594
stderr = tests.StringIOWrapper()
1595
ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
1596
stdout=stdout, stderr=stderr)
1598
# Since the password defined in the authentication config is ignored,
1599
# the user is prompted
1600
self.assertEquals(entered_password,
1601
conf.get_password('ssh', 'bar.org', user='jim'))
1602
self.assertContainsRe(
1603
self._get_log(keep_log_file=True),
1604
'password ignored in section \[ssh with password\]')
1606
def test_ssh_without_password_doesnt_emit_warning(self):
1607
conf = config.AuthenticationConfig(_file=StringIO(
1614
entered_password = 'typed-by-hand'
1615
stdout = tests.StringIOWrapper()
1616
stderr = tests.StringIOWrapper()
1617
ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
1621
# Since the password defined in the authentication config is ignored,
1622
# the user is prompted
1623
self.assertEquals(entered_password,
1624
conf.get_password('ssh', 'bar.org', user='jim'))
1625
# No warning shoud be emitted since there is no password. We are only
1627
self.assertNotContainsRe(
1628
self._get_log(keep_log_file=True),
1629
'password ignored in section \[ssh with password\]')
1631
def test_uses_fallback_stores(self):
1632
self._old_cs_registry = config.credential_store_registry
1634
config.credential_store_registry = self._old_cs_registry
1635
self.addCleanup(restore)
1636
config.credential_store_registry = config.CredentialStoreRegistry()
1637
store = StubCredentialStore()
1638
store.add_credentials("http", "example.com", "joe", "secret")
1639
config.credential_store_registry.register("stub", store, fallback=True)
1640
conf = config.AuthenticationConfig(_file=StringIO())
1641
creds = conf.get_credentials("http", "example.com")
1642
self.assertEquals("joe", creds["user"])
1643
self.assertEquals("secret", creds["password"])
1646
class StubCredentialStore(config.CredentialStore):
1652
def add_credentials(self, scheme, host, user, password=None):
1653
self._username[(scheme, host)] = user
1654
self._password[(scheme, host)] = password
1656
def get_credentials(self, scheme, host, port=None, user=None,
1657
path=None, realm=None):
1658
key = (scheme, host)
1659
if not key in self._username:
1661
return { "scheme": scheme, "host": host, "port": port,
1662
"user": self._username[key], "password": self._password[key]}
1665
class CountingCredentialStore(config.CredentialStore):
1670
def get_credentials(self, scheme, host, port=None, user=None,
1671
path=None, realm=None):
1676
class TestCredentialStoreRegistry(tests.TestCase):
1678
def _get_cs_registry(self):
1679
return config.credential_store_registry
1681
def test_default_credential_store(self):
1682
r = self._get_cs_registry()
1683
default = r.get_credential_store(None)
1684
self.assertIsInstance(default, config.PlainTextCredentialStore)
1686
def test_unknown_credential_store(self):
1687
r = self._get_cs_registry()
1688
# It's hard to imagine someone creating a credential store named
1689
# 'unknown' so we use that as an never registered key.
1690
self.assertRaises(KeyError, r.get_credential_store, 'unknown')
1692
def test_fallback_none_registered(self):
1693
r = config.CredentialStoreRegistry()
1694
self.assertEquals(None,
1695
r.get_fallback_credentials("http", "example.com"))
1697
def test_register(self):
1698
r = config.CredentialStoreRegistry()
1699
r.register("stub", StubCredentialStore(), fallback=False)
1700
r.register("another", StubCredentialStore(), fallback=True)
1701
self.assertEquals(["another", "stub"], r.keys())
1703
def test_register_lazy(self):
1704
r = config.CredentialStoreRegistry()
1705
r.register_lazy("stub", "bzrlib.tests.test_config",
1706
"StubCredentialStore", fallback=False)
1707
self.assertEquals(["stub"], r.keys())
1708
self.assertIsInstance(r.get_credential_store("stub"),
1709
StubCredentialStore)
1711
def test_is_fallback(self):
1712
r = config.CredentialStoreRegistry()
1713
r.register("stub1", None, fallback=False)
1714
r.register("stub2", None, fallback=True)
1715
self.assertEquals(False, r.is_fallback("stub1"))
1716
self.assertEquals(True, r.is_fallback("stub2"))
1718
def test_no_fallback(self):
1719
r = config.CredentialStoreRegistry()
1720
store = CountingCredentialStore()
1721
r.register("count", store, fallback=False)
1722
self.assertEquals(None,
1723
r.get_fallback_credentials("http", "example.com"))
1724
self.assertEquals(0, store._calls)
1726
def test_fallback_credentials(self):
1727
r = config.CredentialStoreRegistry()
1728
store = StubCredentialStore()
1729
store.add_credentials("http", "example.com",
1730
"somebody", "geheim")
1731
r.register("stub", store, fallback=True)
1732
creds = r.get_fallback_credentials("http", "example.com")
1733
self.assertEquals("somebody", creds["user"])
1734
self.assertEquals("geheim", creds["password"])
1736
def test_fallback_first_wins(self):
1737
r = config.CredentialStoreRegistry()
1738
stub1 = StubCredentialStore()
1739
stub1.add_credentials("http", "example.com",
1740
"somebody", "stub1")
1741
r.register("stub1", stub1, fallback=True)
1742
stub2 = StubCredentialStore()
1743
stub2.add_credentials("http", "example.com",
1744
"somebody", "stub2")
1745
r.register("stub2", stub1, fallback=True)
1746
creds = r.get_fallback_credentials("http", "example.com")
1747
self.assertEquals("somebody", creds["user"])
1748
self.assertEquals("stub1", creds["password"])
1751
class TestPlainTextCredentialStore(tests.TestCase):
1753
def test_decode_password(self):
1754
r = config.credential_store_registry
1755
plain_text = r.get_credential_store()
1756
decoded = plain_text.decode_password(dict(password='secret'))
1757
self.assertEquals('secret', decoded)
1760
# FIXME: Once we have a way to declare authentication to all test servers, we
1761
# can implement generic tests.
1762
# test_user_password_in_url
1763
# test_user_in_url_password_from_config
1764
# test_user_in_url_password_prompted
1765
# test_user_in_config
1766
# test_user_getpass.getuser
1767
# test_user_prompted ?
1768
class TestAuthenticationRing(tests.TestCaseWithTransport):