/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Andrew Bennetts
  • Date: 2010-02-12 04:33:05 UTC
  • mfrom: (5031 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5032.
  • Revision ID: andrew.bennetts@canonical.com-20100212043305-ujdbsdoviql2t7i3
MergeĀ lp:bzr

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
from doctest import ELLIPSIS
20
21
import os
21
22
import signal
22
23
import sys
24
25
import unittest
25
26
import warnings
26
27
 
 
28
from testtools import MultiTestResult
 
29
from testtools.content_type import ContentType
 
30
from testtools.matchers import (
 
31
    DocTestMatches,
 
32
    Equals,
 
33
    )
 
34
import testtools.tests.helpers
 
35
 
27
36
import bzrlib
28
37
from bzrlib import (
29
38
    branchbuilder,
52
61
    deprecated_method,
53
62
    )
54
63
from bzrlib.tests import (
55
 
    SubUnitFeature,
 
64
    features,
 
65
    stub_sftp,
56
66
    test_lsprof,
 
67
    test_server,
57
68
    test_sftp_transport,
58
69
    TestUtil,
59
70
    )
60
71
from bzrlib.trace import note
61
 
from bzrlib.transport.memory import MemoryServer, MemoryTransport
 
72
from bzrlib.transport import memory
62
73
from bzrlib.version import _get_bzr_source_tree
63
74
 
64
75
 
78
89
                          TestUtil._load_module_by_name,
79
90
                          'bzrlib.no-name-yet')
80
91
 
 
92
 
81
93
class MetaTestLog(tests.TestCase):
82
94
 
83
95
    def test_logging(self):
84
96
        """Test logs are captured when a test fails."""
85
97
        self.log('a test message')
86
 
        self._log_file.flush()
87
 
        self.assertContainsRe(self._get_log(keep_log_file=True),
88
 
                              'a test message\n')
 
98
        details = self.getDetails()
 
99
        log = details['log']
 
100
        self.assertThat(log.content_type, Equals(ContentType(
 
101
            "text", "plain", {"charset": "utf8"})))
 
102
        self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
 
103
        self.assertThat(self.get_log(),
 
104
            DocTestMatches(u"...a test message\n", ELLIPSIS))
89
105
 
90
106
 
91
107
class TestUnicodeFilename(tests.TestCase):
490
506
        self.assertEqualStat(real, fake)
491
507
 
492
508
    def test_assertEqualStat_notequal(self):
493
 
        self.build_tree(["foo", "bar"])
 
509
        self.build_tree(["foo", "longname"])
494
510
        self.assertRaises(AssertionError, self.assertEqualStat,
495
 
            os.lstat("foo"), os.lstat("bar"))
 
511
            os.lstat("foo"), os.lstat("longname"))
496
512
 
497
513
 
498
514
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
516
532
        cwd = osutils.getcwd()
517
533
        self.assertIsSameRealPath(self.test_dir, cwd)
518
534
 
 
535
    def test_BZR_HOME_and_HOME_are_bytestrings(self):
 
536
        """The $BZR_HOME and $HOME environment variables should not be unicode.
 
537
 
 
538
        See https://bugs.launchpad.net/bzr/+bug/464174
 
539
        """
 
540
        self.assertIsInstance(os.environ['BZR_HOME'], str)
 
541
        self.assertIsInstance(os.environ['HOME'], str)
 
542
 
519
543
    def test_make_branch_and_memory_tree(self):
520
544
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
521
545
 
599
623
 
600
624
    def test_get_readonly_url_none(self):
601
625
        from bzrlib.transport import get_transport
602
 
        from bzrlib.transport.memory import MemoryServer
603
626
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
604
 
        self.vfs_transport_factory = MemoryServer
 
627
        self.vfs_transport_factory = memory.MemoryServer
605
628
        self.transport_readonly_server = None
606
629
        # calling get_readonly_transport() constructs a decorator on the url
607
630
        # for the server
616
639
    def test_get_readonly_url_http(self):
617
640
        from bzrlib.tests.http_server import HttpServer
618
641
        from bzrlib.transport import get_transport
619
 
        from bzrlib.transport.local import LocalURLServer
620
642
        from bzrlib.transport.http import HttpTransportBase
621
 
        self.transport_server = LocalURLServer
 
643
        self.transport_server = test_server.LocalURLServer
622
644
        self.transport_readonly_server = HttpServer
623
645
        # calling get_readonly_transport() gives us a HTTP server instance.
624
646
        url = self.get_readonly_url()
655
677
 
656
678
    def setUp(self):
657
679
        super(TestTestCaseTransports, self).setUp()
658
 
        self.vfs_transport_factory = MemoryServer
 
680
        self.vfs_transport_factory = memory.MemoryServer
659
681
 
660
682
    def test_make_bzrdir_preserves_transport(self):
661
683
        t = self.get_transport()
662
684
        result_bzrdir = self.make_bzrdir('subdir')
663
685
        self.assertIsInstance(result_bzrdir.transport,
664
 
                              MemoryTransport)
 
686
                              memory.MemoryTransport)
665
687
        # should not be on disk, should only be in memory
666
688
        self.failIfExists('subdir')
667
689
 
679
701
 
680
702
    def test_profiles_tests(self):
681
703
        self.requireFeature(test_lsprof.LSProfFeature)
682
 
        terminal = unittest.TestResult()
 
704
        terminal = testtools.tests.helpers.ExtendedTestResult()
683
705
        result = tests.ProfileResult(terminal)
684
706
        class Sample(tests.TestCase):
685
707
            def a(self):
687
709
            def sample_function(self):
688
710
                pass
689
711
        test = Sample("a")
690
 
        test.attrs_to_keep = test.attrs_to_keep + ('_benchcalls',)
691
712
        test.run(result)
692
 
        self.assertLength(1, test._benchcalls)
 
713
        case = terminal._events[0][1]
 
714
        self.assertLength(1, case._benchcalls)
693
715
        # We must be able to unpack it as the test reporting code wants
694
 
        (_, _, _), stats = test._benchcalls[0]
 
716
        (_, _, _), stats = case._benchcalls[0]
695
717
        self.assertTrue(callable(stats.pprint))
696
718
 
697
719
 
702
724
                descriptions=0,
703
725
                verbosity=1,
704
726
                )
705
 
        test_case.run(result)
706
 
        timed_string = result._testTimeString(test_case)
 
727
        capture = testtools.tests.helpers.ExtendedTestResult()
 
728
        test_case.run(MultiTestResult(result, capture))
 
729
        run_case = capture._events[0][1]
 
730
        timed_string = result._testTimeString(run_case)
707
731
        self.assertContainsRe(timed_string, expected_re)
708
732
 
709
733
    def test_test_reporting(self):
730
754
    def _patch_get_bzr_source_tree(self):
731
755
        # Reading from the actual source tree breaks isolation, but we don't
732
756
        # want to assume that thats *all* that would happen.
733
 
        def _get_bzr_source_tree():
734
 
            return None
735
 
        orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
736
 
        bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
737
 
        def restore():
738
 
            bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
739
 
        self.addCleanup(restore)
 
757
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', lambda: None)
740
758
 
741
759
    def test_assigned_benchmark_file_stores_date(self):
742
760
        self._patch_get_bzr_source_tree()
824
842
            def stopTestRun(self): pass
825
843
            def startTests(self): pass
826
844
            def report_test_start(self, test): pass
827
 
            def report_known_failure(self, test, err):
828
 
                self._call = test, err
 
845
            def report_known_failure(self, test, err=None, details=None):
 
846
                self._call = test, 'known failure'
829
847
        result = InstrumentedTestResult(None, None, None, None)
830
848
        class Test(tests.TestCase):
831
849
            def test_function(self):
834
852
        test.run(result)
835
853
        # it should invoke 'report_known_failure'.
836
854
        self.assertEqual(2, len(result._call))
837
 
        self.assertEqual(test, result._call[0])
838
 
        self.assertEqual(tests.KnownFailure, result._call[1][0])
839
 
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
 
855
        self.assertEqual(test.id(), result._call[0].id())
 
856
        self.assertEqual('known failure', result._call[1])
840
857
        # we dont introspec the traceback, if the rest is ok, it would be
841
858
        # exceptional for it not to be.
842
859
        # it should update the known_failure_count on the object.
914
931
        result.report_unsupported(test, feature)
915
932
        output = result_stream.getvalue()[prefix:]
916
933
        lines = output.splitlines()
917
 
        self.assertEqual(lines, ['NODEP        0ms',
918
 
                                 "    The feature 'Feature' is not available."])
 
934
        # We don't check for the final '0ms' since it may fail on slow hosts
 
935
        self.assertStartsWith(lines[0], 'NODEP')
 
936
        self.assertEqual(lines[1],
 
937
                         "    The feature 'Feature' is not available.")
919
938
 
920
939
    def test_unavailable_exception(self):
921
940
        """An UnavailableFeature being raised should invoke addNotSupported."""
934
953
        test.run(result)
935
954
        # it should invoke 'addNotSupported'.
936
955
        self.assertEqual(2, len(result._call))
937
 
        self.assertEqual(test, result._call[0])
 
956
        self.assertEqual(test.id(), result._call[0].id())
938
957
        self.assertEqual(feature, result._call[1])
939
958
        # and not count as an error
940
959
        self.assertEqual(0, result.error_count)
1018
1037
        # the final output when real failures occur.
1019
1038
        class Test(tests.TestCase):
1020
1039
            def known_failure_test(self):
1021
 
                raise tests.KnownFailure('failed')
 
1040
                self.expectFailure('failed', self.assertTrue, False)
1022
1041
        test = unittest.TestSuite()
1023
1042
        test.addTest(Test("known_failure_test"))
1024
1043
        def failing_test():
1025
 
            raise AssertionError('foo')
 
1044
            self.fail('foo')
1026
1045
        test.addTest(unittest.FunctionTestCase(failing_test))
1027
1046
        stream = StringIO()
1028
1047
        runner = tests.TextTestRunner(stream=stream)
1029
1048
        result = self.run_test_runner(runner, test)
1030
1049
        lines = stream.getvalue().splitlines()
1031
1050
        self.assertContainsRe(stream.getvalue(),
1032
 
            '(?sm)^testing.*$'
 
1051
            '(?sm)^bzr selftest.*$'
1033
1052
            '.*'
1034
1053
            '^======================================================================\n'
1035
 
            '^FAIL: unittest.FunctionTestCase \\(failing_test\\)\n'
 
1054
            '^FAIL: failing_test\n'
1036
1055
            '^----------------------------------------------------------------------\n'
1037
1056
            'Traceback \\(most recent call last\\):\n'
1038
1057
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1039
 
            '    raise AssertionError\\(\'foo\'\\)\n'
 
1058
            '    self.fail\\(\'foo\'\\)\n'
1040
1059
            '.*'
1041
1060
            '^----------------------------------------------------------------------\n'
1042
1061
            '.*'
1048
1067
        # the final output.
1049
1068
        class Test(tests.TestCase):
1050
1069
            def known_failure_test(self):
1051
 
                raise tests.KnownFailure('failed')
 
1070
                self.expectFailure('failed', self.assertTrue, False)
1052
1071
        test = Test("known_failure_test")
1053
1072
        stream = StringIO()
1054
1073
        runner = tests.TextTestRunner(stream=stream)
1176
1195
        # Reading from the actual source tree breaks isolation, but we don't
1177
1196
        # want to assume that thats *all* that would happen.
1178
1197
        self._get_source_tree_calls = []
1179
 
        def _get_bzr_source_tree():
 
1198
        def new_get():
1180
1199
            self._get_source_tree_calls.append("called")
1181
1200
            return None
1182
 
        orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
1183
 
        bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
1184
 
        def restore():
1185
 
            bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
1186
 
        self.addCleanup(restore)
 
1201
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree',  new_get)
1187
1202
 
1188
1203
    def test_bench_history(self):
1189
1204
        # tests that the running the benchmark passes bench_history into
1199
1214
        self.assertContainsRe(output_string, "--date [0-9.]+")
1200
1215
        self.assertLength(1, self._get_source_tree_calls)
1201
1216
 
1202
 
    def assertLogDeleted(self, test):
1203
 
        log = test._get_log()
1204
 
        self.assertEqual("DELETED log file to reduce memory footprint", log)
1205
 
        self.assertEqual('', test._log_contents)
1206
 
        self.assertIs(None, test._log_file_name)
1207
 
 
1208
 
    def test_success_log_deleted(self):
1209
 
        """Successful tests have their log deleted"""
1210
 
 
1211
 
        class LogTester(tests.TestCase):
1212
 
 
1213
 
            def test_success(self):
1214
 
                self.log('this will be removed\n')
1215
 
 
1216
 
        sio = StringIO()
1217
 
        runner = tests.TextTestRunner(stream=sio)
1218
 
        test = LogTester('test_success')
1219
 
        result = self.run_test_runner(runner, test)
1220
 
 
1221
 
        self.assertLogDeleted(test)
1222
 
 
1223
 
    def test_skipped_log_deleted(self):
1224
 
        """Skipped tests have their log deleted"""
1225
 
 
1226
 
        class LogTester(tests.TestCase):
1227
 
 
1228
 
            def test_skipped(self):
1229
 
                self.log('this will be removed\n')
1230
 
                raise tests.TestSkipped()
1231
 
 
1232
 
        sio = StringIO()
1233
 
        runner = tests.TextTestRunner(stream=sio)
1234
 
        test = LogTester('test_skipped')
1235
 
        result = self.run_test_runner(runner, test)
1236
 
 
1237
 
        self.assertLogDeleted(test)
1238
 
 
1239
 
    def test_not_aplicable_log_deleted(self):
1240
 
        """Not applicable tests have their log deleted"""
1241
 
 
1242
 
        class LogTester(tests.TestCase):
1243
 
 
1244
 
            def test_not_applicable(self):
1245
 
                self.log('this will be removed\n')
1246
 
                raise tests.TestNotApplicable()
1247
 
 
1248
 
        sio = StringIO()
1249
 
        runner = tests.TextTestRunner(stream=sio)
1250
 
        test = LogTester('test_not_applicable')
1251
 
        result = self.run_test_runner(runner, test)
1252
 
 
1253
 
        self.assertLogDeleted(test)
1254
 
 
1255
 
    def test_known_failure_log_deleted(self):
1256
 
        """Know failure tests have their log deleted"""
1257
 
 
1258
 
        class LogTester(tests.TestCase):
1259
 
 
1260
 
            def test_known_failure(self):
1261
 
                self.log('this will be removed\n')
1262
 
                raise tests.KnownFailure()
1263
 
 
1264
 
        sio = StringIO()
1265
 
        runner = tests.TextTestRunner(stream=sio)
1266
 
        test = LogTester('test_known_failure')
1267
 
        result = self.run_test_runner(runner, test)
1268
 
 
1269
 
        self.assertLogDeleted(test)
1270
 
 
1271
 
    def test_fail_log_kept(self):
1272
 
        """Failed tests have their log kept"""
1273
 
 
1274
 
        class LogTester(tests.TestCase):
1275
 
 
1276
 
            def test_fail(self):
1277
 
                self.log('this will be kept\n')
1278
 
                self.fail('this test fails')
1279
 
 
1280
 
        sio = StringIO()
1281
 
        runner = tests.TextTestRunner(stream=sio)
1282
 
        test = LogTester('test_fail')
1283
 
        result = self.run_test_runner(runner, test)
1284
 
 
1285
 
        text = sio.getvalue()
1286
 
        self.assertContainsRe(text, 'this will be kept')
1287
 
        self.assertContainsRe(text, 'this test fails')
1288
 
 
1289
 
        log = test._get_log()
1290
 
        self.assertContainsRe(log, 'this will be kept')
1291
 
        self.assertEqual(log, test._log_contents)
1292
 
 
1293
 
    def test_error_log_kept(self):
1294
 
        """Tests with errors have their log kept"""
1295
 
 
1296
 
        class LogTester(tests.TestCase):
1297
 
 
1298
 
            def test_error(self):
1299
 
                self.log('this will be kept\n')
1300
 
                raise ValueError('random exception raised')
1301
 
 
1302
 
        sio = StringIO()
1303
 
        runner = tests.TextTestRunner(stream=sio)
1304
 
        test = LogTester('test_error')
1305
 
        result = self.run_test_runner(runner, test)
1306
 
 
1307
 
        text = sio.getvalue()
1308
 
        self.assertContainsRe(text, 'this will be kept')
1309
 
        self.assertContainsRe(text, 'random exception raised')
1310
 
 
1311
 
        log = test._get_log()
1312
 
        self.assertContainsRe(log, 'this will be kept')
1313
 
        self.assertEqual(log, test._log_contents)
1314
 
 
1315
1217
    def test_startTestRun(self):
1316
1218
        """run should call result.startTestRun()"""
1317
1219
        calls = []
1410
1312
        self.assertEqual(flags, bzrlib.debug.debug_flags)
1411
1313
 
1412
1314
    def change_selftest_debug_flags(self, new_flags):
1413
 
        orig_selftest_flags = tests.selftest_debug_flags
1414
 
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
1415
 
        tests.selftest_debug_flags = set(new_flags)
1416
 
 
1417
 
    def _restore_selftest_debug_flags(self, flags):
1418
 
        tests.selftest_debug_flags = flags
 
1315
        self.overrideAttr(tests, 'selftest_debug_flags', set(new_flags))
1419
1316
 
1420
1317
    def test_allow_debug_flag(self):
1421
1318
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1481
1378
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1482
1379
 
1483
1380
    def make_test_result(self):
 
1381
        """Get a test result that writes to the test log file."""
1484
1382
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1485
1383
 
1486
1384
    def inner_test(self):
1494
1392
        result = self.make_test_result()
1495
1393
        self.inner_test.run(result)
1496
1394
        note("outer finish")
 
1395
        self.addCleanup(osutils.delete_any, self._log_file_name)
1497
1396
 
1498
1397
    def test_trace_nesting(self):
1499
1398
        # this tests that each test case nests its trace facility correctly.
1511
1410
        outer_test = TestTestCase("outer_child")
1512
1411
        result = self.make_test_result()
1513
1412
        outer_test.run(result)
1514
 
        self.addCleanup(osutils.delete_any, outer_test._log_file_name)
1515
1413
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
1516
1414
 
1517
1415
    def method_that_times_a_bit_twice(self):
1571
1469
        # permitted.
1572
1470
        # Manually set one up (TestCase doesn't and shouldn't provide magic
1573
1471
        # machinery)
1574
 
        transport_server = MemoryServer()
1575
 
        transport_server.setUp()
1576
 
        self.addCleanup(transport_server.tearDown)
 
1472
        transport_server = memory.MemoryServer()
 
1473
        transport_server.start_server()
 
1474
        self.addCleanup(transport_server.stop_server)
1577
1475
        t = transport.get_transport(transport_server.get_url())
1578
1476
        bzrdir.BzrDir.create(t.base)
1579
1477
        self.assertRaises(errors.BzrError,
1632
1530
        """Test disabled tests behaviour with support aware results."""
1633
1531
        test = SampleTestCase('_test_pass')
1634
1532
        class DisabledFeature(object):
 
1533
            def __eq__(self, other):
 
1534
                return isinstance(other, DisabledFeature)
1635
1535
            def available(self):
1636
1536
                return False
1637
1537
        the_feature = DisabledFeature()
1648
1548
                self.calls.append(('addNotSupported', test, feature))
1649
1549
        result = InstrumentedTestResult()
1650
1550
        test.run(result)
 
1551
        case = result.calls[0][1]
1651
1552
        self.assertEqual([
1652
 
            ('startTest', test),
1653
 
            ('addNotSupported', test, the_feature),
1654
 
            ('stopTest', test),
 
1553
            ('startTest', case),
 
1554
            ('addNotSupported', case, the_feature),
 
1555
            ('stopTest', case),
1655
1556
            ],
1656
1557
            result.calls)
1657
1558
 
1658
1559
    def test_start_server_registers_url(self):
1659
 
        transport_server = MemoryServer()
 
1560
        transport_server = memory.MemoryServer()
1660
1561
        # A little strict, but unlikely to be changed soon.
1661
1562
        self.assertEqual([], self._bzr_selftest_roots)
1662
1563
        self.start_server(transport_server)
1718
1619
        self.assertRaises(AssertionError,
1719
1620
            self.assertListRaises, _TestException, success_generator)
1720
1621
 
 
1622
    def test_overrideAttr_without_value(self):
 
1623
        self.test_attr = 'original' # Define a test attribute
 
1624
        obj = self # Make 'obj' visible to the embedded test
 
1625
        class Test(tests.TestCase):
 
1626
 
 
1627
            def setUp(self):
 
1628
                tests.TestCase.setUp(self)
 
1629
                self.orig = self.overrideAttr(obj, 'test_attr')
 
1630
 
 
1631
            def test_value(self):
 
1632
                self.assertEqual('original', self.orig)
 
1633
                self.assertEqual('original', obj.test_attr)
 
1634
                obj.test_attr = 'modified'
 
1635
                self.assertEqual('modified', obj.test_attr)
 
1636
 
 
1637
        test = Test('test_value')
 
1638
        test.run(unittest.TestResult())
 
1639
        self.assertEqual('original', obj.test_attr)
 
1640
 
 
1641
    def test_overrideAttr_with_value(self):
 
1642
        self.test_attr = 'original' # Define a test attribute
 
1643
        obj = self # Make 'obj' visible to the embedded test
 
1644
        class Test(tests.TestCase):
 
1645
 
 
1646
            def setUp(self):
 
1647
                tests.TestCase.setUp(self)
 
1648
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
 
1649
 
 
1650
            def test_value(self):
 
1651
                self.assertEqual('original', self.orig)
 
1652
                self.assertEqual('modified', obj.test_attr)
 
1653
 
 
1654
        test = Test('test_value')
 
1655
        test.run(unittest.TestResult())
 
1656
        self.assertEqual('original', obj.test_attr)
 
1657
 
1721
1658
 
1722
1659
# NB: Don't delete this; it's not actually from 0.11!
1723
1660
@deprecated_function(deprecated_in((0, 11, 0)))
1867
1804
        # make_branch_and_tree has to use local branch and repositories
1868
1805
        # when the vfs transport and local disk are colocated, even if
1869
1806
        # a different transport is in use for url generation.
1870
 
        from bzrlib.transport.fakevfat import FakeVFATServer
1871
 
        self.transport_server = FakeVFATServer
 
1807
        self.transport_server = test_server.FakeVFATServer
1872
1808
        self.assertFalse(self.get_url('t1').startswith('file://'))
1873
1809
        tree = self.make_branch_and_tree('t1')
1874
1810
        base = tree.bzrdir.root_transport.base
1972
1908
        self.assertEqual(expected.getvalue(), repeated.getvalue())
1973
1909
 
1974
1910
    def test_runner_class(self):
1975
 
        self.requireFeature(SubUnitFeature)
 
1911
        self.requireFeature(features.subunit)
1976
1912
        from subunit import ProtocolTestCase
1977
1913
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1978
1914
            test_suite_factory=self.factory)
2010
1946
        self.assertEqual(transport_server, captured_transport[0])
2011
1947
 
2012
1948
    def test_transport_sftp(self):
2013
 
        try:
2014
 
            import bzrlib.transport.sftp
2015
 
        except errors.ParamikoNotPresent:
2016
 
            raise tests.TestSkipped("Paramiko not present")
2017
 
        self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
 
1949
        self.requireFeature(features.paramiko)
 
1950
        self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
2018
1951
 
2019
1952
    def test_transport_memory(self):
2020
 
        self.check_transport_set(bzrlib.transport.memory.MemoryServer)
 
1953
        self.check_transport_set(memory.MemoryServer)
2021
1954
 
2022
1955
 
2023
1956
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
2424
2357
        self.assertEqual('bzr: interrupted\n', result[1])
2425
2358
 
2426
2359
 
2427
 
class TestKnownFailure(tests.TestCase):
2428
 
 
2429
 
    def test_known_failure(self):
2430
 
        """Check that KnownFailure is defined appropriately."""
2431
 
        # a KnownFailure is an assertion error for compatability with unaware
2432
 
        # runners.
2433
 
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
2434
 
 
2435
 
    def test_expect_failure(self):
2436
 
        try:
2437
 
            self.expectFailure("Doomed to failure", self.assertTrue, False)
2438
 
        except tests.KnownFailure, e:
2439
 
            self.assertEqual('Doomed to failure', e.args[0])
2440
 
        try:
2441
 
            self.expectFailure("Doomed to failure", self.assertTrue, True)
2442
 
        except AssertionError, e:
2443
 
            self.assertEqual('Unexpected success.  Should have failed:'
2444
 
                             ' Doomed to failure', e.args[0])
2445
 
        else:
2446
 
            self.fail('Assertion not raised')
2447
 
 
2448
 
 
2449
2360
class TestFeature(tests.TestCase):
2450
2361
 
2451
2362
    def test_caching(self):
2487
2398
        self.assertIs(feature, exception.args[0])
2488
2399
 
2489
2400
 
 
2401
simple_thunk_feature = tests._CompatabilityThunkFeature(
 
2402
    deprecated_in((2, 1, 0)),
 
2403
    'bzrlib.tests.test_selftest',
 
2404
    'simple_thunk_feature','UnicodeFilename',
 
2405
    replacement_module='bzrlib.tests'
 
2406
    )
 
2407
 
 
2408
class Test_CompatibilityFeature(tests.TestCase):
 
2409
 
 
2410
    def test_does_thunk(self):
 
2411
        res = self.callDeprecated(
 
2412
            ['bzrlib.tests.test_selftest.simple_thunk_feature was deprecated'
 
2413
             ' in version 2.1.0. Use bzrlib.tests.UnicodeFilename instead.'],
 
2414
            simple_thunk_feature.available)
 
2415
        self.assertEqual(tests.UnicodeFilename.available(), res)
 
2416
 
 
2417
 
 
2418
class TestModuleAvailableFeature(tests.TestCase):
 
2419
 
 
2420
    def test_available_module(self):
 
2421
        feature = tests.ModuleAvailableFeature('bzrlib.tests')
 
2422
        self.assertEqual('bzrlib.tests', feature.module_name)
 
2423
        self.assertEqual('bzrlib.tests', str(feature))
 
2424
        self.assertTrue(feature.available())
 
2425
        self.assertIs(tests, feature.module)
 
2426
 
 
2427
    def test_unavailable_module(self):
 
2428
        feature = tests.ModuleAvailableFeature('bzrlib.no_such_module_exists')
 
2429
        self.assertEqual('bzrlib.no_such_module_exists', str(feature))
 
2430
        self.assertFalse(feature.available())
 
2431
        self.assertIs(None, feature.module)
 
2432
 
 
2433
 
2490
2434
class TestSelftestFiltering(tests.TestCase):
2491
2435
 
2492
2436
    def setUp(self):
2671
2615
        # the test framework
2672
2616
        self.assertEquals('always fails', str(e))
2673
2617
        # check that there's no traceback in the test log
2674
 
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
2675
 
            r'Traceback')
 
2618
        self.assertNotContainsRe(self.get_log(), r'Traceback')
2676
2619
 
2677
2620
    def test_run_bzr_user_error_caught(self):
2678
2621
        # Running bzr in blackbox mode, normal/expected/user errors should be
2679
2622
        # caught in the regular way and turned into an error message plus exit
2680
2623
        # code.
2681
 
        transport_server = MemoryServer()
2682
 
        transport_server.setUp()
2683
 
        self.addCleanup(transport_server.tearDown)
 
2624
        transport_server = memory.MemoryServer()
 
2625
        transport_server.start_server()
 
2626
        self.addCleanup(transport_server.stop_server)
2684
2627
        url = transport_server.get_url()
2685
2628
        self.permit_url(url)
2686
2629
        out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
2842
2785
        # test doubles that supply a few sample tests to load, and check they
2843
2786
        # are loaded.
2844
2787
        calls = []
2845
 
        def _test_suite_testmod_names():
 
2788
        def testmod_names():
2846
2789
            calls.append("testmod_names")
2847
2790
            return [
2848
2791
                'bzrlib.tests.blackbox.test_branch',
2849
2792
                'bzrlib.tests.per_transport',
2850
2793
                'bzrlib.tests.test_selftest',
2851
2794
                ]
2852
 
        original_testmod_names = tests._test_suite_testmod_names
2853
 
        def _test_suite_modules_to_doctest():
 
2795
        self.overrideAttr(tests, '_test_suite_testmod_names', testmod_names)
 
2796
        def doctests():
2854
2797
            calls.append("modules_to_doctest")
2855
2798
            return ['bzrlib.timestamp']
2856
 
        orig_modules_to_doctest = tests._test_suite_modules_to_doctest
2857
 
        def restore_names():
2858
 
            tests._test_suite_testmod_names = original_testmod_names
2859
 
            tests._test_suite_modules_to_doctest = orig_modules_to_doctest
2860
 
        self.addCleanup(restore_names)
2861
 
        tests._test_suite_testmod_names = _test_suite_testmod_names
2862
 
        tests._test_suite_modules_to_doctest = _test_suite_modules_to_doctest
 
2799
        self.overrideAttr(tests, '_test_suite_modules_to_doctest', doctests)
2863
2800
        expected_test_list = [
2864
2801
            # testmod_names
2865
2802
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2931
2868
    def test_load_tests(self):
2932
2869
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2933
2870
        loader = self._create_loader(test_list)
2934
 
 
2935
2871
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2936
2872
        self.assertEquals(test_list, _test_ids(suite))
2937
2873
 
2938
2874
    def test_exclude_tests(self):
2939
2875
        test_list = ['bogus']
2940
2876
        loader = self._create_loader(test_list)
2941
 
 
2942
2877
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2943
2878
        self.assertEquals([], _test_ids(suite))
2944
2879
 
2989
2924
        tpr.register('bar', 'bbb.aaa.rrr')
2990
2925
        tpr.register('bar', 'bBB.aAA.rRR')
2991
2926
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2992
 
        self.assertContainsRe(self._get_log(keep_log_file=True),
2993
 
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
 
2927
        self.assertThat(self.get_log(),
 
2928
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR", ELLIPSIS))
2994
2929
 
2995
2930
    def test_get_unknown_prefix(self):
2996
2931
        tpr = self._get_registry()