~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Martin Pool
  • Date: 2010-08-05 08:18:06 UTC
  • mto: (5050.3.20 2.2)
  • mto: This revision was merged to the branch mainline in revision 5371.
  • Revision ID: mbp@sourcefrog.net-20100805081806-4c4gjsiw9i3j0c3w
Clear off progress bars by painting spaces.

This selectively reverts part of the previous progress change.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2008 Canonical Ltd
2
 
#   Authors: Robert Collins <robert.collins@canonical.com>
 
1
# Copyright (C) 2005-2010 Canonical Ltd
3
2
#
4
3
# This program is free software; you can redistribute it and/or modify
5
4
# it under the terms of the GNU General Public License as published by
26
25
    branch,
27
26
    bzrdir,
28
27
    config,
 
28
    diff,
29
29
    errors,
30
30
    osutils,
31
31
    mail_client,
35
35
    trace,
36
36
    transport,
37
37
    )
 
38
from bzrlib.tests import features
38
39
from bzrlib.util.configobj import configobj
39
40
 
40
41
 
43
44
[DEFAULT]
44
45
email=Erik B\u00e5gfors <erik@bagfors.nu>
45
46
editor=vim
 
47
change_editor=vimdiff -of @new_path @old_path
46
48
gpg_signing_command=gnome-gpg
47
49
log_format=short
48
50
user_global_option=something
150
152
        self._transport = self.control_files = \
151
153
            FakeControlFilesAndTransport(user_id=user_id)
152
154
 
 
155
    def _get_config(self):
 
156
        return config.TransportConfig(self._transport, 'branch.conf')
 
157
 
153
158
    def lock_write(self):
154
159
        pass
155
160
 
206
211
        self._calls.append('_get_signature_checking')
207
212
        return self._signatures
208
213
 
 
214
    def _get_change_editor(self):
 
215
        self._calls.append('_get_change_editor')
 
216
        return 'vimdiff -fo @new_path @old_path'
 
217
 
209
218
 
210
219
bool_config = """[DEFAULT]
211
220
active = true
312
321
        my_config = config.Config()
313
322
        self.assertEqual('long', my_config.log_format())
314
323
 
 
324
    def test_get_change_editor(self):
 
325
        my_config = InstrumentedConfig()
 
326
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
 
327
        self.assertEqual(['_get_change_editor'], my_config._calls)
 
328
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
 
329
        self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
 
330
                         change_editor.command_template)
 
331
 
315
332
 
316
333
class TestConfigPath(tests.TestCase):
317
334
 
318
335
    def setUp(self):
319
336
        super(TestConfigPath, self).setUp()
320
337
        os.environ['HOME'] = '/home/bogus'
 
338
        os.environ['XDG_CACHE_DIR'] = ''
321
339
        if sys.platform == 'win32':
322
340
            os.environ['BZR_HOME'] = \
323
341
                r'C:\Documents and Settings\bogus\Application Data'
345
363
        self.assertEqual(config.authentication_config_filename(),
346
364
                         self.bzr_home + '/authentication.conf')
347
365
 
348
 
 
349
 
class TestIniConfig(tests.TestCase):
 
366
    def test_xdg_cache_dir(self):
 
367
        self.assertEqual(config.xdg_cache_dir(),
 
368
            '/home/bogus/.cache')
 
369
 
 
370
 
 
371
class TestIniConfig(tests.TestCaseInTempDir):
 
372
 
 
373
    def make_config_parser(self, s):
 
374
        conf = config.IniBasedConfig(None)
 
375
        parser = conf._get_parser(file=StringIO(s.encode('utf-8')))
 
376
        return conf, parser
 
377
 
 
378
 
 
379
class TestIniConfigBuilding(TestIniConfig):
350
380
 
351
381
    def test_contructs(self):
352
382
        my_config = config.IniBasedConfig("nothing")
364
394
        parser = my_config._get_parser(file=config_file)
365
395
        self.failUnless(my_config._get_parser() is parser)
366
396
 
 
397
    def _dummy_chown(self, path, uid, gid):
 
398
        self.path, self.uid, self.gid = path, uid, gid
 
399
 
 
400
    def test_ini_config_ownership(self):
 
401
        """Ensure that chown is happening during _write_config_file.
 
402
        """
 
403
        self.requireFeature(features.chown_feature)
 
404
        self.overrideAttr(os, 'chown', self._dummy_chown)
 
405
        self.path = self.uid = self.gid = None
 
406
        def get_filename():
 
407
            return 'foo.conf'
 
408
        conf = config.IniBasedConfig(get_filename)
 
409
        conf._write_config_file()
 
410
        self.assertEquals(self.path, 'foo.conf')
 
411
        self.assertTrue(isinstance(self.uid, int))
 
412
        self.assertTrue(isinstance(self.gid, int))
 
413
 
 
414
class TestGetUserOptionAs(TestIniConfig):
 
415
 
 
416
    def test_get_user_option_as_bool(self):
 
417
        conf, parser = self.make_config_parser("""
 
418
a_true_bool = true
 
419
a_false_bool = 0
 
420
an_invalid_bool = maybe
 
421
a_list = hmm, who knows ? # This is interpreted as a list !
 
422
""")
 
423
        get_bool = conf.get_user_option_as_bool
 
424
        self.assertEqual(True, get_bool('a_true_bool'))
 
425
        self.assertEqual(False, get_bool('a_false_bool'))
 
426
        warnings = []
 
427
        def warning(*args):
 
428
            warnings.append(args[0] % args[1:])
 
429
        self.overrideAttr(trace, 'warning', warning)
 
430
        msg = 'Value "%s" is not a boolean for "%s"'
 
431
        self.assertIs(None, get_bool('an_invalid_bool'))
 
432
        self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
 
433
        warnings = []
 
434
        self.assertIs(None, get_bool('not_defined_in_this_config'))
 
435
        self.assertEquals([], warnings)
 
436
 
 
437
    def test_get_user_option_as_list(self):
 
438
        conf, parser = self.make_config_parser("""
 
439
a_list = a,b,c
 
440
length_1 = 1,
 
441
one_item = x
 
442
""")
 
443
        get_list = conf.get_user_option_as_list
 
444
        self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
 
445
        self.assertEqual(['1'], get_list('length_1'))
 
446
        self.assertEqual('x', conf.get_user_option('one_item'))
 
447
        # automatically cast to list
 
448
        self.assertEqual(['x'], get_list('one_item'))
 
449
 
 
450
 
 
451
class TestSupressWarning(TestIniConfig):
 
452
 
 
453
    def make_warnings_config(self, s):
 
454
        conf, parser = self.make_config_parser(s)
 
455
        return conf.suppress_warning
 
456
 
 
457
    def test_suppress_warning_unknown(self):
 
458
        suppress_warning = self.make_warnings_config('')
 
459
        self.assertEqual(False, suppress_warning('unknown_warning'))
 
460
 
 
461
    def test_suppress_warning_known(self):
 
462
        suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
 
463
        self.assertEqual(False, suppress_warning('c'))
 
464
        self.assertEqual(True, suppress_warning('a'))
 
465
        self.assertEqual(True, suppress_warning('b'))
 
466
 
367
467
 
368
468
class TestGetConfig(tests.TestCase):
369
469
 
604
704
        my_config = self._get_sample_config()
605
705
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
606
706
 
 
707
    def test_get_change_editor(self):
 
708
        my_config = self._get_sample_config()
 
709
        change_editor = my_config.get_change_editor('old', 'new')
 
710
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
 
711
        self.assertEqual('vimdiff -of @new_path @old_path',
 
712
                         ' '.join(change_editor.command_template))
 
713
 
 
714
    def test_get_no_change_editor(self):
 
715
        my_config = self._get_empty_config()
 
716
        change_editor = my_config.get_change_editor('old', 'new')
 
717
        self.assertIs(None, change_editor)
 
718
 
607
719
 
608
720
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
609
721
 
1207
1319
 
1208
1320
    def test_set_unset_default_stack_on(self):
1209
1321
        my_dir = self.make_bzrdir('.')
1210
 
        bzrdir_config = config.BzrDirConfig(my_dir.transport)
 
1322
        bzrdir_config = config.BzrDirConfig(my_dir)
1211
1323
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1212
1324
        bzrdir_config.set_default_stack_on('Foo')
1213
1325
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1456
1568
class TestAuthenticationConfig(tests.TestCase):
1457
1569
    """Test AuthenticationConfig behaviour"""
1458
1570
 
1459
 
    def _check_default_prompt(self, expected_prompt_format, scheme,
1460
 
                              host=None, port=None, realm=None, path=None):
 
1571
    def _check_default_password_prompt(self, expected_prompt_format, scheme,
 
1572
                                       host=None, port=None, realm=None,
 
1573
                                       path=None):
1461
1574
        if host is None:
1462
1575
            host = 'bar.org'
1463
1576
        user, password = 'jim', 'precious'
1466
1579
            'user': user, 'realm': realm}
1467
1580
 
1468
1581
        stdout = tests.StringIOWrapper()
 
1582
        stderr = tests.StringIOWrapper()
1469
1583
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
1470
 
                                            stdout=stdout)
 
1584
                                            stdout=stdout, stderr=stderr)
1471
1585
        # We use an empty conf so that the user is always prompted
1472
1586
        conf = config.AuthenticationConfig()
1473
1587
        self.assertEquals(password,
1474
1588
                          conf.get_password(scheme, host, user, port=port,
1475
1589
                                            realm=realm, path=path))
1476
 
        self.assertEquals(stdout.getvalue(), expected_prompt)
1477
 
 
1478
 
    def test_default_prompts(self):
1479
 
        # HTTP prompts can't be tested here, see test_http.py
1480
 
        self._check_default_prompt('FTP %(user)s@%(host)s password: ', 'ftp')
1481
 
        self._check_default_prompt('FTP %(user)s@%(host)s:%(port)d password: ',
1482
 
                                   'ftp', port=10020)
1483
 
 
1484
 
        self._check_default_prompt('SSH %(user)s@%(host)s:%(port)d password: ',
1485
 
                                   'ssh', port=12345)
 
1590
        self.assertEquals(expected_prompt, stderr.getvalue())
 
1591
        self.assertEquals('', stdout.getvalue())
 
1592
 
 
1593
    def _check_default_username_prompt(self, expected_prompt_format, scheme,
 
1594
                                       host=None, port=None, realm=None,
 
1595
                                       path=None):
 
1596
        if host is None:
 
1597
            host = 'bar.org'
 
1598
        username = 'jim'
 
1599
        expected_prompt = expected_prompt_format % {
 
1600
            'scheme': scheme, 'host': host, 'port': port,
 
1601
            'realm': realm}
 
1602
        stdout = tests.StringIOWrapper()
 
1603
        stderr = tests.StringIOWrapper()
 
1604
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
 
1605
                                            stdout=stdout, stderr=stderr)
 
1606
        # We use an empty conf so that the user is always prompted
 
1607
        conf = config.AuthenticationConfig()
 
1608
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
 
1609
                          realm=realm, path=path, ask=True))
 
1610
        self.assertEquals(expected_prompt, stderr.getvalue())
 
1611
        self.assertEquals('', stdout.getvalue())
 
1612
 
 
1613
    def test_username_defaults_prompts(self):
 
1614
        # HTTP prompts can't be tested here, see test_http.py
 
1615
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
 
1616
        self._check_default_username_prompt(
 
1617
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
 
1618
        self._check_default_username_prompt(
 
1619
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
 
1620
 
 
1621
    def test_username_default_no_prompt(self):
 
1622
        conf = config.AuthenticationConfig()
 
1623
        self.assertEquals(None,
 
1624
            conf.get_user('ftp', 'example.com'))
 
1625
        self.assertEquals("explicitdefault",
 
1626
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
 
1627
 
 
1628
    def test_password_default_prompts(self):
 
1629
        # HTTP prompts can't be tested here, see test_http.py
 
1630
        self._check_default_password_prompt(
 
1631
            'FTP %(user)s@%(host)s password: ', 'ftp')
 
1632
        self._check_default_password_prompt(
 
1633
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
 
1634
        self._check_default_password_prompt(
 
1635
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
1486
1636
        # SMTP port handling is a bit special (it's handled if embedded in the
1487
1637
        # host too)
1488
1638
        # FIXME: should we: forbid that, extend it to other schemes, leave
1489
1639
        # things as they are that's fine thank you ?
1490
 
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
1491
 
                                   'smtp')
1492
 
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
1493
 
                                   'smtp', host='bar.org:10025')
1494
 
        self._check_default_prompt(
 
1640
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
 
1641
                                            'smtp')
 
1642
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
 
1643
                                            'smtp', host='bar.org:10025')
 
1644
        self._check_default_password_prompt(
1495
1645
            'SMTP %(user)s@%(host)s:%(port)d password: ',
1496
1646
            'smtp', port=10025)
1497
1647
 
1506
1656
"""))
1507
1657
        entered_password = 'typed-by-hand'
1508
1658
        stdout = tests.StringIOWrapper()
 
1659
        stderr = tests.StringIOWrapper()
1509
1660
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
1510
 
                                            stdout=stdout)
 
1661
                                            stdout=stdout, stderr=stderr)
1511
1662
 
1512
1663
        # Since the password defined in the authentication config is ignored,
1513
1664
        # the user is prompted
1514
1665
        self.assertEquals(entered_password,
1515
1666
                          conf.get_password('ssh', 'bar.org', user='jim'))
1516
1667
        self.assertContainsRe(
1517
 
            self._get_log(keep_log_file=True),
 
1668
            self.get_log(),
1518
1669
            'password ignored in section \[ssh with password\]')
1519
1670
 
1520
1671
    def test_ssh_without_password_doesnt_emit_warning(self):
1527
1678
"""))
1528
1679
        entered_password = 'typed-by-hand'
1529
1680
        stdout = tests.StringIOWrapper()
 
1681
        stderr = tests.StringIOWrapper()
1530
1682
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
1531
 
                                            stdout=stdout)
 
1683
                                            stdout=stdout,
 
1684
                                            stderr=stderr)
1532
1685
 
1533
1686
        # Since the password defined in the authentication config is ignored,
1534
1687
        # the user is prompted
1537
1690
        # No warning shoud be emitted since there is no password. We are only
1538
1691
        # providing "user".
1539
1692
        self.assertNotContainsRe(
1540
 
            self._get_log(keep_log_file=True),
 
1693
            self.get_log(),
1541
1694
            'password ignored in section \[ssh with password\]')
1542
1695
 
 
1696
    def test_uses_fallback_stores(self):
 
1697
        self.overrideAttr(config, 'credential_store_registry',
 
1698
                          config.CredentialStoreRegistry())
 
1699
        store = StubCredentialStore()
 
1700
        store.add_credentials("http", "example.com", "joe", "secret")
 
1701
        config.credential_store_registry.register("stub", store, fallback=True)
 
1702
        conf = config.AuthenticationConfig(_file=StringIO())
 
1703
        creds = conf.get_credentials("http", "example.com")
 
1704
        self.assertEquals("joe", creds["user"])
 
1705
        self.assertEquals("secret", creds["password"])
 
1706
 
 
1707
 
 
1708
class StubCredentialStore(config.CredentialStore):
 
1709
 
 
1710
    def __init__(self):
 
1711
        self._username = {}
 
1712
        self._password = {}
 
1713
 
 
1714
    def add_credentials(self, scheme, host, user, password=None):
 
1715
        self._username[(scheme, host)] = user
 
1716
        self._password[(scheme, host)] = password
 
1717
 
 
1718
    def get_credentials(self, scheme, host, port=None, user=None,
 
1719
        path=None, realm=None):
 
1720
        key = (scheme, host)
 
1721
        if not key in self._username:
 
1722
            return None
 
1723
        return { "scheme": scheme, "host": host, "port": port,
 
1724
                "user": self._username[key], "password": self._password[key]}
 
1725
 
 
1726
 
 
1727
class CountingCredentialStore(config.CredentialStore):
 
1728
 
 
1729
    def __init__(self):
 
1730
        self._calls = 0
 
1731
 
 
1732
    def get_credentials(self, scheme, host, port=None, user=None,
 
1733
        path=None, realm=None):
 
1734
        self._calls += 1
 
1735
        return None
 
1736
 
1543
1737
 
1544
1738
class TestCredentialStoreRegistry(tests.TestCase):
1545
1739
 
1557
1751
        # 'unknown' so we use that as an never registered key.
1558
1752
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
1559
1753
 
 
1754
    def test_fallback_none_registered(self):
 
1755
        r = config.CredentialStoreRegistry()
 
1756
        self.assertEquals(None,
 
1757
                          r.get_fallback_credentials("http", "example.com"))
 
1758
 
 
1759
    def test_register(self):
 
1760
        r = config.CredentialStoreRegistry()
 
1761
        r.register("stub", StubCredentialStore(), fallback=False)
 
1762
        r.register("another", StubCredentialStore(), fallback=True)
 
1763
        self.assertEquals(["another", "stub"], r.keys())
 
1764
 
 
1765
    def test_register_lazy(self):
 
1766
        r = config.CredentialStoreRegistry()
 
1767
        r.register_lazy("stub", "bzrlib.tests.test_config",
 
1768
                        "StubCredentialStore", fallback=False)
 
1769
        self.assertEquals(["stub"], r.keys())
 
1770
        self.assertIsInstance(r.get_credential_store("stub"),
 
1771
                              StubCredentialStore)
 
1772
 
 
1773
    def test_is_fallback(self):
 
1774
        r = config.CredentialStoreRegistry()
 
1775
        r.register("stub1", None, fallback=False)
 
1776
        r.register("stub2", None, fallback=True)
 
1777
        self.assertEquals(False, r.is_fallback("stub1"))
 
1778
        self.assertEquals(True, r.is_fallback("stub2"))
 
1779
 
 
1780
    def test_no_fallback(self):
 
1781
        r = config.CredentialStoreRegistry()
 
1782
        store = CountingCredentialStore()
 
1783
        r.register("count", store, fallback=False)
 
1784
        self.assertEquals(None,
 
1785
                          r.get_fallback_credentials("http", "example.com"))
 
1786
        self.assertEquals(0, store._calls)
 
1787
 
 
1788
    def test_fallback_credentials(self):
 
1789
        r = config.CredentialStoreRegistry()
 
1790
        store = StubCredentialStore()
 
1791
        store.add_credentials("http", "example.com",
 
1792
                              "somebody", "geheim")
 
1793
        r.register("stub", store, fallback=True)
 
1794
        creds = r.get_fallback_credentials("http", "example.com")
 
1795
        self.assertEquals("somebody", creds["user"])
 
1796
        self.assertEquals("geheim", creds["password"])
 
1797
 
 
1798
    def test_fallback_first_wins(self):
 
1799
        r = config.CredentialStoreRegistry()
 
1800
        stub1 = StubCredentialStore()
 
1801
        stub1.add_credentials("http", "example.com",
 
1802
                              "somebody", "stub1")
 
1803
        r.register("stub1", stub1, fallback=True)
 
1804
        stub2 = StubCredentialStore()
 
1805
        stub2.add_credentials("http", "example.com",
 
1806
                              "somebody", "stub2")
 
1807
        r.register("stub2", stub1, fallback=True)
 
1808
        creds = r.get_fallback_credentials("http", "example.com")
 
1809
        self.assertEquals("somebody", creds["user"])
 
1810
        self.assertEquals("stub1", creds["password"])
 
1811
 
1560
1812
 
1561
1813
class TestPlainTextCredentialStore(tests.TestCase):
1562
1814