230
349
my_config = config.Config()
231
350
self.assertEqual('long', my_config.log_format())
234
class TestConfigPath(TestCase):
352
def test_get_change_editor(self):
353
my_config = InstrumentedConfig()
354
change_editor = my_config.get_change_editor('old_tree', 'new_tree')
355
self.assertEqual(['_get_change_editor'], my_config._calls)
356
self.assertIs(diff.DiffFromTool, change_editor.__class__)
357
self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
358
change_editor.command_template)
361
class TestConfigPath(tests.TestCase):
237
364
super(TestConfigPath, self).setUp()
238
self.old_home = os.environ.get('HOME', None)
239
self.old_appdata = os.environ.get('APPDATA', None)
240
365
os.environ['HOME'] = '/home/bogus'
241
os.environ['APPDATA'] = \
242
r'C:\Documents and Settings\bogus\Application Data'
366
os.environ['XDG_CACHE_DIR'] = ''
367
if sys.platform == 'win32':
368
os.environ['BZR_HOME'] = \
369
r'C:\Documents and Settings\bogus\Application Data'
371
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
373
self.bzr_home = '/home/bogus/.bazaar'
245
if self.old_home is None:
246
del os.environ['HOME']
248
os.environ['HOME'] = self.old_home
249
if self.old_appdata is None:
250
del os.environ['APPDATA']
252
os.environ['APPDATA'] = self.old_appdata
253
super(TestConfigPath, self).tearDown()
255
375
def test_config_dir(self):
256
if sys.platform == 'win32':
257
self.assertEqual(config.config_dir(),
258
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0')
260
self.assertEqual(config.config_dir(), '/home/bogus/.bazaar')
376
self.assertEqual(config.config_dir(), self.bzr_home)
262
378
def test_config_filename(self):
263
if sys.platform == 'win32':
264
self.assertEqual(config.config_filename(),
265
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/bazaar.conf')
267
self.assertEqual(config.config_filename(),
268
'/home/bogus/.bazaar/bazaar.conf')
270
def test_branches_config_filename(self):
271
if sys.platform == 'win32':
272
self.assertEqual(config.branches_config_filename(),
273
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/branches.conf')
275
self.assertEqual(config.branches_config_filename(),
276
'/home/bogus/.bazaar/branches.conf')
379
self.assertEqual(config.config_filename(),
380
self.bzr_home + '/bazaar.conf')
278
382
def test_locations_config_filename(self):
279
if sys.platform == 'win32':
280
self.assertEqual(config.locations_config_filename(),
281
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/locations.conf')
283
self.assertEqual(config.locations_config_filename(),
284
'/home/bogus/.bazaar/locations.conf')
286
class TestIniConfig(TestCase):
383
self.assertEqual(config.locations_config_filename(),
384
self.bzr_home + '/locations.conf')
386
def test_authentication_config_filename(self):
387
self.assertEqual(config.authentication_config_filename(),
388
self.bzr_home + '/authentication.conf')
390
def test_xdg_cache_dir(self):
391
self.assertEqual(config.xdg_cache_dir(),
392
'/home/bogus/.cache')
395
class TestIniConfig(tests.TestCaseInTempDir):
397
def make_config_parser(self, s):
398
conf = config.IniBasedConfig.from_string(s)
399
return conf, conf._get_parser()
402
class TestIniConfigBuilding(TestIniConfig):
288
404
def test_contructs(self):
289
my_config = config.IniBasedConfig("nothing")
405
my_config = config.IniBasedConfig()
291
407
def test_from_fp(self):
292
config_file = StringIO(sample_config_text.encode('utf-8'))
293
my_config = config.IniBasedConfig(None)
295
isinstance(my_config._get_parser(file=config_file),
408
my_config = config.IniBasedConfig.from_string(sample_config_text)
409
self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
298
411
def test_cached(self):
299
config_file = StringIO(sample_config_text.encode('utf-8'))
300
my_config = config.IniBasedConfig(None)
301
parser = my_config._get_parser(file=config_file)
412
my_config = config.IniBasedConfig.from_string(sample_config_text)
413
parser = my_config._get_parser()
302
414
self.failUnless(my_config._get_parser() is parser)
305
class TestGetConfig(TestCase):
416
def _dummy_chown(self, path, uid, gid):
417
self.path, self.uid, self.gid = path, uid, gid
419
def test_ini_config_ownership(self):
420
"""Ensure that chown is happening during _write_config_file"""
421
self.requireFeature(features.chown_feature)
422
self.overrideAttr(os, 'chown', self._dummy_chown)
423
self.path = self.uid = self.gid = None
424
conf = config.IniBasedConfig(file_name='./foo.conf')
425
conf._write_config_file()
426
self.assertEquals(self.path, './foo.conf')
427
self.assertTrue(isinstance(self.uid, int))
428
self.assertTrue(isinstance(self.gid, int))
430
def test_get_filename_parameter_is_deprecated_(self):
431
conf = self.callDeprecated([
432
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
433
' Use file_name instead.'],
434
config.IniBasedConfig, lambda: 'ini.conf')
435
self.assertEqual('ini.conf', conf.file_name)
437
def test_get_parser_file_parameter_is_deprecated_(self):
438
config_file = StringIO(sample_config_text.encode('utf-8'))
439
conf = config.IniBasedConfig.from_string(sample_config_text)
440
conf = self.callDeprecated([
441
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
442
' Use IniBasedConfig(_content=xxx) instead.'],
443
conf._get_parser, file=config_file)
445
class TestIniConfigSaving(tests.TestCaseInTempDir):
447
def test_cant_save_without_a_file_name(self):
448
conf = config.IniBasedConfig()
449
self.assertRaises(AssertionError, conf._write_config_file)
451
def test_saved_with_content(self):
452
content = 'foo = bar\n'
453
conf = config.IniBasedConfig.from_string(
454
content, file_name='./test.conf', save=True)
455
self.assertFileEqual(content, 'test.conf')
458
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
460
def test_cannot_reload_without_name(self):
461
conf = config.IniBasedConfig.from_string(sample_config_text)
462
self.assertRaises(AssertionError, conf.reload)
464
def test_reload_see_new_value(self):
465
c1 = config.IniBasedConfig.from_string('editor=vim\n',
466
file_name='./test/conf')
467
c1._write_config_file()
468
c2 = config.IniBasedConfig.from_string('editor=emacs\n',
469
file_name='./test/conf')
470
c2._write_config_file()
471
self.assertEqual('vim', c1.get_user_option('editor'))
472
self.assertEqual('emacs', c2.get_user_option('editor'))
473
# Make sure we get the Right value
475
self.assertEqual('emacs', c1.get_user_option('editor'))
478
class TestLockableConfig(tests.TestCaseInTempDir):
483
config_section = None
486
super(TestLockableConfig, self).setUp()
487
self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
488
self.config = self.create_config(self._content)
490
def get_existing_config(self):
491
return self.config_class(*self.config_args)
493
def create_config(self, content):
494
kwargs = dict(save=True)
495
c = self.config_class.from_string(content, *self.config_args, **kwargs)
498
def test_simple_read_access(self):
499
self.assertEquals('1', self.config.get_user_option('one'))
501
def test_simple_write_access(self):
502
self.config.set_user_option('one', 'one')
503
self.assertEquals('one', self.config.get_user_option('one'))
505
def test_listen_to_the_last_speaker(self):
507
c2 = self.get_existing_config()
508
c1.set_user_option('one', 'ONE')
509
c2.set_user_option('two', 'TWO')
510
self.assertEquals('ONE', c1.get_user_option('one'))
511
self.assertEquals('TWO', c2.get_user_option('two'))
512
# The second update respect the first one
513
self.assertEquals('ONE', c2.get_user_option('one'))
515
def test_last_speaker_wins(self):
516
# If the same config is not shared, the same variable modified twice
517
# can only see a single result.
519
c2 = self.get_existing_config()
520
c1.set_user_option('one', 'c1')
521
c2.set_user_option('one', 'c2')
522
self.assertEquals('c2', c2._get_user_option('one'))
523
# The first modification is still available until another refresh
525
self.assertEquals('c1', c1._get_user_option('one'))
526
c1.set_user_option('two', 'done')
527
self.assertEquals('c2', c1._get_user_option('one'))
529
def test_writes_are_serialized(self):
531
c2 = self.get_existing_config()
533
# We spawn a thread that will pause *during* the write
534
before_writing = threading.Event()
535
after_writing = threading.Event()
536
writing_done = threading.Event()
537
c1_orig = c1._write_config_file
538
def c1_write_config_file():
541
# The lock is held we wait for the main thread to decide when to
544
c1._write_config_file = c1_write_config_file
546
c1.set_user_option('one', 'c1')
548
t1 = threading.Thread(target=c1_set_option)
549
# Collect the thread after the test
550
self.addCleanup(t1.join)
551
# Be ready to unblock the thread if the test goes wrong
552
self.addCleanup(after_writing.set)
554
before_writing.wait()
555
self.assertTrue(c1._lock.is_held)
556
self.assertRaises(errors.LockContention,
557
c2.set_user_option, 'one', 'c2')
558
self.assertEquals('c1', c1.get_user_option('one'))
559
# Let the lock be released
562
c2.set_user_option('one', 'c2')
563
self.assertEquals('c2', c2.get_user_option('one'))
565
def test_read_while_writing(self):
567
# We spawn a thread that will pause *during* the write
568
ready_to_write = threading.Event()
569
do_writing = threading.Event()
570
writing_done = threading.Event()
571
c1_orig = c1._write_config_file
572
def c1_write_config_file():
574
# The lock is held we wait for the main thread to decide when to
579
c1._write_config_file = c1_write_config_file
581
c1.set_user_option('one', 'c1')
582
t1 = threading.Thread(target=c1_set_option)
583
# Collect the thread after the test
584
self.addCleanup(t1.join)
585
# Be ready to unblock the thread if the test goes wrong
586
self.addCleanup(do_writing.set)
588
# Ensure the thread is ready to write
589
ready_to_write.wait()
590
self.assertTrue(c1._lock.is_held)
591
self.assertEquals('c1', c1.get_user_option('one'))
592
# If we read during the write, we get the old value
593
c2 = self.get_existing_config()
594
self.assertEquals('1', c2.get_user_option('one'))
595
# Let the writing occur and ensure it occurred
598
# Now we get the updated value
599
c3 = self.get_existing_config()
600
self.assertEquals('c1', c3.get_user_option('one'))
603
class TestGetUserOptionAs(TestIniConfig):
605
def test_get_user_option_as_bool(self):
606
conf, parser = self.make_config_parser("""
609
an_invalid_bool = maybe
610
a_list = hmm, who knows ? # This is interpreted as a list !
612
get_bool = conf.get_user_option_as_bool
613
self.assertEqual(True, get_bool('a_true_bool'))
614
self.assertEqual(False, get_bool('a_false_bool'))
617
warnings.append(args[0] % args[1:])
618
self.overrideAttr(trace, 'warning', warning)
619
msg = 'Value "%s" is not a boolean for "%s"'
620
self.assertIs(None, get_bool('an_invalid_bool'))
621
self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
623
self.assertIs(None, get_bool('not_defined_in_this_config'))
624
self.assertEquals([], warnings)
626
def test_get_user_option_as_list(self):
627
conf, parser = self.make_config_parser("""
632
get_list = conf.get_user_option_as_list
633
self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
634
self.assertEqual(['1'], get_list('length_1'))
635
self.assertEqual('x', conf.get_user_option('one_item'))
636
# automatically cast to list
637
self.assertEqual(['x'], get_list('one_item'))
640
class TestSupressWarning(TestIniConfig):
642
def make_warnings_config(self, s):
643
conf, parser = self.make_config_parser(s)
644
return conf.suppress_warning
646
def test_suppress_warning_unknown(self):
647
suppress_warning = self.make_warnings_config('')
648
self.assertEqual(False, suppress_warning('unknown_warning'))
650
def test_suppress_warning_known(self):
651
suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
652
self.assertEqual(False, suppress_warning('c'))
653
self.assertEqual(True, suppress_warning('a'))
654
self.assertEqual(True, suppress_warning('b'))
657
class TestGetConfig(tests.TestCase):
307
659
def test_constructs(self):
308
660
my_config = config.GlobalConfig()
310
662
def test_calls_read_filenames(self):
311
# replace the class that is constructured, to check its parameters
663
# replace the class that is constructed, to check its parameters
312
664
oldparserclass = config.ConfigObj
313
665
config.ConfigObj = InstrumentedConfigObj
314
666
my_config = config.GlobalConfig()
738
1296
def test_gpg_signing_command(self):
739
1297
my_config = self.get_branch_config(
1298
global_config=sample_config_text,
740
1299
# branch data cannot set gpg_signing_command
741
1300
branch_data_config="gpg_signing_command=pgp")
742
config_file = StringIO(sample_config_text.encode('utf-8'))
743
my_config._get_global_config()._get_parser(config_file)
744
1301
self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
746
1303
def test_get_user_option_global(self):
747
branch = FakeBranch()
748
my_config = config.BranchConfig(branch)
749
config_file = StringIO(sample_config_text.encode('utf-8'))
750
(my_config._get_global_config()._get_parser(config_file))
1304
my_config = self.get_branch_config(global_config=sample_config_text)
751
1305
self.assertEqual('something',
752
1306
my_config.get_user_option('user_global_option'))
754
1308
def test_post_commit_default(self):
755
branch = FakeBranch()
756
my_config = self.get_branch_config(sample_config_text, '/a/c',
757
sample_branches_text)
1309
my_config = self.get_branch_config(global_config=sample_config_text,
1311
location_config=sample_branches_text)
758
1312
self.assertEqual(my_config.branch.base, '/a/c')
759
1313
self.assertEqual('bzrlib.tests.test_config.post_commit',
760
1314
my_config.post_commit())
761
1315
my_config.set_user_option('post_commit', 'rmtree_root')
762
# post-commit is ignored when bresent in branch data
1316
# post-commit is ignored when present in branch data
763
1317
self.assertEqual('bzrlib.tests.test_config.post_commit',
764
1318
my_config.post_commit())
765
my_config.set_user_option('post_commit', 'rmtree_root', local=True)
1319
my_config.set_user_option('post_commit', 'rmtree_root',
1320
store=config.STORE_LOCATION)
766
1321
self.assertEqual('rmtree_root', my_config.post_commit())
768
1323
def test_config_precedence(self):
1324
# FIXME: eager test, luckily no persitent config file makes it fail
769
1326
my_config = self.get_branch_config(global_config=precedence_global)
770
1327
self.assertEqual(my_config.get_user_option('option'), 'global')
771
my_config = self.get_branch_config(global_config=precedence_global,
772
branch_data_config=precedence_branch)
1328
my_config = self.get_branch_config(global_config=precedence_global,
1329
branch_data_config=precedence_branch)
773
1330
self.assertEqual(my_config.get_user_option('option'), 'branch')
774
my_config = self.get_branch_config(global_config=precedence_global,
775
branch_data_config=precedence_branch,
776
location_config=precedence_location)
1331
my_config = self.get_branch_config(
1332
global_config=precedence_global,
1333
branch_data_config=precedence_branch,
1334
location_config=precedence_location)
777
1335
self.assertEqual(my_config.get_user_option('option'), 'recurse')
778
my_config = self.get_branch_config(global_config=precedence_global,
779
branch_data_config=precedence_branch,
780
location_config=precedence_location,
781
location='http://example.com/specific')
1336
my_config = self.get_branch_config(
1337
global_config=precedence_global,
1338
branch_data_config=precedence_branch,
1339
location_config=precedence_location,
1340
location='http://example.com/specific')
782
1341
self.assertEqual(my_config.get_user_option('option'), 'exact')
785
class TestMailAddressExtraction(TestCase):
1343
def test_get_mail_client(self):
1344
config = self.get_branch_config()
1345
client = config.get_mail_client()
1346
self.assertIsInstance(client, mail_client.DefaultMail)
1349
config.set_user_option('mail_client', 'evolution')
1350
client = config.get_mail_client()
1351
self.assertIsInstance(client, mail_client.Evolution)
1353
config.set_user_option('mail_client', 'kmail')
1354
client = config.get_mail_client()
1355
self.assertIsInstance(client, mail_client.KMail)
1357
config.set_user_option('mail_client', 'mutt')
1358
client = config.get_mail_client()
1359
self.assertIsInstance(client, mail_client.Mutt)
1361
config.set_user_option('mail_client', 'thunderbird')
1362
client = config.get_mail_client()
1363
self.assertIsInstance(client, mail_client.Thunderbird)
1366
config.set_user_option('mail_client', 'default')
1367
client = config.get_mail_client()
1368
self.assertIsInstance(client, mail_client.DefaultMail)
1370
config.set_user_option('mail_client', 'editor')
1371
client = config.get_mail_client()
1372
self.assertIsInstance(client, mail_client.Editor)
1374
config.set_user_option('mail_client', 'mapi')
1375
client = config.get_mail_client()
1376
self.assertIsInstance(client, mail_client.MAPIClient)
1378
config.set_user_option('mail_client', 'xdg-email')
1379
client = config.get_mail_client()
1380
self.assertIsInstance(client, mail_client.XDGEmail)
1382
config.set_user_option('mail_client', 'firebird')
1383
self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1386
class TestMailAddressExtraction(tests.TestCase):
787
1388
def test_extract_email_address(self):
788
1389
self.assertEqual('jane@test.com',
789
1390
config.extract_email_address('Jane <jane@test.com>'))
790
self.assertRaises(errors.BzrError,
1391
self.assertRaises(errors.NoEmailInUsername,
791
1392
config.extract_email_address, 'Jane Tester')
1394
def test_parse_username(self):
1395
self.assertEqual(('', 'jdoe@example.com'),
1396
config.parse_username('jdoe@example.com'))
1397
self.assertEqual(('', 'jdoe@example.com'),
1398
config.parse_username('<jdoe@example.com>'))
1399
self.assertEqual(('John Doe', 'jdoe@example.com'),
1400
config.parse_username('John Doe <jdoe@example.com>'))
1401
self.assertEqual(('John Doe', ''),
1402
config.parse_username('John Doe'))
1403
self.assertEqual(('John Doe', 'jdoe@example.com'),
1404
config.parse_username('John Doe jdoe@example.com'))
1406
class TestTreeConfig(tests.TestCaseWithTransport):
1408
def test_get_value(self):
1409
"""Test that retreiving a value from a section is possible"""
1410
branch = self.make_branch('.')
1411
tree_config = config.TreeConfig(branch)
1412
tree_config.set_option('value', 'key', 'SECTION')
1413
tree_config.set_option('value2', 'key2')
1414
tree_config.set_option('value3-top', 'key3')
1415
tree_config.set_option('value3-section', 'key3', 'SECTION')
1416
value = tree_config.get_option('key', 'SECTION')
1417
self.assertEqual(value, 'value')
1418
value = tree_config.get_option('key2')
1419
self.assertEqual(value, 'value2')
1420
self.assertEqual(tree_config.get_option('non-existant'), None)
1421
value = tree_config.get_option('non-existant', 'SECTION')
1422
self.assertEqual(value, None)
1423
value = tree_config.get_option('non-existant', default='default')
1424
self.assertEqual(value, 'default')
1425
self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1426
value = tree_config.get_option('key2', 'NOSECTION', default='default')
1427
self.assertEqual(value, 'default')
1428
value = tree_config.get_option('key3')
1429
self.assertEqual(value, 'value3-top')
1430
value = tree_config.get_option('key3', 'SECTION')
1431
self.assertEqual(value, 'value3-section')
1434
class TestTransportConfig(tests.TestCaseWithTransport):
1436
def test_get_value(self):
1437
"""Test that retreiving a value from a section is possible"""
1438
bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1440
bzrdir_config.set_option('value', 'key', 'SECTION')
1441
bzrdir_config.set_option('value2', 'key2')
1442
bzrdir_config.set_option('value3-top', 'key3')
1443
bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1444
value = bzrdir_config.get_option('key', 'SECTION')
1445
self.assertEqual(value, 'value')
1446
value = bzrdir_config.get_option('key2')
1447
self.assertEqual(value, 'value2')
1448
self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1449
value = bzrdir_config.get_option('non-existant', 'SECTION')
1450
self.assertEqual(value, None)
1451
value = bzrdir_config.get_option('non-existant', default='default')
1452
self.assertEqual(value, 'default')
1453
self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1454
value = bzrdir_config.get_option('key2', 'NOSECTION',
1456
self.assertEqual(value, 'default')
1457
value = bzrdir_config.get_option('key3')
1458
self.assertEqual(value, 'value3-top')
1459
value = bzrdir_config.get_option('key3', 'SECTION')
1460
self.assertEqual(value, 'value3-section')
1462
def test_set_unset_default_stack_on(self):
1463
my_dir = self.make_bzrdir('.')
1464
bzrdir_config = config.BzrDirConfig(my_dir)
1465
self.assertIs(None, bzrdir_config.get_default_stack_on())
1466
bzrdir_config.set_default_stack_on('Foo')
1467
self.assertEqual('Foo', bzrdir_config._config.get_option(
1468
'default_stack_on'))
1469
self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1470
bzrdir_config.set_default_stack_on(None)
1471
self.assertIs(None, bzrdir_config.get_default_stack_on())
1474
def create_configs(test):
1475
"""Create configuration files for a given test.
1477
This requires creating a tree (and populate the ``test.tree`` attribute and
1478
its associated branch and will populate the following attributes:
1480
- branch_config: A BranchConfig for the associated branch.
1482
- locations_config : A LocationConfig for the associated branch
1484
- bazaar_config: A GlobalConfig.
1486
The tree and branch are created in a 'tree' subdirectory so the tests can
1487
still use the test directory to stay outside of the branch.
1489
tree = test.make_branch_and_tree('tree')
1491
test.branch_config = config.BranchConfig(tree.branch)
1492
test.locations_config = config.LocationConfig(tree.basedir)
1493
test.bazaar_config = config.GlobalConfig()
1496
def create_configs_with_file_option(test):
1497
"""Create configuration files with a ``file`` option set in each.
1499
This builds on ``create_configs`` and add one ``file`` option in each
1500
configuration with a value which allows identifying the configuration file.
1502
create_configs(test)
1503
test.bazaar_config.set_user_option('file', 'bazaar')
1504
test.locations_config.set_user_option('file', 'locations')
1505
test.branch_config.set_user_option('file', 'branch')
1508
class TestConfigGetOptions(tests.TestCaseWithTransport):
1511
super(TestConfigGetOptions, self).setUp()
1512
create_configs(self)
1514
def assertOptions(self, expected, conf):
1515
actual = list(conf._get_options())
1516
self.assertEqual(expected, actual)
1518
# One variable in none of the above
1519
def test_no_variable(self):
1520
# Using branch should query branch, locations and bazaar
1521
self.assertOptions([], self.branch_config)
1523
def test_option_in_bazaar(self):
1524
self.bazaar_config.set_user_option('file', 'bazaar')
1525
self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
1528
def test_option_in_locations(self):
1529
self.locations_config.set_user_option('file', 'locations')
1531
[('file', 'locations', self.tree.basedir, 'locations')],
1532
self.locations_config)
1534
def test_option_in_branch(self):
1535
self.branch_config.set_user_option('file', 'branch')
1536
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
1539
def test_option_in_bazaar_and_branch(self):
1540
self.bazaar_config.set_user_option('file', 'bazaar')
1541
self.branch_config.set_user_option('file', 'branch')
1542
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
1543
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1546
def test_option_in_branch_and_locations(self):
1547
# Hmm, locations override branch :-/
1548
self.locations_config.set_user_option('file', 'locations')
1549
self.branch_config.set_user_option('file', 'branch')
1551
[('file', 'locations', self.tree.basedir, 'locations'),
1552
('file', 'branch', 'DEFAULT', 'branch'),],
1555
def test_option_in_bazaar_locations_and_branch(self):
1556
self.bazaar_config.set_user_option('file', 'bazaar')
1557
self.locations_config.set_user_option('file', 'locations')
1558
self.branch_config.set_user_option('file', 'branch')
1560
[('file', 'locations', self.tree.basedir, 'locations'),
1561
('file', 'branch', 'DEFAULT', 'branch'),
1562
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1566
class TestConfigRemoveOption(tests.TestCaseWithTransport):
1569
super(TestConfigRemoveOption, self).setUp()
1570
create_configs_with_file_option(self)
1572
def assertOptions(self, expected, conf):
1573
actual = list(conf._get_options())
1574
self.assertEqual(expected, actual)
1576
def test_remove_in_locations(self):
1577
self.locations_config.remove_user_option('file', self.tree.basedir)
1579
[('file', 'branch', 'DEFAULT', 'branch'),
1580
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1583
def test_remove_in_branch(self):
1584
self.branch_config.remove_user_option('file')
1586
[('file', 'locations', self.tree.basedir, 'locations'),
1587
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1590
def test_remove_in_bazaar(self):
1591
self.bazaar_config.remove_user_option('file')
1593
[('file', 'locations', self.tree.basedir, 'locations'),
1594
('file', 'branch', 'DEFAULT', 'branch'),],
1598
class TestConfigGetSections(tests.TestCaseWithTransport):
1601
super(TestConfigGetSections, self).setUp()
1602
create_configs(self)
1604
def assertSectionNames(self, expected, conf, name=None):
1605
"""Check which sections are returned for a given config.
1607
If fallback configurations exist their sections can be included.
1609
:param expected: A list of section names.
1611
:param conf: The configuration that will be queried.
1613
:param name: An optional section name that will be passed to
1616
sections = list(conf._get_sections(name))
1617
self.assertLength(len(expected), sections)
1618
self.assertEqual(expected, [name for name, _, _ in sections])
1620
def test_bazaar_default_section(self):
1621
self.assertSectionNames(['DEFAULT'], self.bazaar_config)
1623
def test_locations_default_section(self):
1624
# No sections are defined in an empty file
1625
self.assertSectionNames([], self.locations_config)
1627
def test_locations_named_section(self):
1628
self.locations_config.set_user_option('file', 'locations')
1629
self.assertSectionNames([self.tree.basedir], self.locations_config)
1631
def test_locations_matching_sections(self):
1632
loc_config = self.locations_config
1633
loc_config.set_user_option('file', 'locations')
1634
# We need to cheat a bit here to create an option in sections above and
1635
# below the 'location' one.
1636
parser = loc_config._get_parser()
1637
# locations.cong deals with '/' ignoring native os.sep
1638
location_names = self.tree.basedir.split('/')
1639
parent = '/'.join(location_names[:-1])
1640
child = '/'.join(location_names + ['child'])
1642
parser[parent]['file'] = 'parent'
1644
parser[child]['file'] = 'child'
1645
self.assertSectionNames([self.tree.basedir, parent], loc_config)
1647
def test_branch_data_default_section(self):
1648
self.assertSectionNames([None],
1649
self.branch_config._get_branch_data_config())
1651
def test_branch_default_sections(self):
1652
# No sections are defined in an empty locations file
1653
self.assertSectionNames([None, 'DEFAULT'],
1655
# Unless we define an option
1656
self.branch_config._get_location_config().set_user_option(
1657
'file', 'locations')
1658
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
1661
def test_bazaar_named_section(self):
1662
# We need to cheat as the API doesn't give direct access to sections
1663
# other than DEFAULT.
1664
self.bazaar_config.set_alias('bazaar', 'bzr')
1665
self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
1668
class TestAuthenticationConfigFile(tests.TestCase):
1669
"""Test the authentication.conf file matching"""
1671
def _got_user_passwd(self, expected_user, expected_password,
1672
config, *args, **kwargs):
1673
credentials = config.get_credentials(*args, **kwargs)
1674
if credentials is None:
1678
user = credentials['user']
1679
password = credentials['password']
1680
self.assertEquals(expected_user, user)
1681
self.assertEquals(expected_password, password)
1683
def test_empty_config(self):
1684
conf = config.AuthenticationConfig(_file=StringIO())
1685
self.assertEquals({}, conf._get_config())
1686
self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1688
def test_missing_auth_section_header(self):
1689
conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1690
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1692
def test_auth_section_header_not_closed(self):
1693
conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1694
self.assertRaises(errors.ParseConfigError, conf._get_config)
1696
def test_auth_value_not_boolean(self):
1697
conf = config.AuthenticationConfig(_file=StringIO(
1701
verify_certificates=askme # Error: Not a boolean
1703
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1705
def test_auth_value_not_int(self):
1706
conf = config.AuthenticationConfig(_file=StringIO(
1710
port=port # Error: Not an int
1712
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1714
def test_unknown_password_encoding(self):
1715
conf = config.AuthenticationConfig(_file=StringIO(
1719
password_encoding=unknown
1721
self.assertRaises(ValueError, conf.get_password,
1722
'ftp', 'foo.net', 'joe')
1724
def test_credentials_for_scheme_host(self):
1725
conf = config.AuthenticationConfig(_file=StringIO(
1726
"""# Identity on foo.net
1731
password=secret-pass
1734
self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1736
self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1738
self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1740
def test_credentials_for_host_port(self):
1741
conf = config.AuthenticationConfig(_file=StringIO(
1742
"""# Identity on foo.net
1748
password=secret-pass
1751
self._got_user_passwd('joe', 'secret-pass',
1752
conf, 'ftp', 'foo.net', port=10021)
1754
self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1756
def test_for_matching_host(self):
1757
conf = config.AuthenticationConfig(_file=StringIO(
1758
"""# Identity on foo.net
1764
[sourceforge domain]
1771
self._got_user_passwd('georges', 'bendover',
1772
conf, 'bzr', 'foo.bzr.sf.net')
1774
self._got_user_passwd(None, None,
1775
conf, 'bzr', 'bbzr.sf.net')
1777
def test_for_matching_host_None(self):
1778
conf = config.AuthenticationConfig(_file=StringIO(
1779
"""# Identity on foo.net
1789
self._got_user_passwd('joe', 'joepass',
1790
conf, 'bzr', 'quux.net')
1791
# no host but different scheme
1792
self._got_user_passwd('georges', 'bendover',
1793
conf, 'ftp', 'quux.net')
1795
def test_credentials_for_path(self):
1796
conf = config.AuthenticationConfig(_file=StringIO(
1812
self._got_user_passwd(None, None,
1813
conf, 'http', host='bar.org', path='/dir3')
1815
self._got_user_passwd('georges', 'bendover',
1816
conf, 'http', host='bar.org', path='/dir2')
1818
self._got_user_passwd('jim', 'jimpass',
1819
conf, 'http', host='bar.org',path='/dir1/subdir')
1821
def test_credentials_for_user(self):
1822
conf = config.AuthenticationConfig(_file=StringIO(
1831
self._got_user_passwd('jim', 'jimpass',
1832
conf, 'http', 'bar.org')
1834
self._got_user_passwd('jim', 'jimpass',
1835
conf, 'http', 'bar.org', user='jim')
1836
# Don't get a different user if one is specified
1837
self._got_user_passwd(None, None,
1838
conf, 'http', 'bar.org', user='georges')
1840
def test_credentials_for_user_without_password(self):
1841
conf = config.AuthenticationConfig(_file=StringIO(
1848
# Get user but no password
1849
self._got_user_passwd('jim', None,
1850
conf, 'http', 'bar.org')
1852
def test_verify_certificates(self):
1853
conf = config.AuthenticationConfig(_file=StringIO(
1860
verify_certificates=False
1867
credentials = conf.get_credentials('https', 'bar.org')
1868
self.assertEquals(False, credentials.get('verify_certificates'))
1869
credentials = conf.get_credentials('https', 'foo.net')
1870
self.assertEquals(True, credentials.get('verify_certificates'))
1873
class TestAuthenticationStorage(tests.TestCaseInTempDir):
1875
def test_set_credentials(self):
1876
conf = config.AuthenticationConfig()
1877
conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
1878
99, path='/foo', verify_certificates=False, realm='realm')
1879
credentials = conf.get_credentials(host='host', scheme='scheme',
1880
port=99, path='/foo',
1882
CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
1883
'verify_certificates': False, 'scheme': 'scheme',
1884
'host': 'host', 'port': 99, 'path': '/foo',
1886
self.assertEqual(CREDENTIALS, credentials)
1887
credentials_from_disk = config.AuthenticationConfig().get_credentials(
1888
host='host', scheme='scheme', port=99, path='/foo', realm='realm')
1889
self.assertEqual(CREDENTIALS, credentials_from_disk)
1891
def test_reset_credentials_different_name(self):
1892
conf = config.AuthenticationConfig()
1893
conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
1894
conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
1895
self.assertIs(None, conf._get_config().get('name'))
1896
credentials = conf.get_credentials(host='host', scheme='scheme')
1897
CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
1898
'password', 'verify_certificates': True,
1899
'scheme': 'scheme', 'host': 'host', 'port': None,
1900
'path': None, 'realm': None}
1901
self.assertEqual(CREDENTIALS, credentials)
1904
class TestAuthenticationConfig(tests.TestCase):
1905
"""Test AuthenticationConfig behaviour"""
1907
def _check_default_password_prompt(self, expected_prompt_format, scheme,
1908
host=None, port=None, realm=None,
1912
user, password = 'jim', 'precious'
1913
expected_prompt = expected_prompt_format % {
1914
'scheme': scheme, 'host': host, 'port': port,
1915
'user': user, 'realm': realm}
1917
stdout = tests.StringIOWrapper()
1918
stderr = tests.StringIOWrapper()
1919
ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
1920
stdout=stdout, stderr=stderr)
1921
# We use an empty conf so that the user is always prompted
1922
conf = config.AuthenticationConfig()
1923
self.assertEquals(password,
1924
conf.get_password(scheme, host, user, port=port,
1925
realm=realm, path=path))
1926
self.assertEquals(expected_prompt, stderr.getvalue())
1927
self.assertEquals('', stdout.getvalue())
1929
def _check_default_username_prompt(self, expected_prompt_format, scheme,
1930
host=None, port=None, realm=None,
1935
expected_prompt = expected_prompt_format % {
1936
'scheme': scheme, 'host': host, 'port': port,
1938
stdout = tests.StringIOWrapper()
1939
stderr = tests.StringIOWrapper()
1940
ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
1941
stdout=stdout, stderr=stderr)
1942
# We use an empty conf so that the user is always prompted
1943
conf = config.AuthenticationConfig()
1944
self.assertEquals(username, conf.get_user(scheme, host, port=port,
1945
realm=realm, path=path, ask=True))
1946
self.assertEquals(expected_prompt, stderr.getvalue())
1947
self.assertEquals('', stdout.getvalue())
1949
def test_username_defaults_prompts(self):
1950
# HTTP prompts can't be tested here, see test_http.py
1951
self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
1952
self._check_default_username_prompt(
1953
'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
1954
self._check_default_username_prompt(
1955
'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1957
def test_username_default_no_prompt(self):
1958
conf = config.AuthenticationConfig()
1959
self.assertEquals(None,
1960
conf.get_user('ftp', 'example.com'))
1961
self.assertEquals("explicitdefault",
1962
conf.get_user('ftp', 'example.com', default="explicitdefault"))
1964
def test_password_default_prompts(self):
1965
# HTTP prompts can't be tested here, see test_http.py
1966
self._check_default_password_prompt(
1967
'FTP %(user)s@%(host)s password: ', 'ftp')
1968
self._check_default_password_prompt(
1969
'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
1970
self._check_default_password_prompt(
1971
'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
1972
# SMTP port handling is a bit special (it's handled if embedded in the
1974
# FIXME: should we: forbid that, extend it to other schemes, leave
1975
# things as they are that's fine thank you ?
1976
self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
1978
self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
1979
'smtp', host='bar.org:10025')
1980
self._check_default_password_prompt(
1981
'SMTP %(user)s@%(host)s:%(port)d password: ',
1984
def test_ssh_password_emits_warning(self):
1985
conf = config.AuthenticationConfig(_file=StringIO(
1993
entered_password = 'typed-by-hand'
1994
stdout = tests.StringIOWrapper()
1995
stderr = tests.StringIOWrapper()
1996
ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
1997
stdout=stdout, stderr=stderr)
1999
# Since the password defined in the authentication config is ignored,
2000
# the user is prompted
2001
self.assertEquals(entered_password,
2002
conf.get_password('ssh', 'bar.org', user='jim'))
2003
self.assertContainsRe(
2005
'password ignored in section \[ssh with password\]')
2007
def test_ssh_without_password_doesnt_emit_warning(self):
2008
conf = config.AuthenticationConfig(_file=StringIO(
2015
entered_password = 'typed-by-hand'
2016
stdout = tests.StringIOWrapper()
2017
stderr = tests.StringIOWrapper()
2018
ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
2022
# Since the password defined in the authentication config is ignored,
2023
# the user is prompted
2024
self.assertEquals(entered_password,
2025
conf.get_password('ssh', 'bar.org', user='jim'))
2026
# No warning shoud be emitted since there is no password. We are only
2028
self.assertNotContainsRe(
2030
'password ignored in section \[ssh with password\]')
2032
def test_uses_fallback_stores(self):
2033
self.overrideAttr(config, 'credential_store_registry',
2034
config.CredentialStoreRegistry())
2035
store = StubCredentialStore()
2036
store.add_credentials("http", "example.com", "joe", "secret")
2037
config.credential_store_registry.register("stub", store, fallback=True)
2038
conf = config.AuthenticationConfig(_file=StringIO())
2039
creds = conf.get_credentials("http", "example.com")
2040
self.assertEquals("joe", creds["user"])
2041
self.assertEquals("secret", creds["password"])
2044
class StubCredentialStore(config.CredentialStore):
2050
def add_credentials(self, scheme, host, user, password=None):
2051
self._username[(scheme, host)] = user
2052
self._password[(scheme, host)] = password
2054
def get_credentials(self, scheme, host, port=None, user=None,
2055
path=None, realm=None):
2056
key = (scheme, host)
2057
if not key in self._username:
2059
return { "scheme": scheme, "host": host, "port": port,
2060
"user": self._username[key], "password": self._password[key]}
2063
class CountingCredentialStore(config.CredentialStore):
2068
def get_credentials(self, scheme, host, port=None, user=None,
2069
path=None, realm=None):
2074
class TestCredentialStoreRegistry(tests.TestCase):
2076
def _get_cs_registry(self):
2077
return config.credential_store_registry
2079
def test_default_credential_store(self):
2080
r = self._get_cs_registry()
2081
default = r.get_credential_store(None)
2082
self.assertIsInstance(default, config.PlainTextCredentialStore)
2084
def test_unknown_credential_store(self):
2085
r = self._get_cs_registry()
2086
# It's hard to imagine someone creating a credential store named
2087
# 'unknown' so we use that as an never registered key.
2088
self.assertRaises(KeyError, r.get_credential_store, 'unknown')
2090
def test_fallback_none_registered(self):
2091
r = config.CredentialStoreRegistry()
2092
self.assertEquals(None,
2093
r.get_fallback_credentials("http", "example.com"))
2095
def test_register(self):
2096
r = config.CredentialStoreRegistry()
2097
r.register("stub", StubCredentialStore(), fallback=False)
2098
r.register("another", StubCredentialStore(), fallback=True)
2099
self.assertEquals(["another", "stub"], r.keys())
2101
def test_register_lazy(self):
2102
r = config.CredentialStoreRegistry()
2103
r.register_lazy("stub", "bzrlib.tests.test_config",
2104
"StubCredentialStore", fallback=False)
2105
self.assertEquals(["stub"], r.keys())
2106
self.assertIsInstance(r.get_credential_store("stub"),
2107
StubCredentialStore)
2109
def test_is_fallback(self):
2110
r = config.CredentialStoreRegistry()
2111
r.register("stub1", None, fallback=False)
2112
r.register("stub2", None, fallback=True)
2113
self.assertEquals(False, r.is_fallback("stub1"))
2114
self.assertEquals(True, r.is_fallback("stub2"))
2116
def test_no_fallback(self):
2117
r = config.CredentialStoreRegistry()
2118
store = CountingCredentialStore()
2119
r.register("count", store, fallback=False)
2120
self.assertEquals(None,
2121
r.get_fallback_credentials("http", "example.com"))
2122
self.assertEquals(0, store._calls)
2124
def test_fallback_credentials(self):
2125
r = config.CredentialStoreRegistry()
2126
store = StubCredentialStore()
2127
store.add_credentials("http", "example.com",
2128
"somebody", "geheim")
2129
r.register("stub", store, fallback=True)
2130
creds = r.get_fallback_credentials("http", "example.com")
2131
self.assertEquals("somebody", creds["user"])
2132
self.assertEquals("geheim", creds["password"])
2134
def test_fallback_first_wins(self):
2135
r = config.CredentialStoreRegistry()
2136
stub1 = StubCredentialStore()
2137
stub1.add_credentials("http", "example.com",
2138
"somebody", "stub1")
2139
r.register("stub1", stub1, fallback=True)
2140
stub2 = StubCredentialStore()
2141
stub2.add_credentials("http", "example.com",
2142
"somebody", "stub2")
2143
r.register("stub2", stub1, fallback=True)
2144
creds = r.get_fallback_credentials("http", "example.com")
2145
self.assertEquals("somebody", creds["user"])
2146
self.assertEquals("stub1", creds["password"])
2149
class TestPlainTextCredentialStore(tests.TestCase):
2151
def test_decode_password(self):
2152
r = config.credential_store_registry
2153
plain_text = r.get_credential_store()
2154
decoded = plain_text.decode_password(dict(password='secret'))
2155
self.assertEquals('secret', decoded)
2158
# FIXME: Once we have a way to declare authentication to all test servers, we
2159
# can implement generic tests.
2160
# test_user_password_in_url
2161
# test_user_in_url_password_from_config
2162
# test_user_in_url_password_prompted
2163
# test_user_in_config
2164
# test_user_getpass.getuser
2165
# test_user_prompted ?
2166
class TestAuthenticationRing(tests.TestCaseWithTransport):