1
# Copyright (C) 2005, 2006 Canonical Ltd
2
# Authors: Robert Collins <robert.collins@canonical.com>
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
"""Tests for finding and reading the bzr config file[s]."""
19
# import system imports here
20
from bzrlib.util.configobj.configobj import ConfigObj, ConfigObjError
21
from cStringIO import StringIO
25
#import bzrlib specific imports here
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.control_files = FakeControlFiles(user_id=user_id)
151
def lock_write(self):
158
class FakeControlFiles(object):
160
def __init__(self, user_id=None):
164
def get_utf8(self, filename):
165
if filename != 'email':
166
raise NotImplementedError
167
if self.email is not None:
168
return StringIO(self.email)
169
raise errors.NoSuchFile(filename)
171
def get(self, filename):
173
return StringIO(self.files[filename])
175
raise errors.NoSuchFile(filename)
177
def put(self, filename, fileobj):
178
self.files[filename] = fileobj.read()
181
class InstrumentedConfig(config.Config):
182
"""An instrumented config that supplies stubs for template methods."""
185
super(InstrumentedConfig, self).__init__()
187
self._signatures = config.CHECK_NEVER
189
def _get_user_id(self):
190
self._calls.append('_get_user_id')
191
return "Robert Collins <robert.collins@example.org>"
193
def _get_signature_checking(self):
194
self._calls.append('_get_signature_checking')
195
return self._signatures
198
bool_config = """[DEFAULT]
205
class TestConfigObj(tests.TestCase):
206
def test_get_bool(self):
207
from bzrlib.config import ConfigObj
208
co = ConfigObj(StringIO(bool_config))
209
self.assertIs(co.get_bool('DEFAULT', 'active'), True)
210
self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
211
self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
212
self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
215
erroneous_config = """[section] # line 1
218
whocares=notme # line 4
220
class TestConfigObjErrors(tests.TestCase):
222
def test_duplicate_section_name_error_line(self):
224
co = ConfigObj(StringIO(erroneous_config), raise_errors=True)
225
except config.configobj.DuplicateError, e:
226
self.assertEqual(3, e.line_number)
228
self.fail('Error in config file not detected')
230
class TestConfig(tests.TestCase):
232
def test_constructs(self):
235
def test_no_default_editor(self):
236
self.assertRaises(NotImplementedError, config.Config().get_editor)
238
def test_user_email(self):
239
my_config = InstrumentedConfig()
240
self.assertEqual('robert.collins@example.org', my_config.user_email())
241
self.assertEqual(['_get_user_id'], my_config._calls)
243
def test_username(self):
244
my_config = InstrumentedConfig()
245
self.assertEqual('Robert Collins <robert.collins@example.org>',
246
my_config.username())
247
self.assertEqual(['_get_user_id'], my_config._calls)
249
def test_signatures_default(self):
250
my_config = config.Config()
251
self.assertFalse(my_config.signature_needed())
252
self.assertEqual(config.CHECK_IF_POSSIBLE,
253
my_config.signature_checking())
254
self.assertEqual(config.SIGN_WHEN_REQUIRED,
255
my_config.signing_policy())
257
def test_signatures_template_method(self):
258
my_config = InstrumentedConfig()
259
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
260
self.assertEqual(['_get_signature_checking'], my_config._calls)
262
def test_signatures_template_method_none(self):
263
my_config = InstrumentedConfig()
264
my_config._signatures = None
265
self.assertEqual(config.CHECK_IF_POSSIBLE,
266
my_config.signature_checking())
267
self.assertEqual(['_get_signature_checking'], my_config._calls)
269
def test_gpg_signing_command_default(self):
270
my_config = config.Config()
271
self.assertEqual('gpg', my_config.gpg_signing_command())
273
def test_get_user_option_default(self):
274
my_config = config.Config()
275
self.assertEqual(None, my_config.get_user_option('no_option'))
277
def test_post_commit_default(self):
278
my_config = config.Config()
279
self.assertEqual(None, my_config.post_commit())
281
def test_log_format_default(self):
282
my_config = config.Config()
283
self.assertEqual('long', my_config.log_format())
286
class TestConfigPath(tests.TestCase):
289
super(TestConfigPath, self).setUp()
290
os.environ['HOME'] = '/home/bogus'
291
if sys.platform == 'win32':
292
os.environ['BZR_HOME'] = \
293
r'C:\Documents and Settings\bogus\Application Data'
295
def test_config_dir(self):
296
if sys.platform == 'win32':
297
self.assertEqual(config.config_dir(),
298
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0')
300
self.assertEqual(config.config_dir(), '/home/bogus/.bazaar')
302
def test_config_filename(self):
303
if sys.platform == 'win32':
304
self.assertEqual(config.config_filename(),
305
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/bazaar.conf')
307
self.assertEqual(config.config_filename(),
308
'/home/bogus/.bazaar/bazaar.conf')
310
def test_branches_config_filename(self):
311
if sys.platform == 'win32':
312
self.assertEqual(config.branches_config_filename(),
313
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/branches.conf')
315
self.assertEqual(config.branches_config_filename(),
316
'/home/bogus/.bazaar/branches.conf')
318
def test_locations_config_filename(self):
319
if sys.platform == 'win32':
320
self.assertEqual(config.locations_config_filename(),
321
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/locations.conf')
323
self.assertEqual(config.locations_config_filename(),
324
'/home/bogus/.bazaar/locations.conf')
326
def test_authentication_config_filename(self):
327
if sys.platform == 'win32':
328
self.assertEqual(config.authentication_config_filename(),
329
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/authentication.conf')
331
self.assertEqual(config.authentication_config_filename(),
332
'/home/bogus/.bazaar/authentication.conf')
334
class TestIniConfig(tests.TestCase):
336
def test_contructs(self):
337
my_config = config.IniBasedConfig("nothing")
339
def test_from_fp(self):
340
config_file = StringIO(sample_config_text.encode('utf-8'))
341
my_config = config.IniBasedConfig(None)
343
isinstance(my_config._get_parser(file=config_file),
346
def test_cached(self):
347
config_file = StringIO(sample_config_text.encode('utf-8'))
348
my_config = config.IniBasedConfig(None)
349
parser = my_config._get_parser(file=config_file)
350
self.failUnless(my_config._get_parser() is parser)
353
class TestGetConfig(tests.TestCase):
355
def test_constructs(self):
356
my_config = config.GlobalConfig()
358
def test_calls_read_filenames(self):
359
# replace the class that is constructured, to check its parameters
360
oldparserclass = config.ConfigObj
361
config.ConfigObj = InstrumentedConfigObj
362
my_config = config.GlobalConfig()
364
parser = my_config._get_parser()
366
config.ConfigObj = oldparserclass
367
self.failUnless(isinstance(parser, InstrumentedConfigObj))
368
self.assertEqual(parser._calls, [('__init__', config.config_filename(),
372
class TestBranchConfig(tests.TestCaseWithTransport):
374
def test_constructs(self):
375
branch = FakeBranch()
376
my_config = config.BranchConfig(branch)
377
self.assertRaises(TypeError, config.BranchConfig)
379
def test_get_location_config(self):
380
branch = FakeBranch()
381
my_config = config.BranchConfig(branch)
382
location_config = my_config._get_location_config()
383
self.assertEqual(branch.base, location_config.location)
384
self.failUnless(location_config is my_config._get_location_config())
386
def test_get_config(self):
387
"""The Branch.get_config method works properly"""
388
b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
389
my_config = b.get_config()
390
self.assertIs(my_config.get_user_option('wacky'), None)
391
my_config.set_user_option('wacky', 'unlikely')
392
self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
394
# Ensure we get the same thing if we start again
395
b2 = branch.Branch.open('.')
396
my_config2 = b2.get_config()
397
self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
399
def test_has_explicit_nickname(self):
400
b = self.make_branch('.')
401
self.assertFalse(b.get_config().has_explicit_nickname())
403
self.assertTrue(b.get_config().has_explicit_nickname())
405
def test_config_url(self):
406
"""The Branch.get_config will use section that uses a local url"""
407
branch = self.make_branch('branch')
408
self.assertEqual('branch', branch.nick)
410
locations = config.locations_config_filename()
411
config.ensure_config_dir_exists()
412
local_url = urlutils.local_path_to_url('branch')
413
open(locations, 'wb').write('[%s]\nnickname = foobar'
415
self.assertEqual('foobar', branch.nick)
417
def test_config_local_path(self):
418
"""The Branch.get_config will use a local system path"""
419
branch = self.make_branch('branch')
420
self.assertEqual('branch', branch.nick)
422
locations = config.locations_config_filename()
423
config.ensure_config_dir_exists()
424
open(locations, 'wb').write('[%s/branch]\nnickname = barry'
425
% (osutils.getcwd().encode('utf8'),))
426
self.assertEqual('barry', branch.nick)
428
def test_config_creates_local(self):
429
"""Creating a new entry in config uses a local path."""
430
branch = self.make_branch('branch', format='knit')
431
branch.set_push_location('http://foobar')
432
locations = config.locations_config_filename()
433
local_path = osutils.getcwd().encode('utf8')
434
# Surprisingly ConfigObj doesn't create a trailing newline
435
self.check_file_contents(locations,
436
'[%s/branch]\npush_location = http://foobar\npush_location:policy = norecurse' % (local_path,))
438
def test_autonick_urlencoded(self):
439
b = self.make_branch('!repo')
440
self.assertEqual('!repo', b.get_config().get_nickname())
442
def test_warn_if_masked(self):
443
_warning = trace.warning
446
warnings.append(args[0] % args[1:])
448
def set_option(store, warn_masked=True):
450
conf.set_user_option('example_option', repr(store), store=store,
451
warn_masked=warn_masked)
452
def assertWarning(warning):
454
self.assertEqual(0, len(warnings))
456
self.assertEqual(1, len(warnings))
457
self.assertEqual(warning, warnings[0])
458
trace.warning = warning
460
branch = self.make_branch('.')
461
conf = branch.get_config()
462
set_option(config.STORE_GLOBAL)
464
set_option(config.STORE_BRANCH)
466
set_option(config.STORE_GLOBAL)
467
assertWarning('Value "4" is masked by "3" from branch.conf')
468
set_option(config.STORE_GLOBAL, warn_masked=False)
470
set_option(config.STORE_LOCATION)
472
set_option(config.STORE_BRANCH)
473
assertWarning('Value "3" is masked by "0" from locations.conf')
474
set_option(config.STORE_BRANCH, warn_masked=False)
477
trace.warning = _warning
480
class TestGlobalConfigItems(tests.TestCase):
482
def test_user_id(self):
483
config_file = StringIO(sample_config_text.encode('utf-8'))
484
my_config = config.GlobalConfig()
485
my_config._parser = my_config._get_parser(file=config_file)
486
self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
487
my_config._get_user_id())
489
def test_absent_user_id(self):
490
config_file = StringIO("")
491
my_config = config.GlobalConfig()
492
my_config._parser = my_config._get_parser(file=config_file)
493
self.assertEqual(None, my_config._get_user_id())
495
def test_configured_editor(self):
496
config_file = StringIO(sample_config_text.encode('utf-8'))
497
my_config = config.GlobalConfig()
498
my_config._parser = my_config._get_parser(file=config_file)
499
self.assertEqual("vim", my_config.get_editor())
501
def test_signatures_always(self):
502
config_file = StringIO(sample_always_signatures)
503
my_config = config.GlobalConfig()
504
my_config._parser = my_config._get_parser(file=config_file)
505
self.assertEqual(config.CHECK_NEVER,
506
my_config.signature_checking())
507
self.assertEqual(config.SIGN_ALWAYS,
508
my_config.signing_policy())
509
self.assertEqual(True, my_config.signature_needed())
511
def test_signatures_if_possible(self):
512
config_file = StringIO(sample_maybe_signatures)
513
my_config = config.GlobalConfig()
514
my_config._parser = my_config._get_parser(file=config_file)
515
self.assertEqual(config.CHECK_NEVER,
516
my_config.signature_checking())
517
self.assertEqual(config.SIGN_WHEN_REQUIRED,
518
my_config.signing_policy())
519
self.assertEqual(False, my_config.signature_needed())
521
def test_signatures_ignore(self):
522
config_file = StringIO(sample_ignore_signatures)
523
my_config = config.GlobalConfig()
524
my_config._parser = my_config._get_parser(file=config_file)
525
self.assertEqual(config.CHECK_ALWAYS,
526
my_config.signature_checking())
527
self.assertEqual(config.SIGN_NEVER,
528
my_config.signing_policy())
529
self.assertEqual(False, my_config.signature_needed())
531
def _get_sample_config(self):
532
config_file = StringIO(sample_config_text.encode('utf-8'))
533
my_config = config.GlobalConfig()
534
my_config._parser = my_config._get_parser(file=config_file)
537
def test_gpg_signing_command(self):
538
my_config = self._get_sample_config()
539
self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
540
self.assertEqual(False, my_config.signature_needed())
542
def _get_empty_config(self):
543
config_file = StringIO("")
544
my_config = config.GlobalConfig()
545
my_config._parser = my_config._get_parser(file=config_file)
548
def test_gpg_signing_command_unset(self):
549
my_config = self._get_empty_config()
550
self.assertEqual("gpg", my_config.gpg_signing_command())
552
def test_get_user_option_default(self):
553
my_config = self._get_empty_config()
554
self.assertEqual(None, my_config.get_user_option('no_option'))
556
def test_get_user_option_global(self):
557
my_config = self._get_sample_config()
558
self.assertEqual("something",
559
my_config.get_user_option('user_global_option'))
561
def test_post_commit_default(self):
562
my_config = self._get_sample_config()
563
self.assertEqual(None, my_config.post_commit())
565
def test_configured_logformat(self):
566
my_config = self._get_sample_config()
567
self.assertEqual("short", my_config.log_format())
569
def test_get_alias(self):
570
my_config = self._get_sample_config()
571
self.assertEqual('help', my_config.get_alias('h'))
573
def test_get_no_alias(self):
574
my_config = self._get_sample_config()
575
self.assertEqual(None, my_config.get_alias('foo'))
577
def test_get_long_alias(self):
578
my_config = self._get_sample_config()
579
self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
582
class TestLocationConfig(tests.TestCaseInTempDir):
584
def test_constructs(self):
585
my_config = config.LocationConfig('http://example.com')
586
self.assertRaises(TypeError, config.LocationConfig)
588
def test_branch_calls_read_filenames(self):
589
# This is testing the correct file names are provided.
590
# TODO: consolidate with the test for GlobalConfigs filename checks.
592
# replace the class that is constructured, to check its parameters
593
oldparserclass = config.ConfigObj
594
config.ConfigObj = InstrumentedConfigObj
596
my_config = config.LocationConfig('http://www.example.com')
597
parser = my_config._get_parser()
599
config.ConfigObj = oldparserclass
600
self.failUnless(isinstance(parser, InstrumentedConfigObj))
601
self.assertEqual(parser._calls,
602
[('__init__', config.locations_config_filename(),
604
config.ensure_config_dir_exists()
605
#os.mkdir(config.config_dir())
606
f = file(config.branches_config_filename(), 'wb')
609
oldparserclass = config.ConfigObj
610
config.ConfigObj = InstrumentedConfigObj
612
my_config = config.LocationConfig('http://www.example.com')
613
parser = my_config._get_parser()
615
config.ConfigObj = oldparserclass
617
def test_get_global_config(self):
618
my_config = config.BranchConfig(FakeBranch('http://example.com'))
619
global_config = my_config._get_global_config()
620
self.failUnless(isinstance(global_config, config.GlobalConfig))
621
self.failUnless(global_config is my_config._get_global_config())
623
def test__get_matching_sections_no_match(self):
624
self.get_branch_config('/')
625
self.assertEqual([], self.my_location_config._get_matching_sections())
627
def test__get_matching_sections_exact(self):
628
self.get_branch_config('http://www.example.com')
629
self.assertEqual([('http://www.example.com', '')],
630
self.my_location_config._get_matching_sections())
632
def test__get_matching_sections_suffix_does_not(self):
633
self.get_branch_config('http://www.example.com-com')
634
self.assertEqual([], self.my_location_config._get_matching_sections())
636
def test__get_matching_sections_subdir_recursive(self):
637
self.get_branch_config('http://www.example.com/com')
638
self.assertEqual([('http://www.example.com', 'com')],
639
self.my_location_config._get_matching_sections())
641
def test__get_matching_sections_ignoreparent(self):
642
self.get_branch_config('http://www.example.com/ignoreparent')
643
self.assertEqual([('http://www.example.com/ignoreparent', '')],
644
self.my_location_config._get_matching_sections())
646
def test__get_matching_sections_ignoreparent_subdir(self):
647
self.get_branch_config(
648
'http://www.example.com/ignoreparent/childbranch')
649
self.assertEqual([('http://www.example.com/ignoreparent', 'childbranch')],
650
self.my_location_config._get_matching_sections())
652
def test__get_matching_sections_subdir_trailing_slash(self):
653
self.get_branch_config('/b')
654
self.assertEqual([('/b/', '')],
655
self.my_location_config._get_matching_sections())
657
def test__get_matching_sections_subdir_child(self):
658
self.get_branch_config('/a/foo')
659
self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
660
self.my_location_config._get_matching_sections())
662
def test__get_matching_sections_subdir_child_child(self):
663
self.get_branch_config('/a/foo/bar')
664
self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
665
self.my_location_config._get_matching_sections())
667
def test__get_matching_sections_trailing_slash_with_children(self):
668
self.get_branch_config('/a/')
669
self.assertEqual([('/a/', '')],
670
self.my_location_config._get_matching_sections())
672
def test__get_matching_sections_explicit_over_glob(self):
673
# XXX: 2006-09-08 jamesh
674
# This test only passes because ord('c') > ord('*'). If there
675
# was a config section for '/a/?', it would get precedence
677
self.get_branch_config('/a/c')
678
self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
679
self.my_location_config._get_matching_sections())
681
def test__get_option_policy_normal(self):
682
self.get_branch_config('http://www.example.com')
684
self.my_location_config._get_config_policy(
685
'http://www.example.com', 'normal_option'),
688
def test__get_option_policy_norecurse(self):
689
self.get_branch_config('http://www.example.com')
691
self.my_location_config._get_option_policy(
692
'http://www.example.com', 'norecurse_option'),
693
config.POLICY_NORECURSE)
694
# Test old recurse=False setting:
696
self.my_location_config._get_option_policy(
697
'http://www.example.com/norecurse', 'normal_option'),
698
config.POLICY_NORECURSE)
700
def test__get_option_policy_normal(self):
701
self.get_branch_config('http://www.example.com')
703
self.my_location_config._get_option_policy(
704
'http://www.example.com', 'appendpath_option'),
705
config.POLICY_APPENDPATH)
707
def test_location_without_username(self):
708
self.get_branch_config('http://www.example.com/ignoreparent')
709
self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
710
self.my_config.username())
712
def test_location_not_listed(self):
713
"""Test that the global username is used when no location matches"""
714
self.get_branch_config('/home/robertc/sources')
715
self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
716
self.my_config.username())
718
def test_overriding_location(self):
719
self.get_branch_config('http://www.example.com/foo')
720
self.assertEqual('Robert Collins <robertc@example.org>',
721
self.my_config.username())
723
def test_signatures_not_set(self):
724
self.get_branch_config('http://www.example.com',
725
global_config=sample_ignore_signatures)
726
self.assertEqual(config.CHECK_ALWAYS,
727
self.my_config.signature_checking())
728
self.assertEqual(config.SIGN_NEVER,
729
self.my_config.signing_policy())
731
def test_signatures_never(self):
732
self.get_branch_config('/a/c')
733
self.assertEqual(config.CHECK_NEVER,
734
self.my_config.signature_checking())
736
def test_signatures_when_available(self):
737
self.get_branch_config('/a/', global_config=sample_ignore_signatures)
738
self.assertEqual(config.CHECK_IF_POSSIBLE,
739
self.my_config.signature_checking())
741
def test_signatures_always(self):
742
self.get_branch_config('/b')
743
self.assertEqual(config.CHECK_ALWAYS,
744
self.my_config.signature_checking())
746
def test_gpg_signing_command(self):
747
self.get_branch_config('/b')
748
self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
750
def test_gpg_signing_command_missing(self):
751
self.get_branch_config('/a')
752
self.assertEqual("false", self.my_config.gpg_signing_command())
754
def test_get_user_option_global(self):
755
self.get_branch_config('/a')
756
self.assertEqual('something',
757
self.my_config.get_user_option('user_global_option'))
759
def test_get_user_option_local(self):
760
self.get_branch_config('/a')
761
self.assertEqual('local',
762
self.my_config.get_user_option('user_local_option'))
764
def test_get_user_option_appendpath(self):
765
# returned as is for the base path:
766
self.get_branch_config('http://www.example.com')
767
self.assertEqual('append',
768
self.my_config.get_user_option('appendpath_option'))
769
# Extra path components get appended:
770
self.get_branch_config('http://www.example.com/a/b/c')
771
self.assertEqual('append/a/b/c',
772
self.my_config.get_user_option('appendpath_option'))
773
# Overriden for http://www.example.com/dir, where it is a
775
self.get_branch_config('http://www.example.com/dir/a/b/c')
776
self.assertEqual('normal',
777
self.my_config.get_user_option('appendpath_option'))
779
def test_get_user_option_norecurse(self):
780
self.get_branch_config('http://www.example.com')
781
self.assertEqual('norecurse',
782
self.my_config.get_user_option('norecurse_option'))
783
self.get_branch_config('http://www.example.com/dir')
784
self.assertEqual(None,
785
self.my_config.get_user_option('norecurse_option'))
786
# http://www.example.com/norecurse is a recurse=False section
787
# that redefines normal_option. Subdirectories do not pick up
789
self.get_branch_config('http://www.example.com/norecurse')
790
self.assertEqual('norecurse',
791
self.my_config.get_user_option('normal_option'))
792
self.get_branch_config('http://www.example.com/norecurse/subdir')
793
self.assertEqual('normal',
794
self.my_config.get_user_option('normal_option'))
796
def test_set_user_option_norecurse(self):
797
self.get_branch_config('http://www.example.com')
798
self.my_config.set_user_option('foo', 'bar',
799
store=config.STORE_LOCATION_NORECURSE)
801
self.my_location_config._get_option_policy(
802
'http://www.example.com', 'foo'),
803
config.POLICY_NORECURSE)
805
def test_set_user_option_appendpath(self):
806
self.get_branch_config('http://www.example.com')
807
self.my_config.set_user_option('foo', 'bar',
808
store=config.STORE_LOCATION_APPENDPATH)
810
self.my_location_config._get_option_policy(
811
'http://www.example.com', 'foo'),
812
config.POLICY_APPENDPATH)
814
def test_set_user_option_change_policy(self):
815
self.get_branch_config('http://www.example.com')
816
self.my_config.set_user_option('norecurse_option', 'normal',
817
store=config.STORE_LOCATION)
819
self.my_location_config._get_option_policy(
820
'http://www.example.com', 'norecurse_option'),
823
def test_set_user_option_recurse_false_section(self):
824
# The following section has recurse=False set. The test is to
825
# make sure that a normal option can be added to the section,
826
# converting recurse=False to the norecurse policy.
827
self.get_branch_config('http://www.example.com/norecurse')
828
self.callDeprecated(['The recurse option is deprecated as of 0.14. '
829
'The section "http://www.example.com/norecurse" '
830
'has been converted to use policies.'],
831
self.my_config.set_user_option,
832
'foo', 'bar', store=config.STORE_LOCATION)
834
self.my_location_config._get_option_policy(
835
'http://www.example.com/norecurse', 'foo'),
837
# The previously existing option is still norecurse:
839
self.my_location_config._get_option_policy(
840
'http://www.example.com/norecurse', 'normal_option'),
841
config.POLICY_NORECURSE)
843
def test_post_commit_default(self):
844
self.get_branch_config('/a/c')
845
self.assertEqual('bzrlib.tests.test_config.post_commit',
846
self.my_config.post_commit())
848
def get_branch_config(self, location, global_config=None):
849
if global_config is None:
850
global_file = StringIO(sample_config_text.encode('utf-8'))
852
global_file = StringIO(global_config.encode('utf-8'))
853
branches_file = StringIO(sample_branches_text.encode('utf-8'))
854
self.my_config = config.BranchConfig(FakeBranch(location))
855
# Force location config to use specified file
856
self.my_location_config = self.my_config._get_location_config()
857
self.my_location_config._get_parser(branches_file)
858
# Force global config to use specified file
859
self.my_config._get_global_config()._get_parser(global_file)
861
def test_set_user_setting_sets_and_saves(self):
862
self.get_branch_config('/a/c')
863
record = InstrumentedConfigObj("foo")
864
self.my_location_config._parser = record
866
real_mkdir = os.mkdir
868
def checked_mkdir(path, mode=0777):
869
self.log('making directory: %s', path)
870
real_mkdir(path, mode)
873
os.mkdir = checked_mkdir
875
self.callDeprecated(['The recurse option is deprecated as of '
876
'0.14. The section "/a/c" has been '
877
'converted to use policies.'],
878
self.my_config.set_user_option,
879
'foo', 'bar', store=config.STORE_LOCATION)
881
os.mkdir = real_mkdir
883
self.failUnless(self.created, 'Failed to create ~/.bazaar')
884
self.assertEqual([('__contains__', '/a/c'),
885
('__contains__', '/a/c/'),
886
('__setitem__', '/a/c', {}),
887
('__getitem__', '/a/c'),
888
('__setitem__', 'foo', 'bar'),
889
('__getitem__', '/a/c'),
890
('as_bool', 'recurse'),
891
('__getitem__', '/a/c'),
892
('__delitem__', 'recurse'),
893
('__getitem__', '/a/c'),
895
('__getitem__', '/a/c'),
896
('__contains__', 'foo:policy'),
900
def test_set_user_setting_sets_and_saves2(self):
901
self.get_branch_config('/a/c')
902
self.assertIs(self.my_config.get_user_option('foo'), None)
903
self.my_config.set_user_option('foo', 'bar')
905
self.my_config.branch.control_files.files['branch.conf'],
907
self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
908
self.my_config.set_user_option('foo', 'baz',
909
store=config.STORE_LOCATION)
910
self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
911
self.my_config.set_user_option('foo', 'qux')
912
self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
914
def test_get_bzr_remote_path(self):
915
my_config = config.LocationConfig('/a/c')
916
self.assertEqual('bzr', my_config.get_bzr_remote_path())
917
my_config.set_user_option('bzr_remote_path', '/path-bzr')
918
self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
919
os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
920
self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
923
precedence_global = 'option = global'
924
precedence_branch = 'option = branch'
925
precedence_location = """
929
[http://example.com/specific]
934
class TestBranchConfigItems(tests.TestCaseInTempDir):
936
def get_branch_config(self, global_config=None, location=None,
937
location_config=None, branch_data_config=None):
938
my_config = config.BranchConfig(FakeBranch(location))
939
if global_config is not None:
940
global_file = StringIO(global_config.encode('utf-8'))
941
my_config._get_global_config()._get_parser(global_file)
942
self.my_location_config = my_config._get_location_config()
943
if location_config is not None:
944
location_file = StringIO(location_config.encode('utf-8'))
945
self.my_location_config._get_parser(location_file)
946
if branch_data_config is not None:
947
my_config.branch.control_files.files['branch.conf'] = \
951
def test_user_id(self):
952
branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
953
my_config = config.BranchConfig(branch)
954
self.assertEqual("Robert Collins <robertc@example.net>",
955
my_config.username())
956
branch.control_files.email = "John"
957
my_config.set_user_option('email',
958
"Robert Collins <robertc@example.org>")
959
self.assertEqual("John", my_config.username())
960
branch.control_files.email = None
961
self.assertEqual("Robert Collins <robertc@example.org>",
962
my_config.username())
964
def test_not_set_in_branch(self):
965
my_config = self.get_branch_config(sample_config_text)
966
my_config.branch.control_files.email = None
967
self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
968
my_config._get_user_id())
969
my_config.branch.control_files.email = "John"
970
self.assertEqual("John", my_config._get_user_id())
972
def test_BZR_EMAIL_OVERRIDES(self):
973
os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
974
branch = FakeBranch()
975
my_config = config.BranchConfig(branch)
976
self.assertEqual("Robert Collins <robertc@example.org>",
977
my_config.username())
979
def test_signatures_forced(self):
980
my_config = self.get_branch_config(
981
global_config=sample_always_signatures)
982
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
983
self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
984
self.assertTrue(my_config.signature_needed())
986
def test_signatures_forced_branch(self):
987
my_config = self.get_branch_config(
988
global_config=sample_ignore_signatures,
989
branch_data_config=sample_always_signatures)
990
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
991
self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
992
self.assertTrue(my_config.signature_needed())
994
def test_gpg_signing_command(self):
995
my_config = self.get_branch_config(
996
# branch data cannot set gpg_signing_command
997
branch_data_config="gpg_signing_command=pgp")
998
config_file = StringIO(sample_config_text.encode('utf-8'))
999
my_config._get_global_config()._get_parser(config_file)
1000
self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1002
def test_get_user_option_global(self):
1003
branch = FakeBranch()
1004
my_config = config.BranchConfig(branch)
1005
config_file = StringIO(sample_config_text.encode('utf-8'))
1006
(my_config._get_global_config()._get_parser(config_file))
1007
self.assertEqual('something',
1008
my_config.get_user_option('user_global_option'))
1010
def test_post_commit_default(self):
1011
branch = FakeBranch()
1012
my_config = self.get_branch_config(sample_config_text, '/a/c',
1013
sample_branches_text)
1014
self.assertEqual(my_config.branch.base, '/a/c')
1015
self.assertEqual('bzrlib.tests.test_config.post_commit',
1016
my_config.post_commit())
1017
my_config.set_user_option('post_commit', 'rmtree_root')
1018
# post-commit is ignored when bresent in branch data
1019
self.assertEqual('bzrlib.tests.test_config.post_commit',
1020
my_config.post_commit())
1021
my_config.set_user_option('post_commit', 'rmtree_root',
1022
store=config.STORE_LOCATION)
1023
self.assertEqual('rmtree_root', my_config.post_commit())
1025
def test_config_precedence(self):
1026
my_config = self.get_branch_config(global_config=precedence_global)
1027
self.assertEqual(my_config.get_user_option('option'), 'global')
1028
my_config = self.get_branch_config(global_config=precedence_global,
1029
branch_data_config=precedence_branch)
1030
self.assertEqual(my_config.get_user_option('option'), 'branch')
1031
my_config = self.get_branch_config(global_config=precedence_global,
1032
branch_data_config=precedence_branch,
1033
location_config=precedence_location)
1034
self.assertEqual(my_config.get_user_option('option'), 'recurse')
1035
my_config = self.get_branch_config(global_config=precedence_global,
1036
branch_data_config=precedence_branch,
1037
location_config=precedence_location,
1038
location='http://example.com/specific')
1039
self.assertEqual(my_config.get_user_option('option'), 'exact')
1041
def test_get_mail_client(self):
1042
config = self.get_branch_config()
1043
client = config.get_mail_client()
1044
self.assertIsInstance(client, mail_client.DefaultMail)
1047
config.set_user_option('mail_client', 'evolution')
1048
client = config.get_mail_client()
1049
self.assertIsInstance(client, mail_client.Evolution)
1051
config.set_user_option('mail_client', 'kmail')
1052
client = config.get_mail_client()
1053
self.assertIsInstance(client, mail_client.KMail)
1055
config.set_user_option('mail_client', 'mutt')
1056
client = config.get_mail_client()
1057
self.assertIsInstance(client, mail_client.Mutt)
1059
config.set_user_option('mail_client', 'thunderbird')
1060
client = config.get_mail_client()
1061
self.assertIsInstance(client, mail_client.Thunderbird)
1064
config.set_user_option('mail_client', 'default')
1065
client = config.get_mail_client()
1066
self.assertIsInstance(client, mail_client.DefaultMail)
1068
config.set_user_option('mail_client', 'editor')
1069
client = config.get_mail_client()
1070
self.assertIsInstance(client, mail_client.Editor)
1072
config.set_user_option('mail_client', 'mapi')
1073
client = config.get_mail_client()
1074
self.assertIsInstance(client, mail_client.MAPIClient)
1076
config.set_user_option('mail_client', 'xdg-email')
1077
client = config.get_mail_client()
1078
self.assertIsInstance(client, mail_client.XDGEmail)
1080
config.set_user_option('mail_client', 'firebird')
1081
self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1084
class TestMailAddressExtraction(tests.TestCase):
1086
def test_extract_email_address(self):
1087
self.assertEqual('jane@test.com',
1088
config.extract_email_address('Jane <jane@test.com>'))
1089
self.assertRaises(errors.NoEmailInUsername,
1090
config.extract_email_address, 'Jane Tester')
1093
class TestTreeConfig(tests.TestCaseWithTransport):
1095
def test_get_value(self):
1096
"""Test that retreiving a value from a section is possible"""
1097
branch = self.make_branch('.')
1098
tree_config = config.TreeConfig(branch)
1099
tree_config.set_option('value', 'key', 'SECTION')
1100
tree_config.set_option('value2', 'key2')
1101
tree_config.set_option('value3-top', 'key3')
1102
tree_config.set_option('value3-section', 'key3', 'SECTION')
1103
value = tree_config.get_option('key', 'SECTION')
1104
self.assertEqual(value, 'value')
1105
value = tree_config.get_option('key2')
1106
self.assertEqual(value, 'value2')
1107
self.assertEqual(tree_config.get_option('non-existant'), None)
1108
value = tree_config.get_option('non-existant', 'SECTION')
1109
self.assertEqual(value, None)
1110
value = tree_config.get_option('non-existant', default='default')
1111
self.assertEqual(value, 'default')
1112
self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1113
value = tree_config.get_option('key2', 'NOSECTION', default='default')
1114
self.assertEqual(value, 'default')
1115
value = tree_config.get_option('key3')
1116
self.assertEqual(value, 'value3-top')
1117
value = tree_config.get_option('key3', 'SECTION')
1118
self.assertEqual(value, 'value3-section')
1121
class TestAuthenticationConfigFile(tests.TestCase):
1122
"""Test the authentication.conf file matching"""
1124
def _got_user_passwd(self, expected_user, expected_password,
1125
config, *args, **kwargs):
1126
credentials = config.get_credentials(*args, **kwargs)
1127
if credentials is None:
1131
user = credentials['user']
1132
password = credentials['password']
1133
self.assertEquals(expected_user, user)
1134
self.assertEquals(expected_password, password)
1136
def test_empty_config(self):
1137
conf = config.AuthenticationConfig(_file=StringIO())
1138
self.assertEquals({}, conf._get_config())
1139
self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1141
def test_broken_config(self):
1142
conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1143
self.assertRaises(errors.ParseConfigError, conf._get_config)
1145
conf = config.AuthenticationConfig(_file=StringIO(
1149
verify_certificates=askme # Error: Not a boolean
1151
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1152
conf = config.AuthenticationConfig(_file=StringIO(
1156
port=port # Error: Not an int
1158
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1160
def test_credentials_for_scheme_host(self):
1161
conf = config.AuthenticationConfig(_file=StringIO(
1162
"""# Identity on foo.net
1167
password=secret-pass
1170
self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1172
self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1174
self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1176
def test_credentials_for_host_port(self):
1177
conf = config.AuthenticationConfig(_file=StringIO(
1178
"""# Identity on foo.net
1184
password=secret-pass
1187
self._got_user_passwd('joe', 'secret-pass',
1188
conf, 'ftp', 'foo.net', port=10021)
1190
self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1192
def test_for_matching_host(self):
1193
conf = config.AuthenticationConfig(_file=StringIO(
1194
"""# Identity on foo.net
1200
[sourceforge domain]
1207
self._got_user_passwd('georges', 'bendover',
1208
conf, 'bzr', 'foo.bzr.sf.net')
1210
self._got_user_passwd(None, None,
1211
conf, 'bzr', 'bbzr.sf.net')
1213
def test_for_matching_host_None(self):
1214
conf = config.AuthenticationConfig(_file=StringIO(
1215
"""# Identity on foo.net
1225
self._got_user_passwd('joe', 'joepass',
1226
conf, 'bzr', 'quux.net')
1227
# no host but different scheme
1228
self._got_user_passwd('georges', 'bendover',
1229
conf, 'ftp', 'quux.net')
1231
def test_credentials_for_path(self):
1232
conf = config.AuthenticationConfig(_file=StringIO(
1248
self._got_user_passwd(None, None,
1249
conf, 'http', host='bar.org', path='/dir3')
1251
self._got_user_passwd('georges', 'bendover',
1252
conf, 'http', host='bar.org', path='/dir2')
1254
self._got_user_passwd('jim', 'jimpass',
1255
conf, 'http', host='bar.org',path='/dir1/subdir')
1257
def test_credentials_for_user(self):
1258
conf = config.AuthenticationConfig(_file=StringIO(
1267
self._got_user_passwd('jim', 'jimpass',
1268
conf, 'http', 'bar.org')
1270
self._got_user_passwd('jim', 'jimpass',
1271
conf, 'http', 'bar.org', user='jim')
1272
# Don't get a different user if one is specified
1273
self._got_user_passwd(None, None,
1274
conf, 'http', 'bar.org', user='georges')
1276
def test_verify_certificates(self):
1277
conf = config.AuthenticationConfig(_file=StringIO(
1284
verify_certificates=False
1291
credentials = conf.get_credentials('https', 'bar.org')
1292
self.assertEquals(False, credentials.get('verify_certificates'))
1293
credentials = conf.get_credentials('https', 'foo.net')
1294
self.assertEquals(True, credentials.get('verify_certificates'))
1297
class TestAuthenticationConfig(tests.TestCase):
1298
"""Test AuthenticationConfig behaviour"""
1300
def _check_default_prompt(self, expected_prompt_format, scheme,
1301
host=None, port=None, realm=None, path=None):
1304
user, password = 'jim', 'precious'
1305
expected_prompt = expected_prompt_format % {
1306
'scheme': scheme, 'host': host, 'port': port,
1307
'user': user, 'realm': realm}
1309
stdout = tests.StringIOWrapper()
1310
ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
1312
# We use an empty conf so that the user is always prompted
1313
conf = config.AuthenticationConfig()
1314
self.assertEquals(password,
1315
conf.get_password(scheme, host, user, port=port,
1316
realm=realm, path=path))
1317
self.assertEquals(stdout.getvalue(), expected_prompt)
1319
def test_default_prompts(self):
1320
# HTTP prompts can't be tested here, see test_http.py
1321
self._check_default_prompt('FTP %(user)s@%(host)s password: ', 'ftp')
1322
self._check_default_prompt('FTP %(user)s@%(host)s:%(port)d password: ',
1325
self._check_default_prompt('SSH %(user)s@%(host)s:%(port)d password: ',
1327
# SMTP port handling is a bit special (it's handled if embedded in the
1329
# FIXME: should we: forbid that, extend it to other schemes, leave
1330
# things as they are that's fine thank you ?
1331
self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
1333
self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
1334
'smtp', host='bar.org:10025')
1335
self._check_default_prompt(
1336
'SMTP %(user)s@%(host)s:%(port)d password: ',
1340
# FIXME: Once we have a way to declare authentication to all test servers, we
1341
# can implement generic tests.
1342
# test_user_password_in_url
1343
# test_user_in_url_password_from_config
1344
# test_user_in_url_password_prompted
1345
# test_user_in_config
1346
# test_user_getpass.getuser
1347
# test_user_prompted ?
1348
class TestAuthenticationRing(tests.TestCaseWithTransport):