~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Patch Queue Manager
  • Date: 2011-09-16 13:27:14 UTC
  • mfrom: (6138.3.15 i18n-gettext-errors)
  • Revision ID: pqm@pqm.ubuntu.com-20110916132714-w81xvesg996w68r6
(jr) Add gettext() to user error messages
 (Jonathan Riddell)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2013, 2016 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
"""Tests for the test framework."""
18
18
 
19
19
from cStringIO import StringIO
20
 
import gc
21
20
import doctest
22
21
import os
23
22
import signal
30
29
from testtools import (
31
30
    ExtendedToOriginalDecorator,
32
31
    MultiTestResult,
 
32
    __version__ as testtools_version,
33
33
    )
34
34
from testtools.content import Content
35
35
from testtools.content_type import ContentType
43
43
from bzrlib import (
44
44
    branchbuilder,
45
45
    bzrdir,
46
 
    controldir,
47
46
    errors,
48
47
    hooks,
49
48
    lockdir,
335
334
        server1 = "a"
336
335
        server2 = "b"
337
336
        formats = [workingtree_4.WorkingTreeFormat4(),
338
 
                   workingtree_3.WorkingTreeFormat3(),
339
 
                   workingtree_4.WorkingTreeFormat6()]
340
 
        scenarios = make_scenarios(server1, server2, formats,
341
 
            remote_server='c', remote_readonly_server='d',
342
 
            remote_backing_server='e')
 
337
                   workingtree_3.WorkingTreeFormat3(),]
 
338
        scenarios = make_scenarios(server1, server2, formats)
343
339
        self.assertEqual([
344
340
            ('WorkingTreeFormat4',
345
341
             {'bzrdir_format': formats[0]._matchingbzrdir,
350
346
             {'bzrdir_format': formats[1]._matchingbzrdir,
351
347
              'transport_readonly_server': 'b',
352
348
              'transport_server': 'a',
353
 
              'workingtree_format': formats[1]}),
354
 
            ('WorkingTreeFormat6',
355
 
             {'bzrdir_format': formats[2]._matchingbzrdir,
356
 
              'transport_readonly_server': 'b',
357
 
              'transport_server': 'a',
358
 
              'workingtree_format': formats[2]}),
359
 
            ('WorkingTreeFormat6,remote',
360
 
             {'bzrdir_format': formats[2]._matchingbzrdir,
361
 
              'repo_is_remote': True,
362
 
              'transport_readonly_server': 'd',
363
 
              'transport_server': 'c',
364
 
              'vfs_transport_factory': 'e',
365
 
              'workingtree_format': formats[2]}),
366
 
            ], scenarios)
 
349
              'workingtree_format': formats[1]})],
 
350
            scenarios)
367
351
 
368
352
 
369
353
class TestTreeScenarios(tests.TestCase):
370
354
 
371
355
    def test_scenarios(self):
372
356
        # the tree implementation scenario generator is meant to setup one
373
 
        # instance for each working tree format, one additional instance
 
357
        # instance for each working tree format, and one additional instance
374
358
        # that will use the default wt format, but create a revision tree for
375
 
        # the tests, and one more that uses the default wt format as a
376
 
        # lightweight checkout of a remote repository.  This means that the wt
377
 
        # ones should have the workingtree_to_test_tree attribute set to
378
 
        # 'return_parameter' and the revision one set to
379
 
        # revision_tree_from_workingtree.
 
359
        # the tests.  this means that the wt ones should have the
 
360
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
 
361
        # revision one set to revision_tree_from_workingtree.
380
362
 
381
363
        from bzrlib.tests.per_tree import (
382
364
            _dirstate_tree_from_workingtree,
388
370
            )
389
371
        server1 = "a"
390
372
        server2 = "b"
391
 
        smart_server = test_server.SmartTCPServer_for_testing
392
 
        smart_readonly_server = test_server.ReadonlySmartTCPServer_for_testing
393
 
        mem_server = memory.MemoryServer
394
373
        formats = [workingtree_4.WorkingTreeFormat4(),
395
374
                   workingtree_3.WorkingTreeFormat3(),]
396
375
        scenarios = make_scenarios(server1, server2, formats)
397
 
        self.assertEqual(8, len(scenarios))
 
376
        self.assertEqual(7, len(scenarios))
398
377
        default_wt_format = workingtree.format_registry.get_default()
399
378
        wt4_format = workingtree_4.WorkingTreeFormat4()
400
379
        wt5_format = workingtree_4.WorkingTreeFormat5()
401
 
        wt6_format = workingtree_4.WorkingTreeFormat6()
402
380
        expected_scenarios = [
403
381
            ('WorkingTreeFormat4',
404
382
             {'bzrdir_format': formats[0]._matchingbzrdir,
414
392
              'workingtree_format': formats[1],
415
393
              '_workingtree_to_test_tree': return_parameter,
416
394
             }),
417
 
            ('WorkingTreeFormat6,remote',
418
 
             {'bzrdir_format': wt6_format._matchingbzrdir,
419
 
              'repo_is_remote': True,
420
 
              'transport_readonly_server': smart_readonly_server,
421
 
              'transport_server': smart_server,
422
 
              'vfs_transport_factory': mem_server,
423
 
              'workingtree_format': wt6_format,
424
 
              '_workingtree_to_test_tree': return_parameter,
425
 
             }),
426
395
            ('RevisionTree',
427
396
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
428
397
              'bzrdir_format': default_wt_format._matchingbzrdir,
640
609
        # Guard against regression into MemoryTransport leaking
641
610
        # files to disk instead of keeping them in memory.
642
611
        self.assertFalse(osutils.lexists('dir'))
643
 
        dir_format = controldir.format_registry.make_bzrdir('knit')
 
612
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
644
613
        self.assertEqual(dir_format.repository_format.__class__,
645
614
                         the_branch.repository._format.__class__)
646
615
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
709
678
        builder = self.make_branch_builder('dir')
710
679
        rev_id = builder.build_commit()
711
680
        self.assertPathExists('dir')
712
 
        a_dir = controldir.ControlDir.open('dir')
 
681
        a_dir = bzrdir.BzrDir.open('dir')
713
682
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
714
683
        a_branch = a_dir.open_branch()
715
684
        builder_branch = builder.get_branch()
1002
971
            pass
1003
972
        test = unittest.FunctionTestCase(test_function)
1004
973
        test.run(result)
1005
 
        self.assertEqual(1, result.calls)
 
974
        self.assertEquals(1, result.calls)
1006
975
 
1007
976
    def test_startTests_only_once(self):
1008
977
        """With multiple tests startTests should still only be called once"""
1014
983
            unittest.FunctionTestCase(lambda: None),
1015
984
            unittest.FunctionTestCase(lambda: None)])
1016
985
        suite.run(result)
1017
 
        self.assertEqual(1, result.calls)
1018
 
        self.assertEqual(2, result.count)
 
986
        self.assertEquals(1, result.calls)
 
987
        self.assertEquals(2, result.count)
1019
988
 
1020
989
 
1021
990
class TestRunner(tests.TestCase):
1093
1062
                self.expectFailure("No absolute truth", self.assertTrue, True)
1094
1063
        runner = tests.TextTestRunner(stream=StringIO())
1095
1064
        result = self.run_test_runner(runner, Test("test_truth"))
1096
 
        self.assertContainsRe(runner.stream.getvalue(),
1097
 
            "=+\n"
1098
 
            "FAIL: \\S+\.test_truth\n"
1099
 
            "-+\n"
1100
 
            "(?:.*\n)*"
1101
 
            "\\s*(?:Text attachment: )?reason"
1102
 
            "(?:\n-+\n|: {{{)"
1103
 
            "No absolute truth"
1104
 
            "(?:\n-+\n|}}}\n)"
1105
 
            "(?:.*\n)*"
1106
 
            "-+\n"
1107
 
            "Ran 1 test in .*\n"
1108
 
            "\n"
1109
 
            "FAILED \\(failures=1\\)\n\\Z")
 
1065
        if testtools_version[:3] <= (0, 9, 11):
 
1066
            self.assertContainsRe(runner.stream.getvalue(),
 
1067
                "=+\n"
 
1068
                "FAIL: \\S+\.test_truth\n"
 
1069
                "-+\n"
 
1070
                "(?:.*\n)*"
 
1071
                "No absolute truth\n"
 
1072
                "(?:.*\n)*"
 
1073
                "-+\n"
 
1074
                "Ran 1 test in .*\n"
 
1075
                "\n"
 
1076
                "FAILED \\(failures=1\\)\n\\Z")
 
1077
        else:
 
1078
            self.assertContainsRe(runner.stream.getvalue(),
 
1079
                "=+\n"
 
1080
                "FAIL: \\S+\.test_truth\n"
 
1081
                "-+\n"
 
1082
                "Empty attachments:\n"
 
1083
                "  log\n"
 
1084
                "\n"
 
1085
                "reason: {{{No absolute truth}}}\n"
 
1086
                "-+\n"
 
1087
                "Ran 1 test in .*\n"
 
1088
                "\n"
 
1089
                "FAILED \\(failures=1\\)\n\\Z")
1110
1090
 
1111
1091
    def test_result_decorator(self):
1112
1092
        # decorate results
1161
1141
        class SkippedTest(tests.TestCase):
1162
1142
 
1163
1143
            def setUp(self):
1164
 
                super(SkippedTest, self).setUp()
 
1144
                tests.TestCase.setUp(self)
1165
1145
                calls.append('setUp')
1166
1146
                self.addCleanup(self.cleanup)
1167
1147
 
1271
1251
            lambda trace=False: "ascii")
1272
1252
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
1273
1253
            FailureWithUnicode("test_log_unicode"))
1274
 
        self.assertContainsRe(out.getvalue(),
1275
 
            "(?:Text attachment: )?log"
1276
 
            "(?:\n-+\n|: {{{)"
1277
 
            "\d+\.\d+  \\\\u2606"
1278
 
            "(?:\n-+\n|}}}\n)")
 
1254
        if testtools_version[:3] > (0, 9, 11):
 
1255
            self.assertContainsRe(out.getvalue(), "log: {{{\d+\.\d+  \\\\u2606}}}")
 
1256
        else:
 
1257
            self.assertContainsRe(out.getvalue(),
 
1258
                "Text attachment: log\n"
 
1259
                "-+\n"
 
1260
                "\d+\.\d+  \\\\u2606\n"
 
1261
                "-+\n")
1279
1262
 
1280
1263
 
1281
1264
class SampleTestCase(tests.TestCase):
1508
1491
        transport_server.start_server()
1509
1492
        self.addCleanup(transport_server.stop_server)
1510
1493
        t = transport.get_transport_from_url(transport_server.get_url())
1511
 
        controldir.ControlDir.create(t.base)
 
1494
        bzrdir.BzrDir.create(t.base)
1512
1495
        self.assertRaises(errors.BzrError,
1513
 
            controldir.ControlDir.open_from_transport, t)
 
1496
            bzrdir.BzrDir.open_from_transport, t)
1514
1497
        # But if we declare this as safe, we can open the bzrdir.
1515
1498
        self.permit_url(t.base)
1516
1499
        self._bzr_selftest_roots.append(t.base)
1517
 
        controldir.ControlDir.open_from_transport(t)
 
1500
        bzrdir.BzrDir.open_from_transport(t)
1518
1501
 
1519
1502
    def test_requireFeature_available(self):
1520
1503
        """self.requireFeature(available) is a no-op."""
1654
1637
        self.assertRaises(AssertionError,
1655
1638
            self.assertListRaises, _TestException, success_generator)
1656
1639
 
1657
 
    def _run_successful_test(self, test):
1658
 
        result = testtools.TestResult()
1659
 
        test.run(result)
1660
 
        self.assertTrue(result.wasSuccessful())
1661
 
        return result
1662
 
 
1663
1640
    def test_overrideAttr_without_value(self):
1664
1641
        self.test_attr = 'original' # Define a test attribute
1665
1642
        obj = self # Make 'obj' visible to the embedded test
1666
1643
        class Test(tests.TestCase):
1667
1644
 
1668
1645
            def setUp(self):
1669
 
                super(Test, self).setUp()
 
1646
                tests.TestCase.setUp(self)
1670
1647
                self.orig = self.overrideAttr(obj, 'test_attr')
1671
1648
 
1672
1649
            def test_value(self):
1675
1652
                obj.test_attr = 'modified'
1676
1653
                self.assertEqual('modified', obj.test_attr)
1677
1654
 
1678
 
        self._run_successful_test(Test('test_value'))
 
1655
        test = Test('test_value')
 
1656
        test.run(unittest.TestResult())
1679
1657
        self.assertEqual('original', obj.test_attr)
1680
1658
 
1681
1659
    def test_overrideAttr_with_value(self):
1684
1662
        class Test(tests.TestCase):
1685
1663
 
1686
1664
            def setUp(self):
1687
 
                super(Test, self).setUp()
 
1665
                tests.TestCase.setUp(self)
1688
1666
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
1689
1667
 
1690
1668
            def test_value(self):
1691
1669
                self.assertEqual('original', self.orig)
1692
1670
                self.assertEqual('modified', obj.test_attr)
1693
1671
 
1694
 
        self._run_successful_test(Test('test_value'))
 
1672
        test = Test('test_value')
 
1673
        test.run(unittest.TestResult())
1695
1674
        self.assertEqual('original', obj.test_attr)
1696
1675
 
1697
 
    def test_overrideAttr_with_no_existing_value_and_value(self):
1698
 
        # Do not define the test_attribute
1699
 
        obj = self # Make 'obj' visible to the embedded test
1700
 
        class Test(tests.TestCase):
1701
 
 
1702
 
            def setUp(self):
1703
 
                tests.TestCase.setUp(self)
1704
 
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
1705
 
 
1706
 
            def test_value(self):
1707
 
                self.assertEqual(tests._unitialized_attr, self.orig)
1708
 
                self.assertEqual('modified', obj.test_attr)
1709
 
 
1710
 
        self._run_successful_test(Test('test_value'))
1711
 
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
1712
 
 
1713
 
    def test_overrideAttr_with_no_existing_value_and_no_value(self):
1714
 
        # Do not define the test_attribute
1715
 
        obj = self # Make 'obj' visible to the embedded test
1716
 
        class Test(tests.TestCase):
1717
 
 
1718
 
            def setUp(self):
1719
 
                tests.TestCase.setUp(self)
1720
 
                self.orig = self.overrideAttr(obj, 'test_attr')
1721
 
 
1722
 
            def test_value(self):
1723
 
                self.assertEqual(tests._unitialized_attr, self.orig)
1724
 
                self.assertRaises(AttributeError, getattr, obj, 'test_attr')
1725
 
 
1726
 
        self._run_successful_test(Test('test_value'))
1727
 
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
1728
 
 
1729
1676
    def test_recordCalls(self):
1730
1677
        from bzrlib.tests import test_selftest
1731
1678
        calls = self.recordCalls(
1732
1679
            test_selftest, '_add_numbers')
1733
1680
        self.assertEqual(test_selftest._add_numbers(2, 10),
1734
1681
            12)
1735
 
        self.assertEqual(calls, [((2, 10), {})])
 
1682
        self.assertEquals(calls, [((2, 10), {})])
1736
1683
 
1737
1684
 
1738
1685
def _add_numbers(a, b):
1796
1743
        result = self._run_test('test_fail')
1797
1744
        self.assertEqual(1, len(result.failures))
1798
1745
        result_content = result.failures[0][1]
1799
 
        self.assertContainsRe(result_content,
1800
 
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1746
        if testtools_version < (0, 9, 12):
 
1747
            self.assertContainsRe(result_content, 'Text attachment: log')
1801
1748
        self.assertContainsRe(result_content, 'this was a failing test')
1802
1749
 
1803
1750
    def test_error_has_log(self):
1804
1751
        result = self._run_test('test_error')
1805
1752
        self.assertEqual(1, len(result.errors))
1806
1753
        result_content = result.errors[0][1]
1807
 
        self.assertContainsRe(result_content,
1808
 
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1754
        if testtools_version < (0, 9, 12):
 
1755
            self.assertContainsRe(result_content, 'Text attachment: log')
1809
1756
        self.assertContainsRe(result_content, 'this test errored')
1810
1757
 
1811
1758
    def test_skip_has_no_log(self):
1830
1777
        result = self._run_test('test_xfail')
1831
1778
        self.assertEqual(1, len(result.expectedFailures))
1832
1779
        result_content = result.expectedFailures[0][1]
1833
 
        self.assertNotContainsRe(result_content,
1834
 
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1780
        self.assertNotContainsRe(result_content, 'Text attachment: log')
1835
1781
        self.assertNotContainsRe(result_content, 'test with expected failure')
1836
1782
 
1837
1783
    def test_unexpected_success_has_log(self):
1912
1858
        self.assertIsInstance(2, int)
1913
1859
        self.assertIsInstance(u'', basestring)
1914
1860
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1915
 
        self.assertEqual(str(e),
 
1861
        self.assertEquals(str(e),
1916
1862
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
1917
1863
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1918
1864
        e = self.assertRaises(AssertionError,
1919
1865
            self.assertIsInstance, None, int, "it's just not")
1920
 
        self.assertEqual(str(e),
 
1866
        self.assertEquals(str(e),
1921
1867
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
1922
1868
            ": it's just not")
1923
1869
 
1928
1874
    def test_assertEqualDiff(self):
1929
1875
        e = self.assertRaises(AssertionError,
1930
1876
                              self.assertEqualDiff, '', '\n')
1931
 
        self.assertEqual(str(e),
 
1877
        self.assertEquals(str(e),
1932
1878
                          # Don't blink ! The '+' applies to the second string
1933
1879
                          'first string is missing a final newline.\n+ \n')
1934
1880
        e = self.assertRaises(AssertionError,
1935
1881
                              self.assertEqualDiff, '\n', '')
1936
 
        self.assertEqual(str(e),
 
1882
        self.assertEquals(str(e),
1937
1883
                          # Don't blink ! The '-' applies to the second string
1938
1884
                          'second string is missing a final newline.\n- \n')
1939
1885
 
1996
1942
            warnings.warn("this is your last warning")
1997
1943
            return a + b
1998
1944
        wlist, result = self.callCatchWarnings(meth, 1, 2)
1999
 
        self.assertEqual(3, result)
 
1945
        self.assertEquals(3, result)
2000
1946
        # would like just to compare them, but UserWarning doesn't implement
2001
1947
        # eq well
2002
1948
        w0, = wlist
2003
1949
        self.assertIsInstance(w0, UserWarning)
2004
 
        self.assertEqual("this is your last warning", str(w0))
 
1950
        self.assertEquals("this is your last warning", str(w0))
2005
1951
 
2006
1952
 
2007
1953
class TestConvenienceMakers(tests.TestCaseWithTransport):
2010
1956
    def test_make_branch_and_tree_with_format(self):
2011
1957
        # we should be able to supply a format to make_branch_and_tree
2012
1958
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
2013
 
        self.assertIsInstance(bzrlib.controldir.ControlDir.open('a')._format,
 
1959
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
2014
1960
                              bzrlib.bzrdir.BzrDirMetaFormat1)
2015
1961
 
2016
1962
    def test_make_branch_and_memory_tree(self):
2028
1974
        tree = self.make_branch_and_tree('t1')
2029
1975
        base = tree.bzrdir.root_transport.base
2030
1976
        self.assertStartsWith(base, 'file://')
2031
 
        self.assertEqual(tree.bzrdir.root_transport,
 
1977
        self.assertEquals(tree.bzrdir.root_transport,
2032
1978
                tree.branch.bzrdir.root_transport)
2033
 
        self.assertEqual(tree.bzrdir.root_transport,
 
1979
        self.assertEquals(tree.bzrdir.root_transport,
2034
1980
                tree.branch.repository.bzrdir.root_transport)
2035
1981
 
2036
1982
 
2246
2192
        self.assertNotContainsRe(content, 'test with expected failure')
2247
2193
        self.assertEqual(1, len(result.expectedFailures))
2248
2194
        result_content = result.expectedFailures[0][1]
2249
 
        self.assertNotContainsRe(result_content,
2250
 
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
2195
        self.assertNotContainsRe(result_content, 'Text attachment: log')
2251
2196
        self.assertNotContainsRe(result_content, 'test with expected failure')
2252
2197
 
2253
2198
    def test_unexpected_success_has_log(self):
2300
2245
        self.assertEqual(['rocks'], self.argv)
2301
2246
        self.assertEqual(34, self.retcode)
2302
2247
        self.assertEqual('It sure does!\n', out)
2303
 
        self.assertEqual(out, self.out)
 
2248
        self.assertEquals(out, self.out)
2304
2249
        self.assertEqual('', err)
2305
 
        self.assertEqual(err, self.err)
 
2250
        self.assertEquals(err, self.err)
2306
2251
 
2307
2252
    def test_run_bzr_error_regexes(self):
2308
2253
        self.out = ''
2448
2393
    """Base class for tests testing how we might run bzr."""
2449
2394
 
2450
2395
    def setUp(self):
2451
 
        super(TestWithFakedStartBzrSubprocess, self).setUp()
 
2396
        tests.TestCaseWithTransport.setUp(self)
2452
2397
        self.subprocess_calls = []
2453
2398
 
2454
2399
    def start_bzr_subprocess(self, process_args, env_changes=None,
2668
2613
class TestSelftestFiltering(tests.TestCase):
2669
2614
 
2670
2615
    def setUp(self):
2671
 
        super(TestSelftestFiltering, self).setUp()
 
2616
        tests.TestCase.setUp(self)
2672
2617
        self.suite = TestUtil.TestSuite()
2673
2618
        self.loader = TestUtil.TestLoader()
2674
2619
        self.suite.addTest(self.loader.loadTestsFromModule(
2847
2792
            self.run_bzr, ['assert-fail'])
2848
2793
        # make sure we got the real thing, not an error from somewhere else in
2849
2794
        # the test framework
2850
 
        self.assertEqual('always fails', str(e))
 
2795
        self.assertEquals('always fails', str(e))
2851
2796
        # check that there's no traceback in the test log
2852
2797
        self.assertNotContainsRe(self.get_log(), r'Traceback')
2853
2798
 
2902
2847
    def test_load_tests_from_module_name_smoke_test(self):
2903
2848
        loader = TestUtil.TestLoader()
2904
2849
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2905
 
        self.assertEqual(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2850
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2906
2851
                          _test_ids(suite))
2907
2852
 
2908
2853
    def test_load_tests_from_module_name_with_bogus_module_name(self):
2937
2882
 
2938
2883
    def test_empty_list(self):
2939
2884
        id_list = self._create_id_list([])
2940
 
        self.assertEqual({}, id_list.tests)
2941
 
        self.assertEqual({}, id_list.modules)
 
2885
        self.assertEquals({}, id_list.tests)
 
2886
        self.assertEquals({}, id_list.modules)
2942
2887
 
2943
2888
    def test_valid_list(self):
2944
2889
        id_list = self._create_id_list(
2971
2916
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2972
2917
                     'bogus']
2973
2918
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2974
 
        self.assertEqual(['bogus'], not_found)
2975
 
        self.assertEqual([], duplicates)
 
2919
        self.assertEquals(['bogus'], not_found)
 
2920
        self.assertEquals([], duplicates)
2976
2921
 
2977
2922
    def test_suite_matches_id_list_with_duplicates(self):
2978
2923
        loader = TestUtil.TestLoader()
2985
2930
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2986
2931
        not_found, duplicates = tests.suite_matches_id_list(
2987
2932
            dupes, test_list)
2988
 
        self.assertEqual([], not_found)
2989
 
        self.assertEqual(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2933
        self.assertEquals([], not_found)
 
2934
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2990
2935
                          duplicates)
2991
2936
 
2992
2937
 
3065
3010
        suite = tests.test_suite(test_list,
3066
3011
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
3067
3012
        # test_test_suite_list_and_start is not included 
3068
 
        self.assertEqual(test_list, _test_ids(suite))
 
3013
        self.assertEquals(test_list, _test_ids(suite))
3069
3014
 
3070
3015
 
3071
3016
class TestLoadTestIdList(tests.TestCaseInTempDir):
3084
3029
        self._create_test_list_file(test_list_fname,
3085
3030
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
3086
3031
        tlist = tests.load_test_id_list(test_list_fname)
3087
 
        self.assertEqual(2, len(tlist))
3088
 
        self.assertEqual('mod1.cl1.meth1', tlist[0])
3089
 
        self.assertEqual('mod2.cl2.meth2', tlist[1])
 
3032
        self.assertEquals(2, len(tlist))
 
3033
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
3034
        self.assertEquals('mod2.cl2.meth2', tlist[1])
3090
3035
 
3091
3036
    def test_load_dirty_file(self):
3092
3037
        test_list_fname = 'test.list'
3094
3039
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
3095
3040
                                    'bar baz\n')
3096
3041
        tlist = tests.load_test_id_list(test_list_fname)
3097
 
        self.assertEqual(4, len(tlist))
3098
 
        self.assertEqual('mod1.cl1.meth1', tlist[0])
3099
 
        self.assertEqual('', tlist[1])
3100
 
        self.assertEqual('mod2.cl2.meth2', tlist[2])
3101
 
        self.assertEqual('bar baz', tlist[3])
 
3042
        self.assertEquals(4, len(tlist))
 
3043
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
3044
        self.assertEquals('', tlist[1])
 
3045
        self.assertEquals('mod2.cl2.meth2', tlist[2])
 
3046
        self.assertEquals('bar baz', tlist[3])
3102
3047
 
3103
3048
 
3104
3049
class TestFilteredByModuleTestLoader(tests.TestCase):
3112
3057
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
3113
3058
        loader = self._create_loader(test_list)
3114
3059
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
3115
 
        self.assertEqual(test_list, _test_ids(suite))
 
3060
        self.assertEquals(test_list, _test_ids(suite))
3116
3061
 
3117
3062
    def test_exclude_tests(self):
3118
3063
        test_list = ['bogus']
3119
3064
        loader = self._create_loader(test_list)
3120
3065
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
3121
 
        self.assertEqual([], _test_ids(suite))
 
3066
        self.assertEquals([], _test_ids(suite))
3122
3067
 
3123
3068
 
3124
3069
class TestFilteredByNameStartTestLoader(tests.TestCase):
3134
3079
        loader = self._create_loader('bzrlib.tests.test_samp')
3135
3080
 
3136
3081
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
3137
 
        self.assertEqual(test_list, _test_ids(suite))
 
3082
        self.assertEquals(test_list, _test_ids(suite))
3138
3083
 
3139
3084
    def test_load_tests_inside_module(self):
3140
3085
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
3141
3086
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
3142
3087
 
3143
3088
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
3144
 
        self.assertEqual(test_list, _test_ids(suite))
 
3089
        self.assertEquals(test_list, _test_ids(suite))
3145
3090
 
3146
3091
    def test_exclude_tests(self):
3147
3092
        test_list = ['bogus']
3148
3093
        loader = self._create_loader('bogus')
3149
3094
 
3150
3095
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
3151
 
        self.assertEqual([], _test_ids(suite))
 
3096
        self.assertEquals([], _test_ids(suite))
3152
3097
 
3153
3098
 
3154
3099
class TestTestPrefixRegistry(tests.TestCase):
3160
3105
    def test_register_new_prefix(self):
3161
3106
        tpr = self._get_registry()
3162
3107
        tpr.register('foo', 'fff.ooo.ooo')
3163
 
        self.assertEqual('fff.ooo.ooo', tpr.get('foo'))
 
3108
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
3164
3109
 
3165
3110
    def test_register_existing_prefix(self):
3166
3111
        tpr = self._get_registry()
3167
3112
        tpr.register('bar', 'bbb.aaa.rrr')
3168
3113
        tpr.register('bar', 'bBB.aAA.rRR')
3169
 
        self.assertEqual('bbb.aaa.rrr', tpr.get('bar'))
 
3114
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
3170
3115
        self.assertThat(self.get_log(),
3171
3116
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR",
3172
3117
                           doctest.ELLIPSIS))
3178
3123
    def test_resolve_prefix(self):
3179
3124
        tpr = self._get_registry()
3180
3125
        tpr.register('bar', 'bb.aa.rr')
3181
 
        self.assertEqual('bb.aa.rr', tpr.resolve_alias('bar'))
 
3126
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
3182
3127
 
3183
3128
    def test_resolve_unknown_alias(self):
3184
3129
        tpr = self._get_registry()
3187
3132
 
3188
3133
    def test_predefined_prefixes(self):
3189
3134
        tpr = tests.test_prefix_alias_registry
3190
 
        self.assertEqual('bzrlib', tpr.resolve_alias('bzrlib'))
3191
 
        self.assertEqual('bzrlib.doc', tpr.resolve_alias('bd'))
3192
 
        self.assertEqual('bzrlib.utils', tpr.resolve_alias('bu'))
3193
 
        self.assertEqual('bzrlib.tests', tpr.resolve_alias('bt'))
3194
 
        self.assertEqual('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
3195
 
        self.assertEqual('bzrlib.plugins', tpr.resolve_alias('bp'))
 
3135
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
 
3136
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
 
3137
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
 
3138
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
 
3139
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
 
3140
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
3196
3141
 
3197
3142
 
3198
3143
class TestThreadLeakDetection(tests.TestCase):
3369
3314
        self.assertLength(1, calls)
3370
3315
 
3371
3316
 
3372
 
class _Selftest(object):
3373
 
    """Mixin for tests needing full selftest output"""
3374
 
 
3375
 
    def _inject_stream_into_subunit(self, stream):
3376
 
        """To be overridden by subclasses that run tests out of process"""
3377
 
 
3378
 
    def _run_selftest(self, **kwargs):
3379
 
        sio = StringIO()
3380
 
        self._inject_stream_into_subunit(sio)
3381
 
        tests.selftest(stream=sio, stop_on_failure=False, **kwargs)
3382
 
        return sio.getvalue()
3383
 
 
3384
 
 
3385
 
class _ForkedSelftest(_Selftest):
3386
 
    """Mixin for tests needing full selftest output with forked children"""
3387
 
 
3388
 
    _test_needs_features = [features.subunit]
3389
 
 
3390
 
    def _inject_stream_into_subunit(self, stream):
3391
 
        """Monkey-patch subunit so the extra output goes to stream not stdout
3392
 
 
3393
 
        Some APIs need rewriting so this kind of bogus hackery can be replaced
3394
 
        by passing the stream param from run_tests down into ProtocolTestCase.
3395
 
        """
3396
 
        from subunit import ProtocolTestCase
3397
 
        _original_init = ProtocolTestCase.__init__
3398
 
        def _init_with_passthrough(self, *args, **kwargs):
3399
 
            _original_init(self, *args, **kwargs)
3400
 
            self._passthrough = stream
3401
 
        self.overrideAttr(ProtocolTestCase, "__init__", _init_with_passthrough)
3402
 
 
3403
 
    def _run_selftest(self, **kwargs):
3404
 
        # GZ 2011-05-26: Add a PosixSystem feature so this check can go away
3405
 
        if getattr(os, "fork", None) is None:
3406
 
            raise tests.TestNotApplicable("Platform doesn't support forking")
3407
 
        # Make sure the fork code is actually invoked by claiming two cores
3408
 
        self.overrideAttr(osutils, "local_concurrency", lambda: 2)
3409
 
        kwargs.setdefault("suite_decorators", []).append(tests.fork_decorator)
3410
 
        return super(_ForkedSelftest, self)._run_selftest(**kwargs)
3411
 
 
3412
 
 
3413
 
class TestParallelFork(_ForkedSelftest, tests.TestCase):
3414
 
    """Check operation of --parallel=fork selftest option"""
3415
 
 
3416
 
    def test_error_in_child_during_fork(self):
3417
 
        """Error in a forked child during test setup should get reported"""
3418
 
        class Test(tests.TestCase):
3419
 
            def testMethod(self):
3420
 
                pass
3421
 
        # We don't care what, just break something that a child will run
3422
 
        self.overrideAttr(tests, "workaround_zealous_crypto_random", None)
3423
 
        out = self._run_selftest(test_suite_factory=Test)
3424
 
        # Lines from the tracebacks of the two child processes may be mixed
3425
 
        # together due to the way subunit parses and forwards the streams,
3426
 
        # so permit extra lines between each part of the error output.
3427
 
        self.assertContainsRe(out,
3428
 
            "Traceback.*:\n"
3429
 
            "(?:.*\n)*"
3430
 
            ".+ in fork_for_tests\n"
3431
 
            "(?:.*\n)*"
3432
 
            "\s*workaround_zealous_crypto_random\(\)\n"
3433
 
            "(?:.*\n)*"
3434
 
            "TypeError:")
3435
 
 
3436
 
 
3437
 
class TestUncollectedWarnings(_Selftest, tests.TestCase):
3438
 
    """Check a test case still alive after being run emits a warning"""
3439
 
 
3440
 
    class Test(tests.TestCase):
3441
 
        def test_pass(self):
3442
 
            pass
3443
 
        def test_self_ref(self):
3444
 
            self.also_self = self.test_self_ref
3445
 
        def test_skip(self):
3446
 
            self.skip("Don't need")
3447
 
 
3448
 
    def _get_suite(self):
3449
 
        return TestUtil.TestSuite([
3450
 
            self.Test("test_pass"),
3451
 
            self.Test("test_self_ref"),
3452
 
            self.Test("test_skip"),
3453
 
            ])
3454
 
 
3455
 
    def _run_selftest_with_suite(self, **kwargs):
3456
 
        old_flags = tests.selftest_debug_flags
3457
 
        tests.selftest_debug_flags = old_flags.union(["uncollected_cases"])
3458
 
        gc_on = gc.isenabled()
3459
 
        if gc_on:
3460
 
            gc.disable()
3461
 
        try:
3462
 
            output = self._run_selftest(test_suite_factory=self._get_suite,
3463
 
                **kwargs)
3464
 
        finally:
3465
 
            if gc_on:
3466
 
                gc.enable()
3467
 
            tests.selftest_debug_flags = old_flags
3468
 
        self.assertNotContainsRe(output, "Uncollected test case.*test_pass")
3469
 
        self.assertContainsRe(output, "Uncollected test case.*test_self_ref")
3470
 
        return output
3471
 
 
3472
 
    def test_testsuite(self):
3473
 
        self._run_selftest_with_suite()
3474
 
 
3475
 
    def test_pattern(self):
3476
 
        out = self._run_selftest_with_suite(pattern="test_(?:pass|self_ref)$")
3477
 
        self.assertNotContainsRe(out, "test_skip")
3478
 
 
3479
 
    def test_exclude_pattern(self):
3480
 
        out = self._run_selftest_with_suite(exclude_pattern="test_skip$")
3481
 
        self.assertNotContainsRe(out, "test_skip")
3482
 
 
3483
 
    def test_random_seed(self):
3484
 
        self._run_selftest_with_suite(random_seed="now")
3485
 
 
3486
 
    def test_matching_tests_first(self):
3487
 
        self._run_selftest_with_suite(matching_tests_first=True,
3488
 
            pattern="test_self_ref$")
3489
 
 
3490
 
    def test_starting_with_and_exclude(self):
3491
 
        out = self._run_selftest_with_suite(starting_with=["bt."],
3492
 
            exclude_pattern="test_skip$")
3493
 
        self.assertNotContainsRe(out, "test_skip")
3494
 
 
3495
 
    def test_additonal_decorator(self):
3496
 
        out = self._run_selftest_with_suite(
3497
 
            suite_decorators=[tests.TestDecorator])
3498
 
 
3499
 
 
3500
 
class TestUncollectedWarningsSubunit(TestUncollectedWarnings):
3501
 
    """Check warnings from tests staying alive are emitted with subunit"""
3502
 
 
3503
 
    _test_needs_features = [features.subunit]
3504
 
 
3505
 
    def _run_selftest_with_suite(self, **kwargs):
3506
 
        return TestUncollectedWarnings._run_selftest_with_suite(self,
3507
 
            runner_class=tests.SubUnitBzrRunner, **kwargs)
3508
 
 
3509
 
 
3510
 
class TestUncollectedWarningsForked(_ForkedSelftest, TestUncollectedWarnings):
3511
 
    """Check warnings from tests staying alive are emitted when forking"""
3512
 
 
3513
 
 
3514
3317
class TestEnvironHandling(tests.TestCase):
3515
3318
 
3516
3319
    def test_overrideEnv_None_called_twice_doesnt_leak(self):
3521
3324
            def test_me(self):
3522
3325
                # The first call save the 42 value
3523
3326
                self.overrideEnv('MYVAR', None)
3524
 
                self.assertEqual(None, os.environ.get('MYVAR'))
 
3327
                self.assertEquals(None, os.environ.get('MYVAR'))
3525
3328
                # Make sure we can call it twice
3526
3329
                self.overrideEnv('MYVAR', None)
3527
 
                self.assertEqual(None, os.environ.get('MYVAR'))
 
3330
                self.assertEquals(None, os.environ.get('MYVAR'))
3528
3331
        output = StringIO()
3529
3332
        result = tests.TextTestResult(output, 0, 1)
3530
3333
        Test('test_me').run(result)
3531
3334
        if not result.wasStrictlySuccessful():
3532
3335
            self.fail(output.getvalue())
3533
3336
        # We get our value back
3534
 
        self.assertEqual('42', os.environ.get('MYVAR'))
 
3337
        self.assertEquals('42', os.environ.get('MYVAR'))
3535
3338
 
3536
3339
 
3537
3340
class TestIsolatedEnv(tests.TestCase):
3553
3356
        # Make sure we know the definition of BZR_HOME: not part of os.environ
3554
3357
        # for tests.TestCase.
3555
3358
        self.assertTrue('BZR_HOME' in tests.isolated_environ)
3556
 
        self.assertEqual(None, tests.isolated_environ['BZR_HOME'])
 
3359
        self.assertEquals(None, tests.isolated_environ['BZR_HOME'])
3557
3360
        # Being part of isolated_environ, BZR_HOME should not appear here
3558
3361
        self.assertFalse('BZR_HOME' in os.environ)
3559
3362
        # Make sure we know the definition of LINES: part of os.environ for
3560
3363
        # tests.TestCase
3561
3364
        self.assertTrue('LINES' in tests.isolated_environ)
3562
 
        self.assertEqual('25', tests.isolated_environ['LINES'])
3563
 
        self.assertEqual('25', os.environ['LINES'])
 
3365
        self.assertEquals('25', tests.isolated_environ['LINES'])
 
3366
        self.assertEquals('25', os.environ['LINES'])
3564
3367
 
3565
3368
    def test_injecting_unknown_variable(self):
3566
3369
        # BZR_HOME is known to be absent from os.environ
3567
3370
        test = self.ScratchMonkey('test_me')
3568
3371
        tests.override_os_environ(test, {'BZR_HOME': 'foo'})
3569
 
        self.assertEqual('foo', os.environ['BZR_HOME'])
 
3372
        self.assertEquals('foo', os.environ['BZR_HOME'])
3570
3373
        tests.restore_os_environ(test)
3571
3374
        self.assertFalse('BZR_HOME' in os.environ)
3572
3375
 
3574
3377
        test = self.ScratchMonkey('test_me')
3575
3378
        # LINES is known to be present in os.environ
3576
3379
        tests.override_os_environ(test, {'LINES': '42'})
3577
 
        self.assertEqual('42', os.environ['LINES'])
 
3380
        self.assertEquals('42', os.environ['LINES'])
3578
3381
        tests.restore_os_environ(test)
3579
 
        self.assertEqual('25', os.environ['LINES'])
 
3382
        self.assertEquals('25', os.environ['LINES'])
3580
3383
 
3581
3384
    def test_deleting_variable(self):
3582
3385
        test = self.ScratchMonkey('test_me')
3584
3387
        tests.override_os_environ(test, {'LINES': None})
3585
3388
        self.assertTrue('LINES' not in os.environ)
3586
3389
        tests.restore_os_environ(test)
3587
 
        self.assertEqual('25', os.environ['LINES'])
 
3390
        self.assertEquals('25', os.environ['LINES'])
3588
3391
 
3589
3392
 
3590
3393
class TestDocTestSuiteIsolation(tests.TestCase):
3677
3480
        # test at the command level without loading the whole test suite
3678
3481
        out, err = self.run_bzr(('selftest', '--list') + selftest_args)
3679
3482
        actual = out.splitlines()
3680
 
        self.assertEqual(expected, actual)
 
3483
        self.assertEquals(expected, actual)
3681
3484
 
3682
3485
    def test_full_list(self):
3683
3486
        self.assertTestList(['a', 'b', 'c'])
3718
3521
        test.run(result)
3719
3522
        self.assertTrue(hasattr(test, '_counters'))
3720
3523
        self.assertTrue(test._counters.has_key('myhook'))
3721
 
        self.assertEqual(expected_calls, test._counters['myhook'])
 
3524
        self.assertEquals(expected_calls, test._counters['myhook'])
3722
3525
 
3723
3526
    def test_no_hook(self):
3724
3527
        self.assertHookCalls(0, 'no_hook')