~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

(gz) Fix test failure on alpha by correcting format string for
 gc_chk_sha1_record (Martin [gz])

Show diffs side-by-side

added added

removed removed

Lines of Context:
29
29
from testtools import (
30
30
    ExtendedToOriginalDecorator,
31
31
    MultiTestResult,
32
 
    __version__ as testtools_version,
33
32
    )
34
33
from testtools.content import Content
35
34
from testtools.content_type import ContentType
37
36
    DocTestMatches,
38
37
    Equals,
39
38
    )
40
 
import testtools.testresult.doubles
 
39
import testtools.tests.helpers
41
40
 
42
41
import bzrlib
43
42
from bzrlib import (
44
43
    branchbuilder,
45
44
    bzrdir,
46
45
    errors,
47
 
    hooks,
48
46
    lockdir,
49
47
    memorytree,
50
48
    osutils,
54
52
    tests,
55
53
    transport,
56
54
    workingtree,
57
 
    workingtree_3,
58
 
    workingtree_4,
59
55
    )
60
56
from bzrlib.repofmt import (
61
57
    groupcompress_repo,
94
90
            DocTestMatches(u"...a test message\n", doctest.ELLIPSIS))
95
91
 
96
92
 
 
93
class TestUnicodeFilename(tests.TestCase):
 
94
 
 
95
    def test_probe_passes(self):
 
96
        """UnicodeFilename._probe passes."""
 
97
        # We can't test much more than that because the behaviour depends
 
98
        # on the platform.
 
99
        tests.UnicodeFilename._probe()
 
100
 
 
101
 
97
102
class TestTreeShape(tests.TestCaseInTempDir):
98
103
 
99
104
    def test_unicode_paths(self):
100
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
105
        self.requireFeature(tests.UnicodeFilename)
101
106
 
102
107
        filename = u'hell\u00d8'
103
108
        self.build_tree_contents([(filename, 'contents of hello')])
104
 
        self.assertPathExists(filename)
 
109
        self.failUnlessExists(filename)
105
110
 
106
111
 
107
112
class TestClassesAvailable(tests.TestCase):
333
338
        from bzrlib.tests.per_workingtree import make_scenarios
334
339
        server1 = "a"
335
340
        server2 = "b"
336
 
        formats = [workingtree_4.WorkingTreeFormat4(),
337
 
                   workingtree_3.WorkingTreeFormat3(),]
 
341
        formats = [workingtree.WorkingTreeFormat4(),
 
342
                   workingtree.WorkingTreeFormat3(),]
338
343
        scenarios = make_scenarios(server1, server2, formats)
339
344
        self.assertEqual([
340
345
            ('WorkingTreeFormat4',
370
375
            )
371
376
        server1 = "a"
372
377
        server2 = "b"
373
 
        formats = [workingtree_4.WorkingTreeFormat4(),
374
 
                   workingtree_3.WorkingTreeFormat3(),]
 
378
        formats = [workingtree.WorkingTreeFormat4(),
 
379
                   workingtree.WorkingTreeFormat3(),]
375
380
        scenarios = make_scenarios(server1, server2, formats)
376
381
        self.assertEqual(7, len(scenarios))
377
382
        default_wt_format = workingtree.format_registry.get_default()
378
 
        wt4_format = workingtree_4.WorkingTreeFormat4()
379
 
        wt5_format = workingtree_4.WorkingTreeFormat5()
 
383
        wt4_format = workingtree.WorkingTreeFormat4()
 
384
        wt5_format = workingtree.WorkingTreeFormat5()
380
385
        expected_scenarios = [
381
386
            ('WorkingTreeFormat4',
382
387
             {'bzrdir_format': formats[0]._matchingbzrdir,
448
453
        from bzrlib.tests.per_intertree import (
449
454
            make_scenarios,
450
455
            )
451
 
        from bzrlib.workingtree_3 import WorkingTreeFormat3
452
 
        from bzrlib.workingtree_4 import WorkingTreeFormat4
 
456
        from bzrlib.workingtree import WorkingTreeFormat3, WorkingTreeFormat4
453
457
        input_test = TestInterTreeScenarios(
454
458
            "test_scenarios")
455
459
        server1 = "a"
506
510
        self.assertRaises(AssertionError, self.assertEqualStat,
507
511
            os.lstat("foo"), os.lstat("longname"))
508
512
 
509
 
    def test_failUnlessExists(self):
510
 
        """Deprecated failUnlessExists and failIfExists"""
511
 
        self.applyDeprecated(
512
 
            deprecated_in((2, 4)),
513
 
            self.failUnlessExists, '.')
514
 
        self.build_tree(['foo/', 'foo/bar'])
515
 
        self.applyDeprecated(
516
 
            deprecated_in((2, 4)),
517
 
            self.failUnlessExists, 'foo/bar')
518
 
        self.applyDeprecated(
519
 
            deprecated_in((2, 4)),
520
 
            self.failIfExists, 'foo/foo')
521
 
 
522
 
    def test_assertPathExists(self):
523
 
        self.assertPathExists('.')
524
 
        self.build_tree(['foo/', 'foo/bar'])
525
 
        self.assertPathExists('foo/bar')
526
 
        self.assertPathDoesNotExist('foo/foo')
527
 
 
528
513
 
529
514
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
530
515
 
564
549
        tree = self.make_branch_and_memory_tree('dir')
565
550
        # Guard against regression into MemoryTransport leaking
566
551
        # files to disk instead of keeping them in memory.
567
 
        self.assertFalse(osutils.lexists('dir'))
 
552
        self.failIf(osutils.lexists('dir'))
568
553
        self.assertIsInstance(tree, memorytree.MemoryTree)
569
554
 
570
555
    def test_make_branch_and_memory_tree_with_format(self):
574
559
        tree = self.make_branch_and_memory_tree('dir', format=format)
575
560
        # Guard against regression into MemoryTransport leaking
576
561
        # files to disk instead of keeping them in memory.
577
 
        self.assertFalse(osutils.lexists('dir'))
 
562
        self.failIf(osutils.lexists('dir'))
578
563
        self.assertIsInstance(tree, memorytree.MemoryTree)
579
564
        self.assertEqual(format.repository_format.__class__,
580
565
            tree.branch.repository._format.__class__)
584
569
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
585
570
        # Guard against regression into MemoryTransport leaking
586
571
        # files to disk instead of keeping them in memory.
587
 
        self.assertFalse(osutils.lexists('dir'))
 
572
        self.failIf(osutils.lexists('dir'))
588
573
 
589
574
    def test_make_branch_builder_with_format(self):
590
575
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
596
581
        the_branch = builder.get_branch()
597
582
        # Guard against regression into MemoryTransport leaking
598
583
        # files to disk instead of keeping them in memory.
599
 
        self.assertFalse(osutils.lexists('dir'))
 
584
        self.failIf(osutils.lexists('dir'))
600
585
        self.assertEqual(format.repository_format.__class__,
601
586
                         the_branch.repository._format.__class__)
602
587
        self.assertEqual(repo_format.get_format_string(),
608
593
        the_branch = builder.get_branch()
609
594
        # Guard against regression into MemoryTransport leaking
610
595
        # files to disk instead of keeping them in memory.
611
 
        self.assertFalse(osutils.lexists('dir'))
 
596
        self.failIf(osutils.lexists('dir'))
612
597
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
613
598
        self.assertEqual(dir_format.repository_format.__class__,
614
599
                         the_branch.repository._format.__class__)
619
604
    def test_dangling_locks_cause_failures(self):
620
605
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
621
606
            def test_function(self):
622
 
                t = self.get_transport_from_path('.')
 
607
                t = self.get_transport('.')
623
608
                l = lockdir.LockDir(t, 'lock')
624
609
                l.create()
625
610
                l.attempt_lock()
645
630
        # for the server
646
631
        url = self.get_readonly_url()
647
632
        url2 = self.get_readonly_url('foo/bar')
648
 
        t = transport.get_transport_from_url(url)
649
 
        t2 = transport.get_transport_from_url(url2)
650
 
        self.assertIsInstance(t, ReadonlyTransportDecorator)
651
 
        self.assertIsInstance(t2, ReadonlyTransportDecorator)
 
633
        t = transport.get_transport(url)
 
634
        t2 = transport.get_transport(url2)
 
635
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
 
636
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
652
637
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
653
638
 
654
639
    def test_get_readonly_url_http(self):
660
645
        url = self.get_readonly_url()
661
646
        url2 = self.get_readonly_url('foo/bar')
662
647
        # the transport returned may be any HttpTransportBase subclass
663
 
        t = transport.get_transport_from_url(url)
664
 
        t2 = transport.get_transport_from_url(url2)
665
 
        self.assertIsInstance(t, HttpTransportBase)
666
 
        self.assertIsInstance(t2, HttpTransportBase)
 
648
        t = transport.get_transport(url)
 
649
        t2 = transport.get_transport(url2)
 
650
        self.failUnless(isinstance(t, HttpTransportBase))
 
651
        self.failUnless(isinstance(t2, HttpTransportBase))
667
652
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
668
653
 
669
654
    def test_is_directory(self):
677
662
    def test_make_branch_builder(self):
678
663
        builder = self.make_branch_builder('dir')
679
664
        rev_id = builder.build_commit()
680
 
        self.assertPathExists('dir')
 
665
        self.failUnlessExists('dir')
681
666
        a_dir = bzrdir.BzrDir.open('dir')
682
667
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
683
668
        a_branch = a_dir.open_branch()
699
684
        self.assertIsInstance(result_bzrdir.transport,
700
685
                              memory.MemoryTransport)
701
686
        # should not be on disk, should only be in memory
702
 
        self.assertPathDoesNotExist('subdir')
 
687
        self.failIfExists('subdir')
703
688
 
704
689
 
705
690
class TestChrootedTest(tests.ChrootedTestCase):
706
691
 
707
692
    def test_root_is_root(self):
708
 
        t = transport.get_transport_from_url(self.get_readonly_url())
 
693
        t = transport.get_transport(self.get_readonly_url())
709
694
        url = t.base
710
695
        self.assertEqual(url, t.clone('..').base)
711
696
 
713
698
class TestProfileResult(tests.TestCase):
714
699
 
715
700
    def test_profiles_tests(self):
716
 
        self.requireFeature(features.lsprof_feature)
717
 
        terminal = testtools.testresult.doubles.ExtendedTestResult()
 
701
        self.requireFeature(test_lsprof.LSProfFeature)
 
702
        terminal = testtools.tests.helpers.ExtendedTestResult()
718
703
        result = tests.ProfileResult(terminal)
719
704
        class Sample(tests.TestCase):
720
705
            def a(self):
737
722
                descriptions=0,
738
723
                verbosity=1,
739
724
                )
740
 
        capture = testtools.testresult.doubles.ExtendedTestResult()
 
725
        capture = testtools.tests.helpers.ExtendedTestResult()
741
726
        test_case.run(MultiTestResult(result, capture))
742
727
        run_case = capture._events[0][1]
743
728
        timed_string = result._testTimeString(run_case)
764
749
        self.check_timing(ShortDelayTestCase('test_short_delay'),
765
750
                          r"^ +[0-9]+ms$")
766
751
 
 
752
    def _patch_get_bzr_source_tree(self):
 
753
        # Reading from the actual source tree breaks isolation, but we don't
 
754
        # want to assume that thats *all* that would happen.
 
755
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', lambda: None)
 
756
 
 
757
    def test_assigned_benchmark_file_stores_date(self):
 
758
        self._patch_get_bzr_source_tree()
 
759
        output = StringIO()
 
760
        result = bzrlib.tests.TextTestResult(self._log_file,
 
761
                                        descriptions=0,
 
762
                                        verbosity=1,
 
763
                                        bench_history=output
 
764
                                        )
 
765
        output_string = output.getvalue()
 
766
        # if you are wondering about the regexp please read the comment in
 
767
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
768
        # XXX: what comment?  -- Andrew Bennetts
 
769
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
770
 
 
771
    def test_benchhistory_records_test_times(self):
 
772
        self._patch_get_bzr_source_tree()
 
773
        result_stream = StringIO()
 
774
        result = bzrlib.tests.TextTestResult(
 
775
            self._log_file,
 
776
            descriptions=0,
 
777
            verbosity=1,
 
778
            bench_history=result_stream
 
779
            )
 
780
 
 
781
        # we want profile a call and check that its test duration is recorded
 
782
        # make a new test instance that when run will generate a benchmark
 
783
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
784
        # execute the test, which should succeed and record times
 
785
        example_test_case.run(result)
 
786
        lines = result_stream.getvalue().splitlines()
 
787
        self.assertEqual(2, len(lines))
 
788
        self.assertContainsRe(lines[1],
 
789
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
790
            "._time_hello_world_encoding")
 
791
 
767
792
    def _time_hello_world_encoding(self):
768
793
        """Profile two sleep calls
769
794
 
774
799
 
775
800
    def test_lsprofiling(self):
776
801
        """Verbose test result prints lsprof statistics from test cases."""
777
 
        self.requireFeature(features.lsprof_feature)
 
802
        self.requireFeature(test_lsprof.LSProfFeature)
778
803
        result_stream = StringIO()
779
804
        result = bzrlib.tests.VerboseTestResult(
780
805
            result_stream,
825
850
        self.assertEndsWith(sio.getvalue(), "OK    50002ms\n")
826
851
 
827
852
    def test_known_failure(self):
828
 
        """Using knownFailure should trigger several result actions."""
 
853
        """A KnownFailure being raised should trigger several result actions."""
829
854
        class InstrumentedTestResult(tests.ExtendedTestResult):
830
855
            def stopTestRun(self): pass
831
856
            def report_tests_starting(self): pass
834
859
        result = InstrumentedTestResult(None, None, None, None)
835
860
        class Test(tests.TestCase):
836
861
            def test_function(self):
837
 
                self.knownFailure('failed!')
 
862
                raise tests.KnownFailure('failed!')
838
863
        test = Test("test_function")
839
864
        test.run(result)
840
865
        # it should invoke 'report_known_failure'.
856
881
            descriptions=0,
857
882
            verbosity=2,
858
883
            )
859
 
        _get_test("test_xfail").run(result)
860
 
        self.assertContainsRe(result_stream.getvalue(),
861
 
            "\n\\S+\\.test_xfail\\s+XFAIL\\s+\\d+ms\n"
862
 
            "\\s*(?:Text attachment: )?reason"
863
 
            "(?:\n-+\n|: {{{)"
864
 
            "this_fails"
865
 
            "(?:\n-+\n|}}}\n)")
 
884
        test = self.get_passing_test()
 
885
        result.startTest(test)
 
886
        prefix = len(result_stream.getvalue())
 
887
        # the err parameter has the shape:
 
888
        # (class, exception object, traceback)
 
889
        # KnownFailures dont get their tracebacks shown though, so we
 
890
        # can skip that.
 
891
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
892
        result.report_known_failure(test, err)
 
893
        output = result_stream.getvalue()[prefix:]
 
894
        lines = output.splitlines()
 
895
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
 
896
        if sys.version_info > (2, 7):
 
897
            self.expectFailure("_ExpectedFailure on 2.7 loses the message",
 
898
                self.assertNotEqual, lines[1], '    ')
 
899
        self.assertEqual(lines[1], '    foo')
 
900
        self.assertEqual(2, len(lines))
866
901
 
867
902
    def get_passing_test(self):
868
903
        """Return a test object that can't be run usefully."""
879
914
                self._call = test, feature
880
915
        result = InstrumentedTestResult(None, None, None, None)
881
916
        test = SampleTestCase('_test_pass')
882
 
        feature = features.Feature()
 
917
        feature = tests.Feature()
883
918
        result.startTest(test)
884
919
        result.addNotSupported(test, feature)
885
920
        # it should invoke 'report_unsupported'.
904
939
            verbosity=2,
905
940
            )
906
941
        test = self.get_passing_test()
907
 
        feature = features.Feature()
 
942
        feature = tests.Feature()
908
943
        result.startTest(test)
909
944
        prefix = len(result_stream.getvalue())
910
945
        result.report_unsupported(test, feature)
923
958
            def addNotSupported(self, test, feature):
924
959
                self._call = test, feature
925
960
        result = InstrumentedTestResult(None, None, None, None)
926
 
        feature = features.Feature()
 
961
        feature = tests.Feature()
927
962
        class Test(tests.TestCase):
928
963
            def test_function(self):
929
964
                raise tests.UnavailableFeature(feature)
948
983
    def test_strict_with_known_failure(self):
949
984
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
950
985
                                             verbosity=1)
951
 
        test = _get_test("test_xfail")
952
 
        test.run(result)
 
986
        test = self.get_passing_test()
 
987
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
988
        result.addExpectedFailure(test, err)
953
989
        self.assertFalse(result.wasStrictlySuccessful())
954
990
        self.assertEqual(None, result._extractBenchmarkTime(test))
955
991
 
987
1023
        self.assertEquals(2, result.count)
988
1024
 
989
1025
 
 
1026
class TestUnicodeFilenameFeature(tests.TestCase):
 
1027
 
 
1028
    def test_probe_passes(self):
 
1029
        """UnicodeFilenameFeature._probe passes."""
 
1030
        # We can't test much more than that because the behaviour depends
 
1031
        # on the platform.
 
1032
        tests.UnicodeFilenameFeature._probe()
 
1033
 
 
1034
 
990
1035
class TestRunner(tests.TestCase):
991
1036
 
992
1037
    def dummy_test(self):
1018
1063
        test = unittest.TestSuite()
1019
1064
        test.addTest(Test("known_failure_test"))
1020
1065
        def failing_test():
1021
 
            raise AssertionError('foo')
 
1066
            self.fail('foo')
1022
1067
        test.addTest(unittest.FunctionTestCase(failing_test))
1023
1068
        stream = StringIO()
1024
1069
        runner = tests.TextTestRunner(stream=stream)
1032
1077
            '^----------------------------------------------------------------------\n'
1033
1078
            'Traceback \\(most recent call last\\):\n'
1034
1079
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1035
 
            '    raise AssertionError\\(\'foo\'\\)\n'
 
1080
            '    self.fail\\(\'foo\'\\)\n'
1036
1081
            '.*'
1037
1082
            '^----------------------------------------------------------------------\n'
1038
1083
            '.*'
1044
1089
        # the final output.
1045
1090
        class Test(tests.TestCase):
1046
1091
            def known_failure_test(self):
1047
 
                self.knownFailure("Never works...")
 
1092
                self.expectFailure('failed', self.assertTrue, False)
1048
1093
        test = Test("known_failure_test")
1049
1094
        stream = StringIO()
1050
1095
        runner = tests.TextTestRunner(stream=stream)
1056
1101
            '\n'
1057
1102
            'OK \\(known_failures=1\\)\n')
1058
1103
 
1059
 
    def test_unexpected_success_bad(self):
1060
 
        class Test(tests.TestCase):
1061
 
            def test_truth(self):
1062
 
                self.expectFailure("No absolute truth", self.assertTrue, True)
1063
 
        runner = tests.TextTestRunner(stream=StringIO())
1064
 
        result = self.run_test_runner(runner, Test("test_truth"))
1065
 
        if testtools_version[:3] <= (0, 9, 11):
1066
 
            self.assertContainsRe(runner.stream.getvalue(),
1067
 
                "=+\n"
1068
 
                "FAIL: \\S+\.test_truth\n"
1069
 
                "-+\n"
1070
 
                "(?:.*\n)*"
1071
 
                "No absolute truth\n"
1072
 
                "(?:.*\n)*"
1073
 
                "-+\n"
1074
 
                "Ran 1 test in .*\n"
1075
 
                "\n"
1076
 
                "FAILED \\(failures=1\\)\n\\Z")
1077
 
        else:
1078
 
            self.assertContainsRe(runner.stream.getvalue(),
1079
 
                "=+\n"
1080
 
                "FAIL: \\S+\.test_truth\n"
1081
 
                "-+\n"
1082
 
                "Empty attachments:\n"
1083
 
                "  log\n"
1084
 
                "\n"
1085
 
                "reason: {{{No absolute truth}}}\n"
1086
 
                "-+\n"
1087
 
                "Ran 1 test in .*\n"
1088
 
                "\n"
1089
 
                "FAILED \\(failures=1\\)\n\\Z")
1090
 
 
1091
1104
    def test_result_decorator(self):
1092
1105
        # decorate results
1093
1106
        calls = []
1177
1190
 
1178
1191
    def test_unsupported_features_listed(self):
1179
1192
        """When unsupported features are encountered they are detailed."""
1180
 
        class Feature1(features.Feature):
 
1193
        class Feature1(tests.Feature):
1181
1194
            def _probe(self): return False
1182
 
        class Feature2(features.Feature):
 
1195
        class Feature2(tests.Feature):
1183
1196
            def _probe(self): return False
1184
1197
        # create sample tests
1185
1198
        test1 = SampleTestCase('_test_pass')
1200
1213
            ],
1201
1214
            lines[-3:])
1202
1215
 
 
1216
    def _patch_get_bzr_source_tree(self):
 
1217
        # Reading from the actual source tree breaks isolation, but we don't
 
1218
        # want to assume that thats *all* that would happen.
 
1219
        self._get_source_tree_calls = []
 
1220
        def new_get():
 
1221
            self._get_source_tree_calls.append("called")
 
1222
            return None
 
1223
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree',  new_get)
 
1224
 
 
1225
    def test_bench_history(self):
 
1226
        # tests that the running the benchmark passes bench_history into
 
1227
        # the test result object. We can tell that happens if
 
1228
        # _get_bzr_source_tree is called.
 
1229
        self._patch_get_bzr_source_tree()
 
1230
        test = TestRunner('dummy_test')
 
1231
        output = StringIO()
 
1232
        runner = tests.TextTestRunner(stream=self._log_file,
 
1233
                                      bench_history=output)
 
1234
        result = self.run_test_runner(runner, test)
 
1235
        output_string = output.getvalue()
 
1236
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
1237
        self.assertLength(1, self._get_source_tree_calls)
 
1238
 
1203
1239
    def test_verbose_test_count(self):
1204
1240
        """A verbose test run reports the right test count at the start"""
1205
1241
        suite = TestUtil.TestSuite([
1251
1287
            lambda trace=False: "ascii")
1252
1288
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
1253
1289
            FailureWithUnicode("test_log_unicode"))
1254
 
        if testtools_version[:3] > (0, 9, 11):
1255
 
            self.assertContainsRe(out.getvalue(), "log: {{{\d+\.\d+  \\\\u2606}}}")
1256
 
        else:
1257
 
            self.assertContainsRe(out.getvalue(),
1258
 
                "Text attachment: log\n"
1259
 
                "-+\n"
1260
 
                "\d+\.\d+  \\\\u2606\n"
1261
 
                "-+\n")
 
1290
        self.assertContainsRe(out.getvalue(),
 
1291
            "Text attachment: log\n"
 
1292
            "-+\n"
 
1293
            "\d+\.\d+  \\\\u2606\n"
 
1294
            "-+\n")
1262
1295
 
1263
1296
 
1264
1297
class SampleTestCase(tests.TestCase):
1453
1486
        # Note this test won't fail with hooks that the core library doesn't
1454
1487
        # use - but it trigger with a plugin that adds hooks, so its still a
1455
1488
        # useful warning in that case.
1456
 
        self.assertEqual(bzrlib.branch.BranchHooks(), bzrlib.branch.Branch.hooks)
1457
 
        self.assertEqual(
1458
 
            bzrlib.smart.server.SmartServerHooks(),
 
1489
        self.assertEqual(bzrlib.branch.BranchHooks(),
 
1490
            bzrlib.branch.Branch.hooks)
 
1491
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1459
1492
            bzrlib.smart.server.SmartTCPServer.hooks)
1460
 
        self.assertEqual(
1461
 
            bzrlib.commands.CommandHooks(), bzrlib.commands.Command.hooks)
 
1493
        self.assertEqual(bzrlib.commands.CommandHooks(),
 
1494
            bzrlib.commands.Command.hooks)
1462
1495
 
1463
1496
    def test__gather_lsprof_in_benchmarks(self):
1464
1497
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1465
1498
 
1466
1499
        Each self.time() call is individually and separately profiled.
1467
1500
        """
1468
 
        self.requireFeature(features.lsprof_feature)
 
1501
        self.requireFeature(test_lsprof.LSProfFeature)
1469
1502
        # overrides the class member with an instance member so no cleanup
1470
1503
        # needed.
1471
1504
        self._gather_lsprof_in_benchmarks = True
1490
1523
        transport_server = memory.MemoryServer()
1491
1524
        transport_server.start_server()
1492
1525
        self.addCleanup(transport_server.stop_server)
1493
 
        t = transport.get_transport_from_url(transport_server.get_url())
 
1526
        t = transport.get_transport(transport_server.get_url())
1494
1527
        bzrdir.BzrDir.create(t.base)
1495
1528
        self.assertRaises(errors.BzrError,
1496
1529
            bzrdir.BzrDir.open_from_transport, t)
1501
1534
 
1502
1535
    def test_requireFeature_available(self):
1503
1536
        """self.requireFeature(available) is a no-op."""
1504
 
        class Available(features.Feature):
 
1537
        class Available(tests.Feature):
1505
1538
            def _probe(self):return True
1506
1539
        feature = Available()
1507
1540
        self.requireFeature(feature)
1508
1541
 
1509
1542
    def test_requireFeature_unavailable(self):
1510
1543
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1511
 
        class Unavailable(features.Feature):
 
1544
        class Unavailable(tests.Feature):
1512
1545
            def _probe(self):return False
1513
1546
        feature = Unavailable()
1514
1547
        self.assertRaises(tests.UnavailableFeature,
1673
1706
        test.run(unittest.TestResult())
1674
1707
        self.assertEqual('original', obj.test_attr)
1675
1708
 
1676
 
    def test_recordCalls(self):
1677
 
        from bzrlib.tests import test_selftest
1678
 
        calls = self.recordCalls(
1679
 
            test_selftest, '_add_numbers')
1680
 
        self.assertEqual(test_selftest._add_numbers(2, 10),
1681
 
            12)
1682
 
        self.assertEquals(calls, [((2, 10), {})])
1683
 
 
1684
 
 
1685
 
def _add_numbers(a, b):
1686
 
    return a + b
1687
 
 
1688
 
 
1689
 
class _MissingFeature(features.Feature):
 
1709
 
 
1710
class _MissingFeature(tests.Feature):
1690
1711
    def _probe(self):
1691
1712
        return False
1692
1713
missing_feature = _MissingFeature()
1743
1764
        result = self._run_test('test_fail')
1744
1765
        self.assertEqual(1, len(result.failures))
1745
1766
        result_content = result.failures[0][1]
1746
 
        if testtools_version < (0, 9, 12):
1747
 
            self.assertContainsRe(result_content, 'Text attachment: log')
 
1767
        self.assertContainsRe(result_content, 'Text attachment: log')
1748
1768
        self.assertContainsRe(result_content, 'this was a failing test')
1749
1769
 
1750
1770
    def test_error_has_log(self):
1751
1771
        result = self._run_test('test_error')
1752
1772
        self.assertEqual(1, len(result.errors))
1753
1773
        result_content = result.errors[0][1]
1754
 
        if testtools_version < (0, 9, 12):
1755
 
            self.assertContainsRe(result_content, 'Text attachment: log')
 
1774
        self.assertContainsRe(result_content, 'Text attachment: log')
1756
1775
        self.assertContainsRe(result_content, 'this test errored')
1757
1776
 
1758
1777
    def test_skip_has_no_log(self):
2040
2059
        self.assertLength(2, output.readlines())
2041
2060
 
2042
2061
    def test_lsprof_tests(self):
2043
 
        self.requireFeature(features.lsprof_feature)
2044
 
        results = []
 
2062
        self.requireFeature(test_lsprof.LSProfFeature)
 
2063
        calls = []
2045
2064
        class Test(object):
2046
2065
            def __call__(test, result):
2047
2066
                test.run(result)
2048
2067
            def run(test, result):
2049
 
                results.append(result)
 
2068
                self.assertIsInstance(result, ExtendedToOriginalDecorator)
 
2069
                calls.append("called")
2050
2070
            def countTestCases(self):
2051
2071
                return 1
2052
2072
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
2053
 
        self.assertLength(1, results)
2054
 
        self.assertIsInstance(results.pop(), ExtendedToOriginalDecorator)
 
2073
        self.assertLength(1, calls)
2055
2074
 
2056
2075
    def test_random(self):
2057
2076
        # test randomising by listing a number of tests.
2199
2218
        content, result = self.run_subunit_stream('test_unexpected_success')
2200
2219
        self.assertContainsRe(content, '(?m)^log$')
2201
2220
        self.assertContainsRe(content, 'test with unexpected success')
2202
 
        # GZ 2011-05-18: Old versions of subunit treat unexpected success as a
2203
 
        #                success, if a min version check is added remove this
2204
 
        from subunit import TestProtocolClient as _Client
2205
 
        if _Client.addUnexpectedSuccess.im_func is _Client.addSuccess.im_func:
2206
 
            self.expectFailure('subunit treats "unexpectedSuccess"'
2207
 
                               ' as a plain success',
2208
 
                self.assertEqual, 1, len(result.unexpectedSuccesses))
 
2221
        self.expectFailure('subunit treats "unexpectedSuccess"'
 
2222
                           ' as a plain success',
 
2223
            self.assertEqual, 1, len(result.unexpectedSuccesses))
2209
2224
        self.assertEqual(1, len(result.unexpectedSuccesses))
2210
2225
        test = result.unexpectedSuccesses[0]
2211
2226
        # RemotedTestCase doesn't preserve the "details"
2346
2361
        # stdout and stderr of the invoked run_bzr
2347
2362
        current_factory = bzrlib.ui.ui_factory
2348
2363
        self.run_bzr(['foo'])
2349
 
        self.assertFalse(current_factory is self.factory)
 
2364
        self.failIf(current_factory is self.factory)
2350
2365
        self.assertNotEqual(sys.stdout, self.factory.stdout)
2351
2366
        self.assertNotEqual(sys.stderr, self.factory.stderr)
2352
2367
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
2509
2524
 
2510
2525
 
2511
2526
class TestStartBzrSubProcess(tests.TestCase):
2512
 
    """Stub test start_bzr_subprocess."""
2513
2527
 
2514
 
    def _subprocess_log_cleanup(self):
2515
 
        """Inhibits the base version as we don't produce a log file."""
 
2528
    def check_popen_state(self):
 
2529
        """Replace to make assertions when popen is called."""
2516
2530
 
2517
2531
    def _popen(self, *args, **kwargs):
2518
 
        """Override the base version to record the command that is run.
2519
 
 
2520
 
        From there we can ensure it is correct without spawning a real process.
2521
 
        """
 
2532
        """Record the command that is run, so that we can ensure it is correct"""
2522
2533
        self.check_popen_state()
2523
2534
        self._popen_args = args
2524
2535
        self._popen_kwargs = kwargs
2525
2536
        raise _DontSpawnProcess()
2526
2537
 
2527
 
    def check_popen_state(self):
2528
 
        """Replace to make assertions when popen is called."""
2529
 
 
2530
2538
    def test_run_bzr_subprocess_no_plugins(self):
2531
2539
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2532
2540
        command = self._popen_args[0]
2536
2544
 
2537
2545
    def test_allow_plugins(self):
2538
2546
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2539
 
                          allow_plugins=True)
 
2547
            allow_plugins=True)
2540
2548
        command = self._popen_args[0]
2541
2549
        self.assertEqual([], command[2:])
2542
2550
 
2543
2551
    def test_set_env(self):
2544
 
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2552
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
2545
2553
        # set in the child
2546
2554
        def check_environment():
2547
2555
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2548
2556
        self.check_popen_state = check_environment
2549
2557
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2550
 
                          env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2558
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
2551
2559
        # not set in theparent
2552
2560
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2553
2561
 
2554
2562
    def test_run_bzr_subprocess_env_del(self):
2555
2563
        """run_bzr_subprocess can remove environment variables too."""
2556
 
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2564
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
2557
2565
        def check_environment():
2558
2566
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2559
2567
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2560
2568
        self.check_popen_state = check_environment
2561
2569
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2562
 
                          env_changes={'EXISTANT_ENV_VAR':None})
 
2570
            env_changes={'EXISTANT_ENV_VAR':None})
2563
2571
        # Still set in parent
2564
2572
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2565
2573
        del os.environ['EXISTANT_ENV_VAR']
2566
2574
 
2567
2575
    def test_env_del_missing(self):
2568
 
        self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
 
2576
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2569
2577
        def check_environment():
2570
2578
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2571
2579
        self.check_popen_state = check_environment
2572
2580
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2573
 
                          env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2581
            env_changes={'NON_EXISTANT_ENV_VAR':None})
2574
2582
 
2575
2583
    def test_working_dir(self):
2576
2584
        """Test that we can specify the working dir for the child"""
2579
2587
        chdirs = []
2580
2588
        def chdir(path):
2581
2589
            chdirs.append(path)
2582
 
        self.overrideAttr(os, 'chdir', chdir)
2583
 
        def getcwd():
2584
 
            return 'current'
2585
 
        self.overrideAttr(osutils, 'getcwd', getcwd)
2586
 
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2587
 
                          working_dir='foo')
 
2590
        os.chdir = chdir
 
2591
        try:
 
2592
            def getcwd():
 
2593
                return 'current'
 
2594
            osutils.getcwd = getcwd
 
2595
            try:
 
2596
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2597
                    working_dir='foo')
 
2598
            finally:
 
2599
                osutils.getcwd = orig_getcwd
 
2600
        finally:
 
2601
            os.chdir = orig_chdir
2588
2602
        self.assertEqual(['foo', 'current'], chdirs)
2589
2603
 
2590
2604
    def test_get_bzr_path_with_cwd_bzrlib(self):
2610
2624
        self.assertEqual('bzr: interrupted\n', result[1])
2611
2625
 
2612
2626
 
 
2627
class TestFeature(tests.TestCase):
 
2628
 
 
2629
    def test_caching(self):
 
2630
        """Feature._probe is called by the feature at most once."""
 
2631
        class InstrumentedFeature(tests.Feature):
 
2632
            def __init__(self):
 
2633
                super(InstrumentedFeature, self).__init__()
 
2634
                self.calls = []
 
2635
            def _probe(self):
 
2636
                self.calls.append('_probe')
 
2637
                return False
 
2638
        feature = InstrumentedFeature()
 
2639
        feature.available()
 
2640
        self.assertEqual(['_probe'], feature.calls)
 
2641
        feature.available()
 
2642
        self.assertEqual(['_probe'], feature.calls)
 
2643
 
 
2644
    def test_named_str(self):
 
2645
        """Feature.__str__ should thunk to feature_name()."""
 
2646
        class NamedFeature(tests.Feature):
 
2647
            def feature_name(self):
 
2648
                return 'symlinks'
 
2649
        feature = NamedFeature()
 
2650
        self.assertEqual('symlinks', str(feature))
 
2651
 
 
2652
    def test_default_str(self):
 
2653
        """Feature.__str__ should default to __class__.__name__."""
 
2654
        class NamedFeature(tests.Feature):
 
2655
            pass
 
2656
        feature = NamedFeature()
 
2657
        self.assertEqual('NamedFeature', str(feature))
 
2658
 
 
2659
 
 
2660
class TestUnavailableFeature(tests.TestCase):
 
2661
 
 
2662
    def test_access_feature(self):
 
2663
        feature = tests.Feature()
 
2664
        exception = tests.UnavailableFeature(feature)
 
2665
        self.assertIs(feature, exception.args[0])
 
2666
 
 
2667
 
 
2668
simple_thunk_feature = tests._CompatabilityThunkFeature(
 
2669
    deprecated_in((2, 1, 0)),
 
2670
    'bzrlib.tests.test_selftest',
 
2671
    'simple_thunk_feature','UnicodeFilename',
 
2672
    replacement_module='bzrlib.tests'
 
2673
    )
 
2674
 
 
2675
class Test_CompatibilityFeature(tests.TestCase):
 
2676
 
 
2677
    def test_does_thunk(self):
 
2678
        res = self.callDeprecated(
 
2679
            ['bzrlib.tests.test_selftest.simple_thunk_feature was deprecated'
 
2680
             ' in version 2.1.0. Use bzrlib.tests.UnicodeFilename instead.'],
 
2681
            simple_thunk_feature.available)
 
2682
        self.assertEqual(tests.UnicodeFilename.available(), res)
 
2683
 
 
2684
 
 
2685
class TestModuleAvailableFeature(tests.TestCase):
 
2686
 
 
2687
    def test_available_module(self):
 
2688
        feature = tests.ModuleAvailableFeature('bzrlib.tests')
 
2689
        self.assertEqual('bzrlib.tests', feature.module_name)
 
2690
        self.assertEqual('bzrlib.tests', str(feature))
 
2691
        self.assertTrue(feature.available())
 
2692
        self.assertIs(tests, feature.module)
 
2693
 
 
2694
    def test_unavailable_module(self):
 
2695
        feature = tests.ModuleAvailableFeature('bzrlib.no_such_module_exists')
 
2696
        self.assertEqual('bzrlib.no_such_module_exists', str(feature))
 
2697
        self.assertFalse(feature.available())
 
2698
        self.assertIs(None, feature.module)
 
2699
 
 
2700
 
2613
2701
class TestSelftestFiltering(tests.TestCase):
2614
2702
 
2615
2703
    def setUp(self):
2766
2854
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2767
2855
 
2768
2856
 
2769
 
class TestCheckTreeShape(tests.TestCaseWithTransport):
 
2857
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2770
2858
 
2771
 
    def test_check_tree_shape(self):
 
2859
    def test_check_inventory_shape(self):
2772
2860
        files = ['a', 'b/', 'b/c']
2773
2861
        tree = self.make_branch_and_tree('.')
2774
2862
        self.build_tree(files)
2775
2863
        tree.add(files)
2776
2864
        tree.lock_read()
2777
2865
        try:
2778
 
            self.check_tree_shape(tree, files)
 
2866
            self.check_inventory_shape(tree.inventory, files)
2779
2867
        finally:
2780
2868
            tree.unlock()
2781
2869
 
3317
3405
class TestEnvironHandling(tests.TestCase):
3318
3406
 
3319
3407
    def test_overrideEnv_None_called_twice_doesnt_leak(self):
3320
 
        self.assertFalse('MYVAR' in os.environ)
 
3408
        self.failIf('MYVAR' in os.environ)
3321
3409
        self.overrideEnv('MYVAR', '42')
3322
3410
        # We use an embedded test to make sure we fix the _captureVar bug
3323
3411
        class Test(tests.TestCase):
3453
3541
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
3454
3542
        # tests.DocTestSuite sees None
3455
3543
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
3456
 
 
3457
 
 
3458
 
class TestSelftestExcludePatterns(tests.TestCase):
3459
 
 
3460
 
    def setUp(self):
3461
 
        super(TestSelftestExcludePatterns, self).setUp()
3462
 
        self.overrideAttr(tests, 'test_suite', self.suite_factory)
3463
 
 
3464
 
    def suite_factory(self, keep_only=None, starting_with=None):
3465
 
        """A test suite factory with only a few tests."""
3466
 
        class Test(tests.TestCase):
3467
 
            def id(self):
3468
 
                # We don't need the full class path
3469
 
                return self._testMethodName
3470
 
            def a(self):
3471
 
                pass
3472
 
            def b(self):
3473
 
                pass
3474
 
            def c(self):
3475
 
                pass
3476
 
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
3477
 
 
3478
 
    def assertTestList(self, expected, *selftest_args):
3479
 
        # We rely on setUp installing the right test suite factory so we can
3480
 
        # test at the command level without loading the whole test suite
3481
 
        out, err = self.run_bzr(('selftest', '--list') + selftest_args)
3482
 
        actual = out.splitlines()
3483
 
        self.assertEquals(expected, actual)
3484
 
 
3485
 
    def test_full_list(self):
3486
 
        self.assertTestList(['a', 'b', 'c'])
3487
 
 
3488
 
    def test_single_exclude(self):
3489
 
        self.assertTestList(['b', 'c'], '-x', 'a')
3490
 
 
3491
 
    def test_mutiple_excludes(self):
3492
 
        self.assertTestList(['c'], '-x', 'a', '-x', 'b')
3493
 
 
3494
 
 
3495
 
class TestCounterHooks(tests.TestCase, SelfTestHelper):
3496
 
 
3497
 
    _test_needs_features = [features.subunit]
3498
 
 
3499
 
    def setUp(self):
3500
 
        super(TestCounterHooks, self).setUp()
3501
 
        class Test(tests.TestCase):
3502
 
 
3503
 
            def setUp(self):
3504
 
                super(Test, self).setUp()
3505
 
                self.hooks = hooks.Hooks()
3506
 
                self.hooks.add_hook('myhook', 'Foo bar blah', (2,4))
3507
 
                self.install_counter_hook(self.hooks, 'myhook')
3508
 
 
3509
 
            def no_hook(self):
3510
 
                pass
3511
 
 
3512
 
            def run_hook_once(self):
3513
 
                for hook in self.hooks['myhook']:
3514
 
                    hook(self)
3515
 
 
3516
 
        self.test_class = Test
3517
 
 
3518
 
    def assertHookCalls(self, expected_calls, test_name):
3519
 
        test = self.test_class(test_name)
3520
 
        result = unittest.TestResult()
3521
 
        test.run(result)
3522
 
        self.assertTrue(hasattr(test, '_counters'))
3523
 
        self.assertTrue(test._counters.has_key('myhook'))
3524
 
        self.assertEquals(expected_calls, test._counters['myhook'])
3525
 
 
3526
 
    def test_no_hook(self):
3527
 
        self.assertHookCalls(0, 'no_hook')
3528
 
 
3529
 
    def test_run_hook_once(self):
3530
 
        tt = features.testtools
3531
 
        if tt.module.__version__ < (0, 9, 8):
3532
 
            raise tests.TestSkipped('testtools-0.9.8 required for addDetail')
3533
 
        self.assertHookCalls(1, 'run_hook_once')