~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Vincent Ladeuil
  • Date: 2009-05-05 15:31:34 UTC
  • mto: (4343.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4344.
  • Revision ID: v.ladeuil+lp@free.fr-20090505153134-q4bp4is9gywsmzrv
Clean up test for log formats.

* bzrlib/tests/blackbox/test_logformats.py:
Update tests to actual style.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""Tests for the test framework."""
18
18
 
19
 
from cStringIO import StringIO
 
19
import cStringIO
20
20
import os
 
21
from StringIO import StringIO
21
22
import sys
22
23
import time
23
24
import unittest
32
33
    lockdir,
33
34
    memorytree,
34
35
    osutils,
35
 
    progress,
36
36
    remote,
37
37
    repository,
38
38
    symbol_versioning,
39
39
    tests,
40
40
    workingtree,
41
41
    )
 
42
from bzrlib.progress import _BaseProgressBar
42
43
from bzrlib.repofmt import (
43
44
    pack_repo,
44
45
    weaverepo,
49
50
    deprecated_method,
50
51
    )
51
52
from bzrlib.tests import (
52
 
    test_lsprof,
53
 
    test_sftp_transport,
54
 
    TestUtil,
55
 
    )
 
53
                          ChrootedTestCase,
 
54
                          ExtendedTestResult,
 
55
                          Feature,
 
56
                          KnownFailure,
 
57
                          TestCase,
 
58
                          TestCaseInTempDir,
 
59
                          TestCaseWithMemoryTransport,
 
60
                          TestCaseWithTransport,
 
61
                          TestNotApplicable,
 
62
                          TestSkipped,
 
63
                          TestSuite,
 
64
                          TestUtil,
 
65
                          TextTestRunner,
 
66
                          UnavailableFeature,
 
67
                          condition_id_re,
 
68
                          condition_isinstance,
 
69
                          exclude_tests_by_condition,
 
70
                          exclude_tests_by_re,
 
71
                          filter_suite_by_condition,
 
72
                          filter_suite_by_re,
 
73
                          iter_suite_tests,
 
74
                          preserve_input,
 
75
                          randomize_suite,
 
76
                          run_suite,
 
77
                          split_suite_by_condition,
 
78
                          split_suite_by_re,
 
79
                          test_lsprof,
 
80
                          test_suite,
 
81
                          )
 
82
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
 
83
from bzrlib.tests.TestUtil import _load_module_by_name
56
84
from bzrlib.trace import note
57
85
from bzrlib.transport.memory import MemoryServer, MemoryTransport
58
86
from bzrlib.version import _get_bzr_source_tree
60
88
 
61
89
def _test_ids(test_suite):
62
90
    """Get the ids for the tests in a test suite."""
63
 
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
64
 
 
65
 
 
66
 
class SelftestTests(tests.TestCase):
 
91
    return [t.id() for t in iter_suite_tests(test_suite)]
 
92
 
 
93
 
 
94
class SelftestTests(TestCase):
67
95
 
68
96
    def test_import_tests(self):
69
 
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
 
97
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
70
98
        self.assertEqual(mod.SelftestTests, SelftestTests)
71
99
 
72
100
    def test_import_test_failure(self):
73
101
        self.assertRaises(ImportError,
74
 
                          TestUtil._load_module_by_name,
 
102
                          _load_module_by_name,
75
103
                          'bzrlib.no-name-yet')
76
104
 
77
 
class MetaTestLog(tests.TestCase):
 
105
class MetaTestLog(TestCase):
78
106
 
79
107
    def test_logging(self):
80
108
        """Test logs are captured when a test fails."""
84
112
                              'a test message\n')
85
113
 
86
114
 
87
 
class TestUnicodeFilename(tests.TestCase):
 
115
class TestUnicodeFilename(TestCase):
88
116
 
89
117
    def test_probe_passes(self):
90
118
        """UnicodeFilename._probe passes."""
93
121
        tests.UnicodeFilename._probe()
94
122
 
95
123
 
96
 
class TestTreeShape(tests.TestCaseInTempDir):
 
124
class TestTreeShape(TestCaseInTempDir):
97
125
 
98
126
    def test_unicode_paths(self):
99
127
        self.requireFeature(tests.UnicodeFilename)
103
131
        self.failUnlessExists(filename)
104
132
 
105
133
 
106
 
class TestTransportScenarios(tests.TestCase):
 
134
class TestTransportScenarios(TestCase):
107
135
    """A group of tests that test the transport implementation adaption core.
108
136
 
109
137
    This is a meta test that the tests are applied to all available
120
148
            def get_test_permutations(self):
121
149
                return sample_permutation
122
150
        sample_permutation = [(1,2), (3,4)]
123
 
        from bzrlib.tests.per_transport import get_transport_test_permutations
 
151
        from bzrlib.tests.test_transport_implementations \
 
152
            import get_transport_test_permutations
124
153
        self.assertEqual(sample_permutation,
125
154
                         get_transport_test_permutations(MockModule()))
126
155
 
129
158
        # as there are in all the registered transport modules - we assume if
130
159
        # this matches its probably doing the right thing especially in
131
160
        # combination with the tests for setting the right classes below.
132
 
        from bzrlib.tests.per_transport import transport_test_permutations
 
161
        from bzrlib.tests.test_transport_implementations \
 
162
            import transport_test_permutations
133
163
        from bzrlib.transport import _get_transport_modules
134
164
        modules = _get_transport_modules()
135
165
        permutation_count = 0
147
177
        # This test used to know about all the possible transports and the
148
178
        # order they were returned but that seems overly brittle (mbp
149
179
        # 20060307)
150
 
        from bzrlib.tests.per_transport import transport_test_permutations
 
180
        from bzrlib.tests.test_transport_implementations \
 
181
            import transport_test_permutations
151
182
        scenarios = transport_test_permutations()
152
183
        # there are at least that many builtin transports
153
184
        self.assertTrue(len(scenarios) > 6)
159
190
                                   bzrlib.transport.Server))
160
191
 
161
192
 
162
 
class TestBranchScenarios(tests.TestCase):
 
193
class TestBranchScenarios(TestCase):
163
194
 
164
195
    def test_scenarios(self):
165
196
        # check that constructor parameters are passed through to the adapted
166
197
        # test.
167
 
        from bzrlib.tests.per_branch import make_scenarios
 
198
        from bzrlib.tests.branch_implementations import make_scenarios
168
199
        server1 = "a"
169
200
        server2 = "b"
170
201
        formats = [("c", "C"), ("d", "D")]
184
215
            scenarios)
185
216
 
186
217
 
187
 
class TestBzrDirScenarios(tests.TestCase):
 
218
class TestBzrDirScenarios(TestCase):
188
219
 
189
220
    def test_scenarios(self):
190
221
        # check that constructor parameters are passed through to the adapted
191
222
        # test.
192
 
        from bzrlib.tests.per_bzrdir import make_scenarios
 
223
        from bzrlib.tests.bzrdir_implementations import make_scenarios
193
224
        vfs_factory = "v"
194
225
        server1 = "a"
195
226
        server2 = "b"
209
240
            scenarios)
210
241
 
211
242
 
212
 
class TestRepositoryScenarios(tests.TestCase):
 
243
class TestRepositoryScenarios(TestCase):
213
244
 
214
245
    def test_formats_to_scenarios(self):
215
246
        from bzrlib.tests.per_repository import formats_to_scenarios
249
280
            vfs_scenarios)
250
281
 
251
282
 
252
 
class TestTestScenarioApplication(tests.TestCase):
 
283
class TestTestScenarioApplication(TestCase):
253
284
    """Tests for the test adaption facilities."""
254
285
 
255
286
    def test_apply_scenario(self):
285
316
            adapted_test2.id())
286
317
 
287
318
 
288
 
class TestInterRepositoryScenarios(tests.TestCase):
 
319
class TestInterRepositoryScenarios(TestCase):
289
320
 
290
321
    def test_scenarios(self):
291
322
        # check that constructor parameters are passed through to the adapted
292
323
        # test.
293
 
        from bzrlib.tests.per_interrepository import make_scenarios
 
324
        from bzrlib.tests.interrepository_implementations import \
 
325
            make_scenarios
294
326
        server1 = "a"
295
327
        server2 = "b"
296
328
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
311
343
            scenarios)
312
344
 
313
345
 
314
 
class TestWorkingTreeScenarios(tests.TestCase):
 
346
class TestWorkingTreeScenarios(TestCase):
315
347
 
316
348
    def test_scenarios(self):
317
349
        # check that constructor parameters are passed through to the adapted
318
350
        # test.
319
 
        from bzrlib.tests.per_workingtree import make_scenarios
 
351
        from bzrlib.tests.workingtree_implementations \
 
352
            import make_scenarios
320
353
        server1 = "a"
321
354
        server2 = "b"
322
355
        formats = [workingtree.WorkingTreeFormat2(),
336
369
            scenarios)
337
370
 
338
371
 
339
 
class TestTreeScenarios(tests.TestCase):
 
372
class TestTreeScenarios(TestCase):
340
373
 
341
374
    def test_scenarios(self):
342
375
        # the tree implementation scenario generator is meant to setup one
346
379
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
347
380
        # revision one set to revision_tree_from_workingtree.
348
381
 
349
 
        from bzrlib.tests.per_tree import (
 
382
        from bzrlib.tests.tree_implementations import (
350
383
            _dirstate_tree_from_workingtree,
351
384
            make_scenarios,
352
385
            preview_tree_pre,
415
448
        self.assertEqual(expected_scenarios, scenarios)
416
449
 
417
450
 
418
 
class TestInterTreeScenarios(tests.TestCase):
 
451
class TestInterTreeScenarios(TestCase):
419
452
    """A group of tests that test the InterTreeTestAdapter."""
420
453
 
421
454
    def test_scenarios(self):
428
461
        # unlike the TestProviderAdapter we dont want to automatically add a
429
462
        # parameterized one for WorkingTree - the optimisers will tell us what
430
463
        # ones to add.
431
 
        from bzrlib.tests.per_tree import (
 
464
        from bzrlib.tests.tree_implementations import (
432
465
            return_parameter,
433
466
            revision_tree_from_workingtree
434
467
            )
435
 
        from bzrlib.tests.per_intertree import (
 
468
        from bzrlib.tests.intertree_implementations import (
436
469
            make_scenarios,
437
470
            )
438
471
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
471
504
        self.assertEqual(scenarios, expected_scenarios)
472
505
 
473
506
 
474
 
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
 
507
class TestTestCaseInTempDir(TestCaseInTempDir):
475
508
 
476
509
    def test_home_is_not_working(self):
477
510
        self.assertNotEqual(self.test_dir, self.test_home_dir)
493
526
            os.lstat("foo"), os.lstat("bar"))
494
527
 
495
528
 
496
 
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
 
529
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
497
530
 
498
531
    def test_home_is_non_existant_dir_under_root(self):
499
532
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
589
622
        self.assertRaises(AssertionError, self._check_safety_net)
590
623
 
591
624
    def test_dangling_locks_cause_failures(self):
592
 
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
 
625
        # This is currently only enabled during debug runs, so turn debugging
 
626
        # on.
 
627
        debug.debug_flags.add('lock')
 
628
        class TestDanglingLock(TestCaseWithMemoryTransport):
593
629
            def test_function(self):
594
630
                t = self.get_transport('.')
595
631
                l = lockdir.LockDir(t, 'lock')
600
636
        self.assertEqual(1, len(result.errors))
601
637
 
602
638
 
603
 
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
 
639
class TestTestCaseWithTransport(TestCaseWithTransport):
604
640
    """Tests for the convenience functions TestCaseWithTransport introduces."""
605
641
 
606
642
    def test_get_readonly_url_none(self):
657
693
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
658
694
 
659
695
 
660
 
class TestTestCaseTransports(tests.TestCaseWithTransport):
 
696
class TestTestCaseTransports(TestCaseWithTransport):
661
697
 
662
698
    def setUp(self):
663
699
        super(TestTestCaseTransports, self).setUp()
672
708
        self.failIfExists('subdir')
673
709
 
674
710
 
675
 
class TestChrootedTest(tests.ChrootedTestCase):
 
711
class TestChrootedTest(ChrootedTestCase):
676
712
 
677
713
    def test_root_is_root(self):
678
714
        from bzrlib.transport import get_transport
681
717
        self.assertEqual(url, t.clone('..').base)
682
718
 
683
719
 
684
 
class TestTestResult(tests.TestCase):
 
720
class MockProgress(_BaseProgressBar):
 
721
    """Progress-bar standin that records calls.
 
722
 
 
723
    Useful for testing pb using code.
 
724
    """
 
725
 
 
726
    def __init__(self):
 
727
        _BaseProgressBar.__init__(self)
 
728
        self.calls = []
 
729
 
 
730
    def tick(self):
 
731
        self.calls.append(('tick',))
 
732
 
 
733
    def update(self, msg=None, current=None, total=None):
 
734
        self.calls.append(('update', msg, current, total))
 
735
 
 
736
    def clear(self):
 
737
        self.calls.append(('clear',))
 
738
 
 
739
    def note(self, msg, *args):
 
740
        self.calls.append(('note', msg, args))
 
741
 
 
742
 
 
743
class TestTestResult(TestCase):
685
744
 
686
745
    def check_timing(self, test_case, expected_re):
687
746
        result = bzrlib.tests.TextTestResult(self._log_file,
693
752
        self.assertContainsRe(timed_string, expected_re)
694
753
 
695
754
    def test_test_reporting(self):
696
 
        class ShortDelayTestCase(tests.TestCase):
 
755
        class ShortDelayTestCase(TestCase):
697
756
            def test_short_delay(self):
698
757
                time.sleep(0.003)
699
758
            def test_short_benchmark(self):
700
759
                self.time(time.sleep, 0.003)
701
760
        self.check_timing(ShortDelayTestCase('test_short_delay'),
702
761
                          r"^ +[0-9]+ms$")
703
 
        # if a benchmark time is given, we now show just that time followed by
704
 
        # a star
 
762
        # if a benchmark time is given, we want a x of y style result.
705
763
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
706
 
                          r"^ +[0-9]+ms\*$")
 
764
                          r"^ +[0-9]+ms/ +[0-9]+ms$")
707
765
 
708
766
    def test_unittest_reporting_unittest_class(self):
709
767
        # getting the time from a non-bzrlib test works ok
793
851
 
794
852
    def test_known_failure(self):
795
853
        """A KnownFailure being raised should trigger several result actions."""
796
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
854
        class InstrumentedTestResult(ExtendedTestResult):
797
855
            def done(self): pass
798
856
            def startTests(self): pass
799
857
            def report_test_start(self, test): pass
801
859
                self._call = test, err
802
860
        result = InstrumentedTestResult(None, None, None, None)
803
861
        def test_function():
804
 
            raise tests.KnownFailure('failed!')
 
862
            raise KnownFailure('failed!')
805
863
        test = unittest.FunctionTestCase(test_function)
806
864
        test.run(result)
807
865
        # it should invoke 'report_known_failure'.
808
866
        self.assertEqual(2, len(result._call))
809
867
        self.assertEqual(test, result._call[0])
810
 
        self.assertEqual(tests.KnownFailure, result._call[1][0])
811
 
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
 
868
        self.assertEqual(KnownFailure, result._call[1][0])
 
869
        self.assertIsInstance(result._call[1][1], KnownFailure)
812
870
        # we dont introspec the traceback, if the rest is ok, it would be
813
871
        # exceptional for it not to be.
814
872
        # it should update the known_failure_count on the object.
831
889
        # (class, exception object, traceback)
832
890
        # KnownFailures dont get their tracebacks shown though, so we
833
891
        # can skip that.
834
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
892
        err = (KnownFailure, KnownFailure('foo'), None)
835
893
        result.report_known_failure(test, err)
836
894
        output = result_stream.getvalue()[prefix:]
837
895
        lines = output.splitlines()
839
897
        self.assertEqual(lines[1], '    foo')
840
898
        self.assertEqual(2, len(lines))
841
899
 
 
900
    def test_text_report_known_failure(self):
 
901
        # text test output formatting
 
902
        pb = MockProgress()
 
903
        result = bzrlib.tests.TextTestResult(
 
904
            StringIO(),
 
905
            descriptions=0,
 
906
            verbosity=1,
 
907
            pb=pb,
 
908
            )
 
909
        test = self.get_passing_test()
 
910
        # this seeds the state to handle reporting the test.
 
911
        result.startTest(test)
 
912
        # the err parameter has the shape:
 
913
        # (class, exception object, traceback)
 
914
        # KnownFailures dont get their tracebacks shown though, so we
 
915
        # can skip that.
 
916
        err = (KnownFailure, KnownFailure('foo'), None)
 
917
        result.report_known_failure(test, err)
 
918
        self.assertEqual(
 
919
            [
 
920
            ('update', '[1 in 0s] passing_test', None, None),
 
921
            ('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
 
922
            ],
 
923
            pb.calls)
 
924
        # known_failures should be printed in the summary, so if we run a test
 
925
        # after there are some known failures, the update prefix should match
 
926
        # this.
 
927
        result.known_failure_count = 3
 
928
        test.run(result)
 
929
        self.assertEqual(
 
930
            [
 
931
            ('update', '[2 in 0s] passing_test', None, None),
 
932
            ],
 
933
            pb.calls[2:])
 
934
 
842
935
    def get_passing_test(self):
843
936
        """Return a test object that can't be run usefully."""
844
937
        def passing_test():
847
940
 
848
941
    def test_add_not_supported(self):
849
942
        """Test the behaviour of invoking addNotSupported."""
850
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
943
        class InstrumentedTestResult(ExtendedTestResult):
851
944
            def done(self): pass
852
945
            def startTests(self): pass
853
946
            def report_test_start(self, test): pass
855
948
                self._call = test, feature
856
949
        result = InstrumentedTestResult(None, None, None, None)
857
950
        test = SampleTestCase('_test_pass')
858
 
        feature = tests.Feature()
 
951
        feature = Feature()
859
952
        result.startTest(test)
860
953
        result.addNotSupported(test, feature)
861
954
        # it should invoke 'report_unsupported'.
880
973
            verbosity=2,
881
974
            )
882
975
        test = self.get_passing_test()
883
 
        feature = tests.Feature()
 
976
        feature = Feature()
884
977
        result.startTest(test)
885
978
        prefix = len(result_stream.getvalue())
886
979
        result.report_unsupported(test, feature)
887
980
        output = result_stream.getvalue()[prefix:]
888
981
        lines = output.splitlines()
889
 
        self.assertEqual(lines, ['NODEP        0ms',
890
 
                                 "    The feature 'Feature' is not available."])
 
982
        self.assertEqual(lines, ['NODEP                   0ms', "    The feature 'Feature' is not available."])
 
983
 
 
984
    def test_text_report_unsupported(self):
 
985
        # text test output formatting
 
986
        pb = MockProgress()
 
987
        result = bzrlib.tests.TextTestResult(
 
988
            StringIO(),
 
989
            descriptions=0,
 
990
            verbosity=1,
 
991
            pb=pb,
 
992
            )
 
993
        test = self.get_passing_test()
 
994
        feature = Feature()
 
995
        # this seeds the state to handle reporting the test.
 
996
        result.startTest(test)
 
997
        result.report_unsupported(test, feature)
 
998
        # no output on unsupported features
 
999
        self.assertEqual(
 
1000
            [('update', '[1 in 0s] passing_test', None, None)
 
1001
            ],
 
1002
            pb.calls)
 
1003
        # the number of missing features should be printed in the progress
 
1004
        # summary, so check for that.
 
1005
        result.unsupported = {'foo':0, 'bar':0}
 
1006
        test.run(result)
 
1007
        self.assertEqual(
 
1008
            [
 
1009
            ('update', '[2 in 0s, 2 missing] passing_test', None, None),
 
1010
            ],
 
1011
            pb.calls[1:])
891
1012
 
892
1013
    def test_unavailable_exception(self):
893
1014
        """An UnavailableFeature being raised should invoke addNotSupported."""
894
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
1015
        class InstrumentedTestResult(ExtendedTestResult):
895
1016
            def done(self): pass
896
1017
            def startTests(self): pass
897
1018
            def report_test_start(self, test): pass
898
1019
            def addNotSupported(self, test, feature):
899
1020
                self._call = test, feature
900
1021
        result = InstrumentedTestResult(None, None, None, None)
901
 
        feature = tests.Feature()
 
1022
        feature = Feature()
902
1023
        def test_function():
903
 
            raise tests.UnavailableFeature(feature)
 
1024
            raise UnavailableFeature(feature)
904
1025
        test = unittest.FunctionTestCase(test_function)
905
1026
        test.run(result)
906
1027
        # it should invoke 'addNotSupported'.
923
1044
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
924
1045
                                             verbosity=1)
925
1046
        test = self.get_passing_test()
926
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
1047
        err = (KnownFailure, KnownFailure('foo'), None)
927
1048
        result._addKnownFailure(test, err)
928
1049
        self.assertFalse(result.wasStrictlySuccessful())
929
1050
        self.assertEqual(None, result._extractBenchmarkTime(test))
938
1059
 
939
1060
    def test_startTests(self):
940
1061
        """Starting the first test should trigger startTests."""
941
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
1062
        class InstrumentedTestResult(ExtendedTestResult):
942
1063
            calls = 0
943
1064
            def startTests(self): self.calls += 1
944
1065
            def report_test_start(self, test): pass
950
1071
        self.assertEquals(1, result.calls)
951
1072
 
952
1073
 
953
 
class TestUnicodeFilenameFeature(tests.TestCase):
 
1074
class TestUnicodeFilenameFeature(TestCase):
954
1075
 
955
1076
    def test_probe_passes(self):
956
1077
        """UnicodeFilenameFeature._probe passes."""
959
1080
        tests.UnicodeFilenameFeature._probe()
960
1081
 
961
1082
 
962
 
class TestRunner(tests.TestCase):
 
1083
class TestRunner(TestCase):
963
1084
 
964
1085
    def dummy_test(self):
965
1086
        pass
970
1091
        This current saves and restores:
971
1092
        TestCaseInTempDir.TEST_ROOT
972
1093
 
973
 
        There should be no tests in this file that use
974
 
        bzrlib.tests.TextTestRunner without using this convenience method,
975
 
        because of our use of global state.
 
1094
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
 
1095
        without using this convenience method, because of our use of global state.
976
1096
        """
977
 
        old_root = tests.TestCaseInTempDir.TEST_ROOT
 
1097
        old_root = TestCaseInTempDir.TEST_ROOT
978
1098
        try:
979
 
            tests.TestCaseInTempDir.TEST_ROOT = None
 
1099
            TestCaseInTempDir.TEST_ROOT = None
980
1100
            return testrunner.run(test)
981
1101
        finally:
982
 
            tests.TestCaseInTempDir.TEST_ROOT = old_root
 
1102
            TestCaseInTempDir.TEST_ROOT = old_root
983
1103
 
984
1104
    def test_known_failure_failed_run(self):
985
1105
        # run a test that generates a known failure which should be printed in
986
1106
        # the final output when real failures occur.
987
1107
        def known_failure_test():
988
 
            raise tests.KnownFailure('failed')
 
1108
            raise KnownFailure('failed')
989
1109
        test = unittest.TestSuite()
990
1110
        test.addTest(unittest.FunctionTestCase(known_failure_test))
991
1111
        def failing_test():
992
1112
            raise AssertionError('foo')
993
1113
        test.addTest(unittest.FunctionTestCase(failing_test))
994
1114
        stream = StringIO()
995
 
        runner = tests.TextTestRunner(stream=stream)
 
1115
        runner = TextTestRunner(stream=stream)
996
1116
        result = self.run_test_runner(runner, test)
997
1117
        lines = stream.getvalue().splitlines()
998
1118
        self.assertEqual([
1012
1132
    def test_known_failure_ok_run(self):
1013
1133
        # run a test that generates a known failure which should be printed in the final output.
1014
1134
        def known_failure_test():
1015
 
            raise tests.KnownFailure('failed')
 
1135
            raise KnownFailure('failed')
1016
1136
        test = unittest.FunctionTestCase(known_failure_test)
1017
1137
        stream = StringIO()
1018
 
        runner = tests.TextTestRunner(stream=stream)
 
1138
        runner = TextTestRunner(stream=stream)
1019
1139
        result = self.run_test_runner(runner, test)
1020
1140
        self.assertContainsRe(stream.getvalue(),
1021
1141
            '\n'
1028
1148
        # run a test that is skipped, and check the suite as a whole still
1029
1149
        # succeeds.
1030
1150
        # skipping_test must be hidden in here so it's not run as a real test
1031
 
        class SkippingTest(tests.TestCase):
 
1151
        class SkippingTest(TestCase):
1032
1152
            def skipping_test(self):
1033
 
                raise tests.TestSkipped('test intentionally skipped')
1034
 
        runner = tests.TextTestRunner(stream=self._log_file)
 
1153
                raise TestSkipped('test intentionally skipped')
 
1154
        runner = TextTestRunner(stream=self._log_file)
1035
1155
        test = SkippingTest("skipping_test")
1036
1156
        result = self.run_test_runner(runner, test)
1037
1157
        self.assertTrue(result.wasSuccessful())
1038
1158
 
1039
1159
    def test_skipped_from_setup(self):
1040
1160
        calls = []
1041
 
        class SkippedSetupTest(tests.TestCase):
 
1161
        class SkippedSetupTest(TestCase):
1042
1162
 
1043
1163
            def setUp(self):
1044
1164
                calls.append('setUp')
1045
1165
                self.addCleanup(self.cleanup)
1046
 
                raise tests.TestSkipped('skipped setup')
 
1166
                raise TestSkipped('skipped setup')
1047
1167
 
1048
1168
            def test_skip(self):
1049
1169
                self.fail('test reached')
1051
1171
            def cleanup(self):
1052
1172
                calls.append('cleanup')
1053
1173
 
1054
 
        runner = tests.TextTestRunner(stream=self._log_file)
 
1174
        runner = TextTestRunner(stream=self._log_file)
1055
1175
        test = SkippedSetupTest('test_skip')
1056
1176
        result = self.run_test_runner(runner, test)
1057
1177
        self.assertTrue(result.wasSuccessful())
1060
1180
 
1061
1181
    def test_skipped_from_test(self):
1062
1182
        calls = []
1063
 
        class SkippedTest(tests.TestCase):
 
1183
        class SkippedTest(TestCase):
1064
1184
 
1065
1185
            def setUp(self):
1066
 
                tests.TestCase.setUp(self)
 
1186
                TestCase.setUp(self)
1067
1187
                calls.append('setUp')
1068
1188
                self.addCleanup(self.cleanup)
1069
1189
 
1070
1190
            def test_skip(self):
1071
 
                raise tests.TestSkipped('skipped test')
 
1191
                raise TestSkipped('skipped test')
1072
1192
 
1073
1193
            def cleanup(self):
1074
1194
                calls.append('cleanup')
1075
1195
 
1076
 
        runner = tests.TextTestRunner(stream=self._log_file)
 
1196
        runner = TextTestRunner(stream=self._log_file)
1077
1197
        test = SkippedTest('test_skip')
1078
1198
        result = self.run_test_runner(runner, test)
1079
1199
        self.assertTrue(result.wasSuccessful())
1083
1203
    def test_not_applicable(self):
1084
1204
        # run a test that is skipped because it's not applicable
1085
1205
        def not_applicable_test():
1086
 
            raise tests.TestNotApplicable('this test never runs')
 
1206
            from bzrlib.tests import TestNotApplicable
 
1207
            raise TestNotApplicable('this test never runs')
1087
1208
        out = StringIO()
1088
 
        runner = tests.TextTestRunner(stream=out, verbosity=2)
 
1209
        runner = TextTestRunner(stream=out, verbosity=2)
1089
1210
        test = unittest.FunctionTestCase(not_applicable_test)
1090
1211
        result = self.run_test_runner(runner, test)
1091
1212
        self._log_file.write(out.getvalue())
1098
1219
 
1099
1220
    def test_not_applicable_demo(self):
1100
1221
        # just so you can see it in the test output
1101
 
        raise tests.TestNotApplicable('this test is just a demonstation')
 
1222
        raise TestNotApplicable('this test is just a demonstation')
1102
1223
 
1103
1224
    def test_unsupported_features_listed(self):
1104
1225
        """When unsupported features are encountered they are detailed."""
1105
 
        class Feature1(tests.Feature):
 
1226
        class Feature1(Feature):
1106
1227
            def _probe(self): return False
1107
 
        class Feature2(tests.Feature):
 
1228
        class Feature2(Feature):
1108
1229
            def _probe(self): return False
1109
1230
        # create sample tests
1110
1231
        test1 = SampleTestCase('_test_pass')
1115
1236
        test.addTest(test1)
1116
1237
        test.addTest(test2)
1117
1238
        stream = StringIO()
1118
 
        runner = tests.TextTestRunner(stream=stream)
 
1239
        runner = TextTestRunner(stream=stream)
1119
1240
        result = self.run_test_runner(runner, test)
1120
1241
        lines = stream.getvalue().splitlines()
1121
1242
        self.assertEqual([
1132
1253
        workingtree = _get_bzr_source_tree()
1133
1254
        test = TestRunner('dummy_test')
1134
1255
        output = StringIO()
1135
 
        runner = tests.TextTestRunner(stream=self._log_file,
1136
 
                                      bench_history=output)
 
1256
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
1137
1257
        result = self.run_test_runner(runner, test)
1138
1258
        output_string = output.getvalue()
1139
1259
        self.assertContainsRe(output_string, "--date [0-9.]+")
1150
1270
    def test_success_log_deleted(self):
1151
1271
        """Successful tests have their log deleted"""
1152
1272
 
1153
 
        class LogTester(tests.TestCase):
 
1273
        class LogTester(TestCase):
1154
1274
 
1155
1275
            def test_success(self):
1156
1276
                self.log('this will be removed\n')
1157
1277
 
1158
 
        sio = StringIO()
1159
 
        runner = tests.TextTestRunner(stream=sio)
 
1278
        sio = cStringIO.StringIO()
 
1279
        runner = TextTestRunner(stream=sio)
1160
1280
        test = LogTester('test_success')
1161
1281
        result = self.run_test_runner(runner, test)
1162
1282
 
1165
1285
    def test_skipped_log_deleted(self):
1166
1286
        """Skipped tests have their log deleted"""
1167
1287
 
1168
 
        class LogTester(tests.TestCase):
 
1288
        class LogTester(TestCase):
1169
1289
 
1170
1290
            def test_skipped(self):
1171
1291
                self.log('this will be removed\n')
1172
1292
                raise tests.TestSkipped()
1173
1293
 
1174
 
        sio = StringIO()
1175
 
        runner = tests.TextTestRunner(stream=sio)
 
1294
        sio = cStringIO.StringIO()
 
1295
        runner = TextTestRunner(stream=sio)
1176
1296
        test = LogTester('test_skipped')
1177
1297
        result = self.run_test_runner(runner, test)
1178
1298
 
1181
1301
    def test_not_aplicable_log_deleted(self):
1182
1302
        """Not applicable tests have their log deleted"""
1183
1303
 
1184
 
        class LogTester(tests.TestCase):
 
1304
        class LogTester(TestCase):
1185
1305
 
1186
1306
            def test_not_applicable(self):
1187
1307
                self.log('this will be removed\n')
1188
1308
                raise tests.TestNotApplicable()
1189
1309
 
1190
 
        sio = StringIO()
1191
 
        runner = tests.TextTestRunner(stream=sio)
 
1310
        sio = cStringIO.StringIO()
 
1311
        runner = TextTestRunner(stream=sio)
1192
1312
        test = LogTester('test_not_applicable')
1193
1313
        result = self.run_test_runner(runner, test)
1194
1314
 
1197
1317
    def test_known_failure_log_deleted(self):
1198
1318
        """Know failure tests have their log deleted"""
1199
1319
 
1200
 
        class LogTester(tests.TestCase):
 
1320
        class LogTester(TestCase):
1201
1321
 
1202
1322
            def test_known_failure(self):
1203
1323
                self.log('this will be removed\n')
1204
1324
                raise tests.KnownFailure()
1205
1325
 
1206
 
        sio = StringIO()
1207
 
        runner = tests.TextTestRunner(stream=sio)
 
1326
        sio = cStringIO.StringIO()
 
1327
        runner = TextTestRunner(stream=sio)
1208
1328
        test = LogTester('test_known_failure')
1209
1329
        result = self.run_test_runner(runner, test)
1210
1330
 
1213
1333
    def test_fail_log_kept(self):
1214
1334
        """Failed tests have their log kept"""
1215
1335
 
1216
 
        class LogTester(tests.TestCase):
 
1336
        class LogTester(TestCase):
1217
1337
 
1218
1338
            def test_fail(self):
1219
1339
                self.log('this will be kept\n')
1220
1340
                self.fail('this test fails')
1221
1341
 
1222
 
        sio = StringIO()
1223
 
        runner = tests.TextTestRunner(stream=sio)
 
1342
        sio = cStringIO.StringIO()
 
1343
        runner = TextTestRunner(stream=sio)
1224
1344
        test = LogTester('test_fail')
1225
1345
        result = self.run_test_runner(runner, test)
1226
1346
 
1235
1355
    def test_error_log_kept(self):
1236
1356
        """Tests with errors have their log kept"""
1237
1357
 
1238
 
        class LogTester(tests.TestCase):
 
1358
        class LogTester(TestCase):
1239
1359
 
1240
1360
            def test_error(self):
1241
1361
                self.log('this will be kept\n')
1242
1362
                raise ValueError('random exception raised')
1243
1363
 
1244
 
        sio = StringIO()
1245
 
        runner = tests.TextTestRunner(stream=sio)
 
1364
        sio = cStringIO.StringIO()
 
1365
        runner = TextTestRunner(stream=sio)
1246
1366
        test = LogTester('test_error')
1247
1367
        result = self.run_test_runner(runner, test)
1248
1368
 
1255
1375
        self.assertEqual(log, test._log_contents)
1256
1376
 
1257
1377
 
1258
 
class SampleTestCase(tests.TestCase):
 
1378
class SampleTestCase(TestCase):
1259
1379
 
1260
1380
    def _test_pass(self):
1261
1381
        pass
1263
1383
class _TestException(Exception):
1264
1384
    pass
1265
1385
 
1266
 
class TestTestCase(tests.TestCase):
 
1386
class TestTestCase(TestCase):
1267
1387
    """Tests that test the core bzrlib TestCase."""
1268
1388
 
1269
1389
    def test_assertLength_matches_empty(self):
1286
1406
            exception.args[0])
1287
1407
 
1288
1408
    def test_base_setUp_not_called_causes_failure(self):
1289
 
        class TestCaseWithBrokenSetUp(tests.TestCase):
 
1409
        class TestCaseWithBrokenSetUp(TestCase):
1290
1410
            def setUp(self):
1291
1411
                pass # does not call TestCase.setUp
1292
1412
            def test_foo(self):
1298
1418
        self.assertEqual(1, result.testsRun)
1299
1419
 
1300
1420
    def test_base_tearDown_not_called_causes_failure(self):
1301
 
        class TestCaseWithBrokenTearDown(tests.TestCase):
 
1421
        class TestCaseWithBrokenTearDown(TestCase):
1302
1422
            def tearDown(self):
1303
1423
                pass # does not call TestCase.tearDown
1304
1424
            def test_foo(self):
1312
1432
    def test_debug_flags_sanitised(self):
1313
1433
        """The bzrlib debug flags should be sanitised by setUp."""
1314
1434
        if 'allow_debug' in tests.selftest_debug_flags:
1315
 
            raise tests.TestNotApplicable(
 
1435
            raise TestNotApplicable(
1316
1436
                '-Eallow_debug option prevents debug flag sanitisation')
1317
1437
        # we could set something and run a test that will check
1318
1438
        # it gets santised, but this is probably sufficient for now:
1333
1453
        """
1334
1454
        self.change_selftest_debug_flags(set(['allow_debug']))
1335
1455
        bzrlib.debug.debug_flags = set(['a-flag'])
1336
 
        class TestThatRecordsFlags(tests.TestCase):
 
1456
        class TestThatRecordsFlags(TestCase):
1337
1457
            def test_foo(nested_self):
1338
1458
                self.flags = set(bzrlib.debug.debug_flags)
1339
1459
        test = TestThatRecordsFlags('test_foo')
1347
1467
        self.change_selftest_debug_flags(set(['allow_debug']))
1348
1468
        # Now run a test that modifies debug.debug_flags.
1349
1469
        bzrlib.debug.debug_flags = set(['original-state'])
1350
 
        class TestThatModifiesFlags(tests.TestCase):
 
1470
        class TestThatModifiesFlags(TestCase):
1351
1471
            def test_foo(self):
1352
1472
                bzrlib.debug.debug_flags = set(['modified'])
1353
1473
        test = TestThatModifiesFlags('test_foo')
1355
1475
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1356
1476
 
1357
1477
    def make_test_result(self):
1358
 
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
 
1478
        return bzrlib.tests.TextTestResult(
 
1479
            self._log_file, descriptions=0, verbosity=1)
1359
1480
 
1360
1481
    def inner_test(self):
1361
1482
        # the inner child test
1399
1520
        result = bzrlib.tests.VerboseTestResult(
1400
1521
            unittest._WritelnDecorator(output_stream),
1401
1522
            descriptions=0,
1402
 
            verbosity=2)
 
1523
            verbosity=2,
 
1524
            num_tests=sample_test.countTestCases())
1403
1525
        sample_test.run(result)
1404
1526
        self.assertContainsRe(
1405
1527
            output_stream.getvalue(),
1406
 
            r"\d+ms\*\n$")
 
1528
            r"\d+ms/ +\d+ms\n$")
1407
1529
 
1408
1530
    def test_hooks_sanitised(self):
1409
1531
        """The bzrlib hooks should be sanitised by setUp."""
1436
1558
 
1437
1559
    def test_knownFailure(self):
1438
1560
        """Self.knownFailure() should raise a KnownFailure exception."""
1439
 
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
 
1561
        self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
1440
1562
 
1441
1563
    def test_requireFeature_available(self):
1442
1564
        """self.requireFeature(available) is a no-op."""
1443
 
        class Available(tests.Feature):
 
1565
        class Available(Feature):
1444
1566
            def _probe(self):return True
1445
1567
        feature = Available()
1446
1568
        self.requireFeature(feature)
1447
1569
 
1448
1570
    def test_requireFeature_unavailable(self):
1449
1571
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1450
 
        class Unavailable(tests.Feature):
 
1572
        class Unavailable(Feature):
1451
1573
            def _probe(self):return False
1452
1574
        feature = Unavailable()
1453
 
        self.assertRaises(tests.UnavailableFeature,
1454
 
                          self.requireFeature, feature)
 
1575
        self.assertRaises(UnavailableFeature, self.requireFeature, feature)
1455
1576
 
1456
1577
    def test_run_no_parameters(self):
1457
1578
        test = SampleTestCase('_test_pass')
1593
1714
        return sample_deprecated_function()
1594
1715
 
1595
1716
 
1596
 
class TestExtraAssertions(tests.TestCase):
 
1717
class TestExtraAssertions(TestCase):
1597
1718
    """Tests for new test assertions in bzrlib test suite"""
1598
1719
 
1599
1720
    def test_assert_isinstance(self):
1600
1721
        self.assertIsInstance(2, int)
1601
1722
        self.assertIsInstance(u'', basestring)
1602
 
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1603
 
        self.assertEquals(str(e),
1604
 
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
 
1723
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1605
1724
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1606
 
        e = self.assertRaises(AssertionError,
1607
 
            self.assertIsInstance, None, int, "it's just not")
1608
 
        self.assertEquals(str(e),
1609
 
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
1610
 
            ": it's just not")
1611
1725
 
1612
1726
    def test_assertEndsWith(self):
1613
1727
        self.assertEndsWith('foo', 'oo')
1661
1775
        self.callDeprecated([], testfunc, be_deprecated=False)
1662
1776
 
1663
1777
 
1664
 
class TestWarningTests(tests.TestCase):
 
1778
class TestWarningTests(TestCase):
1665
1779
    """Tests for calling methods that raise warnings."""
1666
1780
 
1667
1781
    def test_callCatchWarnings(self):
1677
1791
        self.assertEquals("this is your last warning", str(w0))
1678
1792
 
1679
1793
 
1680
 
class TestConvenienceMakers(tests.TestCaseWithTransport):
 
1794
class TestConvenienceMakers(TestCaseWithTransport):
1681
1795
    """Test for the make_* convenience functions."""
1682
1796
 
1683
1797
    def test_make_branch_and_tree_with_format(self):
1696
1810
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1697
1811
 
1698
1812
 
1699
 
class TestSFTPMakeBranchAndTree(test_sftp_transport.TestCaseWithSFTPServer):
 
1813
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1700
1814
 
1701
1815
    def test_make_tree_for_sftp_branch(self):
1702
1816
        """Transports backed by local directories create local trees."""
1711
1825
                tree.branch.repository.bzrdir.root_transport)
1712
1826
 
1713
1827
 
1714
 
class TestSelftest(tests.TestCase):
 
1828
class TestSelftest(TestCase):
1715
1829
    """Tests of bzrlib.tests.selftest."""
1716
1830
 
1717
1831
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1718
1832
        factory_called = []
1719
1833
        def factory():
1720
1834
            factory_called.append(True)
1721
 
            return TestUtil.TestSuite()
 
1835
            return TestSuite()
1722
1836
        out = StringIO()
1723
1837
        err = StringIO()
1724
1838
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1726
1840
        self.assertEqual([True], factory_called)
1727
1841
 
1728
1842
 
1729
 
class TestKnownFailure(tests.TestCase):
 
1843
class TestKnownFailure(TestCase):
1730
1844
 
1731
1845
    def test_known_failure(self):
1732
1846
        """Check that KnownFailure is defined appropriately."""
1733
1847
        # a KnownFailure is an assertion error for compatability with unaware
1734
1848
        # runners.
1735
 
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
 
1849
        self.assertIsInstance(KnownFailure(""), AssertionError)
1736
1850
 
1737
1851
    def test_expect_failure(self):
1738
1852
        try:
1739
1853
            self.expectFailure("Doomed to failure", self.assertTrue, False)
1740
 
        except tests.KnownFailure, e:
 
1854
        except KnownFailure, e:
1741
1855
            self.assertEqual('Doomed to failure', e.args[0])
1742
1856
        try:
1743
1857
            self.expectFailure("Doomed to failure", self.assertTrue, True)
1748
1862
            self.fail('Assertion not raised')
1749
1863
 
1750
1864
 
1751
 
class TestFeature(tests.TestCase):
 
1865
class TestFeature(TestCase):
1752
1866
 
1753
1867
    def test_caching(self):
1754
1868
        """Feature._probe is called by the feature at most once."""
1755
 
        class InstrumentedFeature(tests.Feature):
 
1869
        class InstrumentedFeature(Feature):
1756
1870
            def __init__(self):
1757
 
                super(InstrumentedFeature, self).__init__()
 
1871
                Feature.__init__(self)
1758
1872
                self.calls = []
1759
1873
            def _probe(self):
1760
1874
                self.calls.append('_probe')
1767
1881
 
1768
1882
    def test_named_str(self):
1769
1883
        """Feature.__str__ should thunk to feature_name()."""
1770
 
        class NamedFeature(tests.Feature):
 
1884
        class NamedFeature(Feature):
1771
1885
            def feature_name(self):
1772
1886
                return 'symlinks'
1773
1887
        feature = NamedFeature()
1775
1889
 
1776
1890
    def test_default_str(self):
1777
1891
        """Feature.__str__ should default to __class__.__name__."""
1778
 
        class NamedFeature(tests.Feature):
 
1892
        class NamedFeature(Feature):
1779
1893
            pass
1780
1894
        feature = NamedFeature()
1781
1895
        self.assertEqual('NamedFeature', str(feature))
1782
1896
 
1783
1897
 
1784
 
class TestUnavailableFeature(tests.TestCase):
 
1898
class TestUnavailableFeature(TestCase):
1785
1899
 
1786
1900
    def test_access_feature(self):
1787
 
        feature = tests.Feature()
1788
 
        exception = tests.UnavailableFeature(feature)
 
1901
        feature = Feature()
 
1902
        exception = UnavailableFeature(feature)
1789
1903
        self.assertIs(feature, exception.args[0])
1790
1904
 
1791
1905
 
1792
 
class TestSelftestFiltering(tests.TestCase):
 
1906
class TestSelftestFiltering(TestCase):
1793
1907
 
1794
1908
    def setUp(self):
1795
 
        tests.TestCase.setUp(self)
 
1909
        TestCase.setUp(self)
1796
1910
        self.suite = TestUtil.TestSuite()
1797
1911
        self.loader = TestUtil.TestLoader()
1798
1912
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
1802
1916
    def test_condition_id_re(self):
1803
1917
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1804
1918
            'test_condition_id_re')
1805
 
        filtered_suite = tests.filter_suite_by_condition(
1806
 
            self.suite, tests.condition_id_re('test_condition_id_re'))
 
1919
        filtered_suite = filter_suite_by_condition(self.suite,
 
1920
            condition_id_re('test_condition_id_re'))
1807
1921
        self.assertEqual([test_name], _test_ids(filtered_suite))
1808
1922
 
1809
1923
    def test_condition_id_in_list(self):
1810
1924
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1811
1925
                      'test_condition_id_in_list']
1812
1926
        id_list = tests.TestIdList(test_names)
1813
 
        filtered_suite = tests.filter_suite_by_condition(
 
1927
        filtered_suite = filter_suite_by_condition(
1814
1928
            self.suite, tests.condition_id_in_list(id_list))
1815
1929
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1816
 
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
 
1930
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
1817
1931
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1818
1932
 
1819
1933
    def test_condition_id_startswith(self):
1823
1937
        test_names = [ klass + 'test_condition_id_in_list',
1824
1938
                      klass + 'test_condition_id_startswith',
1825
1939
                     ]
1826
 
        filtered_suite = tests.filter_suite_by_condition(
 
1940
        filtered_suite = filter_suite_by_condition(
1827
1941
            self.suite, tests.condition_id_startswith([start1, start2]))
1828
1942
        self.assertEqual(test_names, _test_ids(filtered_suite))
1829
1943
 
1830
1944
    def test_condition_isinstance(self):
1831
 
        filtered_suite = tests.filter_suite_by_condition(
1832
 
            self.suite, tests.condition_isinstance(self.__class__))
 
1945
        filtered_suite = filter_suite_by_condition(self.suite,
 
1946
            condition_isinstance(self.__class__))
1833
1947
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1834
 
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
 
1948
        re_filtered = filter_suite_by_re(self.suite, class_pattern)
1835
1949
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1836
1950
 
1837
1951
    def test_exclude_tests_by_condition(self):
1838
1952
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1839
1953
            'test_exclude_tests_by_condition')
1840
 
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
 
1954
        filtered_suite = exclude_tests_by_condition(self.suite,
1841
1955
            lambda x:x.id() == excluded_name)
1842
1956
        self.assertEqual(len(self.all_names) - 1,
1843
1957
            filtered_suite.countTestCases())
1848
1962
 
1849
1963
    def test_exclude_tests_by_re(self):
1850
1964
        self.all_names = _test_ids(self.suite)
1851
 
        filtered_suite = tests.exclude_tests_by_re(self.suite,
1852
 
                                                   'exclude_tests_by_re')
 
1965
        filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
1853
1966
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1854
1967
            'test_exclude_tests_by_re')
1855
1968
        self.assertEqual(len(self.all_names) - 1,
1862
1975
    def test_filter_suite_by_condition(self):
1863
1976
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1864
1977
            'test_filter_suite_by_condition')
1865
 
        filtered_suite = tests.filter_suite_by_condition(self.suite,
 
1978
        filtered_suite = filter_suite_by_condition(self.suite,
1866
1979
            lambda x:x.id() == test_name)
1867
1980
        self.assertEqual([test_name], _test_ids(filtered_suite))
1868
1981
 
1869
1982
    def test_filter_suite_by_re(self):
1870
 
        filtered_suite = tests.filter_suite_by_re(self.suite,
1871
 
                                                  'test_filter_suite_by_r')
 
1983
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
1872
1984
        filtered_names = _test_ids(filtered_suite)
1873
1985
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1874
1986
            'TestSelftestFiltering.test_filter_suite_by_re'])
1902
2014
 
1903
2015
    def test_preserve_input(self):
1904
2016
        # NB: Surely this is something in the stdlib to do this?
1905
 
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
1906
 
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
 
2017
        self.assertTrue(self.suite is preserve_input(self.suite))
 
2018
        self.assertTrue("@#$" is preserve_input("@#$"))
1907
2019
 
1908
2020
    def test_randomize_suite(self):
1909
 
        randomized_suite = tests.randomize_suite(self.suite)
 
2021
        randomized_suite = randomize_suite(self.suite)
1910
2022
        # randomizing should not add or remove test names.
1911
2023
        self.assertEqual(set(_test_ids(self.suite)),
1912
2024
                         set(_test_ids(randomized_suite)))
1922
2034
 
1923
2035
    def test_split_suit_by_condition(self):
1924
2036
        self.all_names = _test_ids(self.suite)
1925
 
        condition = tests.condition_id_re('test_filter_suite_by_r')
1926
 
        split_suite = tests.split_suite_by_condition(self.suite, condition)
 
2037
        condition = condition_id_re('test_filter_suite_by_r')
 
2038
        split_suite = split_suite_by_condition(self.suite, condition)
1927
2039
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1928
2040
            'test_filter_suite_by_re')
1929
2041
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1934
2046
 
1935
2047
    def test_split_suit_by_re(self):
1936
2048
        self.all_names = _test_ids(self.suite)
1937
 
        split_suite = tests.split_suite_by_re(self.suite,
1938
 
                                              'test_filter_suite_by_r')
 
2049
        split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
1939
2050
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1940
2051
            'test_filter_suite_by_re')
1941
2052
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1945
2056
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
1946
2057
 
1947
2058
 
1948
 
class TestCheckInventoryShape(tests.TestCaseWithTransport):
 
2059
class TestCheckInventoryShape(TestCaseWithTransport):
1949
2060
 
1950
2061
    def test_check_inventory_shape(self):
1951
2062
        files = ['a', 'b/', 'b/c']
1959
2070
            tree.unlock()
1960
2071
 
1961
2072
 
1962
 
class TestBlackboxSupport(tests.TestCase):
 
2073
class TestBlackboxSupport(TestCase):
1963
2074
    """Tests for testsuite blackbox features."""
1964
2075
 
1965
2076
    def test_run_bzr_failure_not_caught(self):
1986
2097
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
1987
2098
 
1988
2099
 
1989
 
class TestTestLoader(tests.TestCase):
 
2100
class TestTestLoader(TestCase):
1990
2101
    """Tests for the test loader."""
1991
2102
 
1992
2103
    def _get_loader_and_module(self):
1993
2104
        """Gets a TestLoader and a module with one test in it."""
1994
2105
        loader = TestUtil.TestLoader()
1995
2106
        module = {}
1996
 
        class Stub(tests.TestCase):
 
2107
        class Stub(TestCase):
1997
2108
            def test_foo(self):
1998
2109
                pass
1999
2110
        class MyModule(object):
2012
2123
        # load_tests do not need that :)
2013
2124
        def load_tests(self, standard_tests, module, loader):
2014
2125
            result = loader.suiteClass()
2015
 
            for test in tests.iter_suite_tests(standard_tests):
 
2126
            for test in iter_suite_tests(standard_tests):
2016
2127
                result.addTests([test, test])
2017
2128
            return result
2018
2129
        # add a load_tests() method which multiplies the tests from the module.
2037
2148
 
2038
2149
    def _create_suite(self, test_id_list):
2039
2150
 
2040
 
        class Stub(tests.TestCase):
 
2151
        class Stub(TestCase):
2041
2152
            def test_foo(self):
2042
2153
                pass
2043
2154
 
2053
2164
 
2054
2165
    def _test_ids(self, test_suite):
2055
2166
        """Get the ids for the tests in a test suite."""
2056
 
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
2167
        return [t.id() for t in iter_suite_tests(test_suite)]
2057
2168
 
2058
2169
    def test_empty_list(self):
2059
2170
        id_list = self._create_id_list([])
2085
2196
        self.assertTrue(id_list.refers_to('mod.class'))
2086
2197
        self.assertTrue(id_list.refers_to('mod.class.meth'))
2087
2198
 
 
2199
    def test_test_suite(self):
 
2200
        # This test is slow, so we do a single test with one test in each
 
2201
        # category
 
2202
        test_list = [
 
2203
            # testmod_names
 
2204
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
 
2205
            'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
 
2206
            # transport implementations
 
2207
            'bzrlib.tests.test_transport_implementations.TransportTests'
 
2208
            '.test_abspath(LocalURLServer)',
 
2209
            # modules_to_doctest
 
2210
            'bzrlib.timestamp.format_highres_date',
 
2211
            # plugins can't be tested that way since selftest may be run with
 
2212
            # --no-plugins
 
2213
            ]
 
2214
        suite = tests.test_suite(test_list)
 
2215
        self.assertEquals(test_list, _test_ids(suite))
 
2216
 
2088
2217
    def test_test_suite_matches_id_list_with_unknown(self):
2089
2218
        loader = TestUtil.TestLoader()
2090
2219
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2098
2227
        loader = TestUtil.TestLoader()
2099
2228
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2100
2229
        dupes = loader.suiteClass()
2101
 
        for test in tests.iter_suite_tests(suite):
 
2230
        for test in iter_suite_tests(suite):
2102
2231
            dupes.addTest(test)
2103
2232
            dupes.addTest(test) # Add it again
2104
2233
 
2110
2239
                          duplicates)
2111
2240
 
2112
2241
 
2113
 
class TestTestSuite(tests.TestCase):
2114
 
 
2115
 
    def test_test_suite(self):
2116
 
        # This test is slow, so we do a single test with one test in each
2117
 
        # category
2118
 
        test_list = [
2119
 
            # testmod_names
2120
 
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2121
 
            ('bzrlib.tests.per_transport.TransportTests'
2122
 
             '.test_abspath(LocalURLServer)'),
2123
 
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2124
 
            # modules_to_doctest
2125
 
            'bzrlib.timestamp.format_highres_date',
2126
 
            # plugins can't be tested that way since selftest may be run with
2127
 
            # --no-plugins
2128
 
            ]
2129
 
        suite = tests.test_suite(test_list)
2130
 
        self.assertEquals(test_list, _test_ids(suite))
2131
 
 
2132
 
    def test_test_suite_list_and_start(self):
2133
 
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2134
 
        suite = tests.test_suite(test_list,
2135
 
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
2136
 
        # test_test_suite_list_and_start is not included 
2137
 
        self.assertEquals(test_list, _test_ids(suite))
2138
 
 
2139
 
 
2140
2242
class TestLoadTestIdList(tests.TestCaseInTempDir):
2141
2243
 
2142
2244
    def _create_test_list_file(self, file_name, content):
2265
2367
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2266
2368
 
2267
2369
 
2268
 
class TestRunSuite(tests.TestCase):
 
2370
class TestRunSuite(TestCase):
2269
2371
 
2270
2372
    def test_runner_class(self):
2271
2373
        """run_suite accepts and uses a runner_class keyword argument."""
2272
 
        class Stub(tests.TestCase):
 
2374
        class Stub(TestCase):
2273
2375
            def test_foo(self):
2274
2376
                pass
2275
2377
        suite = Stub("test_foo")
2276
2378
        calls = []
2277
 
        class MyRunner(tests.TextTestRunner):
 
2379
        class MyRunner(TextTestRunner):
2278
2380
            def run(self, test):
2279
2381
                calls.append(test)
2280
 
                return tests.ExtendedTestResult(self.stream, self.descriptions,
2281
 
                                                self.verbosity)
2282
 
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2283
 
        self.assertLength(1, calls)
 
2382
                return ExtendedTestResult(self.stream, self.descriptions,
 
2383
                    self.verbosity)
 
2384
        run_suite(suite, runner_class=MyRunner, stream=StringIO())
 
2385
        self.assertEqual(calls, [suite])
2284
2386
 
2285
2387
    def test_done(self):
2286
2388
        """run_suite should call result.done()"""
2289
2391
        def test_function():
2290
2392
            pass
2291
2393
        test = unittest.FunctionTestCase(test_function)
2292
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
2394
        class InstrumentedTestResult(ExtendedTestResult):
2293
2395
            def done(self): one_more_call()
2294
 
        class MyRunner(tests.TextTestRunner):
 
2396
        class MyRunner(TextTestRunner):
2295
2397
            def run(self, test):
2296
2398
                return InstrumentedTestResult(self.stream, self.descriptions,
2297
2399
                                              self.verbosity)
2298
 
        tests.run_suite(test, runner_class=MyRunner, stream=StringIO())
 
2400
        run_suite(test, runner_class=MyRunner, stream=StringIO())
2299
2401
        self.assertEquals(1, self.calls)