~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Zearin
  • Date: 2010-11-12 22:36:19 UTC
  • mto: (5570.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5572.
  • Revision ID: zearin@users.sourceforge.net-20101112223619-1i2oscfgg1xgzuqk
Continued capitalization fixes ([S]FTP, SSH).

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
"""Tests for the test framework."""
18
18
 
19
19
from cStringIO import StringIO
20
 
import doctest
 
20
from doctest import ELLIPSIS
21
21
import os
22
22
import signal
23
23
import sys
36
36
    DocTestMatches,
37
37
    Equals,
38
38
    )
39
 
import testtools.testresult.doubles
 
39
import testtools.tests.helpers
40
40
 
41
41
import bzrlib
42
42
from bzrlib import (
43
43
    branchbuilder,
44
44
    bzrdir,
 
45
    debug,
45
46
    errors,
46
 
    hooks,
47
47
    lockdir,
48
48
    memorytree,
49
49
    osutils,
53
53
    tests,
54
54
    transport,
55
55
    workingtree,
56
 
    workingtree_3,
57
 
    workingtree_4,
58
56
    )
59
57
from bzrlib.repofmt import (
60
58
    groupcompress_repo,
 
59
    pack_repo,
 
60
    weaverepo,
61
61
    )
62
62
from bzrlib.symbol_versioning import (
63
63
    deprecated_function,
68
68
    features,
69
69
    test_lsprof,
70
70
    test_server,
 
71
    test_sftp_transport,
71
72
    TestUtil,
72
73
    )
73
74
from bzrlib.trace import note, mutter
74
75
from bzrlib.transport import memory
 
76
from bzrlib.version import _get_bzr_source_tree
75
77
 
76
78
 
77
79
def _test_ids(test_suite):
90
92
            "text", "plain", {"charset": "utf8"})))
91
93
        self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
92
94
        self.assertThat(self.get_log(),
93
 
            DocTestMatches(u"...a test message\n", doctest.ELLIPSIS))
 
95
            DocTestMatches(u"...a test message\n", ELLIPSIS))
94
96
 
95
97
 
96
98
class TestUnicodeFilename(tests.TestCase):
109
111
 
110
112
        filename = u'hell\u00d8'
111
113
        self.build_tree_contents([(filename, 'contents of hello')])
112
 
        self.assertPathExists(filename)
 
114
        self.failUnlessExists(filename)
113
115
 
114
116
 
115
117
class TestClassesAvailable(tests.TestCase):
341
343
        from bzrlib.tests.per_workingtree import make_scenarios
342
344
        server1 = "a"
343
345
        server2 = "b"
344
 
        formats = [workingtree_4.WorkingTreeFormat4(),
345
 
                   workingtree_3.WorkingTreeFormat3(),]
 
346
        formats = [workingtree.WorkingTreeFormat2(),
 
347
                   workingtree.WorkingTreeFormat3(),]
346
348
        scenarios = make_scenarios(server1, server2, formats)
347
349
        self.assertEqual([
348
 
            ('WorkingTreeFormat4',
 
350
            ('WorkingTreeFormat2',
349
351
             {'bzrdir_format': formats[0]._matchingbzrdir,
350
352
              'transport_readonly_server': 'b',
351
353
              'transport_server': 'a',
378
380
            )
379
381
        server1 = "a"
380
382
        server2 = "b"
381
 
        formats = [workingtree_4.WorkingTreeFormat4(),
382
 
                   workingtree_3.WorkingTreeFormat3(),]
 
383
        formats = [workingtree.WorkingTreeFormat2(),
 
384
                   workingtree.WorkingTreeFormat3(),]
383
385
        scenarios = make_scenarios(server1, server2, formats)
384
386
        self.assertEqual(7, len(scenarios))
385
 
        default_wt_format = workingtree.format_registry.get_default()
386
 
        wt4_format = workingtree_4.WorkingTreeFormat4()
387
 
        wt5_format = workingtree_4.WorkingTreeFormat5()
 
387
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
 
388
        wt4_format = workingtree.WorkingTreeFormat4()
 
389
        wt5_format = workingtree.WorkingTreeFormat5()
388
390
        expected_scenarios = [
389
 
            ('WorkingTreeFormat4',
 
391
            ('WorkingTreeFormat2',
390
392
             {'bzrdir_format': formats[0]._matchingbzrdir,
391
393
              'transport_readonly_server': 'b',
392
394
              'transport_server': 'a',
452
454
        # ones to add.
453
455
        from bzrlib.tests.per_tree import (
454
456
            return_parameter,
 
457
            revision_tree_from_workingtree
455
458
            )
456
459
        from bzrlib.tests.per_intertree import (
457
460
            make_scenarios,
458
461
            )
459
 
        from bzrlib.workingtree_3 import WorkingTreeFormat3
460
 
        from bzrlib.workingtree_4 import WorkingTreeFormat4
 
462
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
461
463
        input_test = TestInterTreeScenarios(
462
464
            "test_scenarios")
463
465
        server1 = "a"
464
466
        server2 = "b"
465
 
        format1 = WorkingTreeFormat4()
 
467
        format1 = WorkingTreeFormat2()
466
468
        format2 = WorkingTreeFormat3()
467
469
        formats = [("1", str, format1, format2, "converter1"),
468
470
            ("2", int, format2, format1, "converter2")]
514
516
        self.assertRaises(AssertionError, self.assertEqualStat,
515
517
            os.lstat("foo"), os.lstat("longname"))
516
518
 
517
 
    def test_failUnlessExists(self):
518
 
        """Deprecated failUnlessExists and failIfExists"""
519
 
        self.applyDeprecated(
520
 
            deprecated_in((2, 4)),
521
 
            self.failUnlessExists, '.')
522
 
        self.build_tree(['foo/', 'foo/bar'])
523
 
        self.applyDeprecated(
524
 
            deprecated_in((2, 4)),
525
 
            self.failUnlessExists, 'foo/bar')
526
 
        self.applyDeprecated(
527
 
            deprecated_in((2, 4)),
528
 
            self.failIfExists, 'foo/foo')
529
 
 
530
 
    def test_assertPathExists(self):
531
 
        self.assertPathExists('.')
532
 
        self.build_tree(['foo/', 'foo/bar'])
533
 
        self.assertPathExists('foo/bar')
534
 
        self.assertPathDoesNotExist('foo/foo')
535
 
 
536
519
 
537
520
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
538
521
 
572
555
        tree = self.make_branch_and_memory_tree('dir')
573
556
        # Guard against regression into MemoryTransport leaking
574
557
        # files to disk instead of keeping them in memory.
575
 
        self.assertFalse(osutils.lexists('dir'))
 
558
        self.failIf(osutils.lexists('dir'))
576
559
        self.assertIsInstance(tree, memorytree.MemoryTree)
577
560
 
578
561
    def test_make_branch_and_memory_tree_with_format(self):
579
562
        """make_branch_and_memory_tree should accept a format option."""
580
563
        format = bzrdir.BzrDirMetaFormat1()
581
 
        format.repository_format = repository.format_registry.get_default()
 
564
        format.repository_format = weaverepo.RepositoryFormat7()
582
565
        tree = self.make_branch_and_memory_tree('dir', format=format)
583
566
        # Guard against regression into MemoryTransport leaking
584
567
        # files to disk instead of keeping them in memory.
585
 
        self.assertFalse(osutils.lexists('dir'))
 
568
        self.failIf(osutils.lexists('dir'))
586
569
        self.assertIsInstance(tree, memorytree.MemoryTree)
587
570
        self.assertEqual(format.repository_format.__class__,
588
571
            tree.branch.repository._format.__class__)
592
575
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
593
576
        # Guard against regression into MemoryTransport leaking
594
577
        # files to disk instead of keeping them in memory.
595
 
        self.assertFalse(osutils.lexists('dir'))
 
578
        self.failIf(osutils.lexists('dir'))
596
579
 
597
580
    def test_make_branch_builder_with_format(self):
598
581
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
599
582
        # that the format objects are used.
600
583
        format = bzrdir.BzrDirMetaFormat1()
601
 
        repo_format = repository.format_registry.get_default()
 
584
        repo_format = weaverepo.RepositoryFormat7()
602
585
        format.repository_format = repo_format
603
586
        builder = self.make_branch_builder('dir', format=format)
604
587
        the_branch = builder.get_branch()
605
588
        # Guard against regression into MemoryTransport leaking
606
589
        # files to disk instead of keeping them in memory.
607
 
        self.assertFalse(osutils.lexists('dir'))
 
590
        self.failIf(osutils.lexists('dir'))
608
591
        self.assertEqual(format.repository_format.__class__,
609
592
                         the_branch.repository._format.__class__)
610
593
        self.assertEqual(repo_format.get_format_string(),
616
599
        the_branch = builder.get_branch()
617
600
        # Guard against regression into MemoryTransport leaking
618
601
        # files to disk instead of keeping them in memory.
619
 
        self.assertFalse(osutils.lexists('dir'))
 
602
        self.failIf(osutils.lexists('dir'))
620
603
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
621
604
        self.assertEqual(dir_format.repository_format.__class__,
622
605
                         the_branch.repository._format.__class__)
655
638
        url2 = self.get_readonly_url('foo/bar')
656
639
        t = transport.get_transport(url)
657
640
        t2 = transport.get_transport(url2)
658
 
        self.assertIsInstance(t, ReadonlyTransportDecorator)
659
 
        self.assertIsInstance(t2, ReadonlyTransportDecorator)
 
641
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
 
642
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
660
643
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
661
644
 
662
645
    def test_get_readonly_url_http(self):
670
653
        # the transport returned may be any HttpTransportBase subclass
671
654
        t = transport.get_transport(url)
672
655
        t2 = transport.get_transport(url2)
673
 
        self.assertIsInstance(t, HttpTransportBase)
674
 
        self.assertIsInstance(t2, HttpTransportBase)
 
656
        self.failUnless(isinstance(t, HttpTransportBase))
 
657
        self.failUnless(isinstance(t2, HttpTransportBase))
675
658
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
676
659
 
677
660
    def test_is_directory(self):
685
668
    def test_make_branch_builder(self):
686
669
        builder = self.make_branch_builder('dir')
687
670
        rev_id = builder.build_commit()
688
 
        self.assertPathExists('dir')
 
671
        self.failUnlessExists('dir')
689
672
        a_dir = bzrdir.BzrDir.open('dir')
690
673
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
691
674
        a_branch = a_dir.open_branch()
707
690
        self.assertIsInstance(result_bzrdir.transport,
708
691
                              memory.MemoryTransport)
709
692
        # should not be on disk, should only be in memory
710
 
        self.assertPathDoesNotExist('subdir')
 
693
        self.failIfExists('subdir')
711
694
 
712
695
 
713
696
class TestChrootedTest(tests.ChrootedTestCase):
722
705
 
723
706
    def test_profiles_tests(self):
724
707
        self.requireFeature(test_lsprof.LSProfFeature)
725
 
        terminal = testtools.testresult.doubles.ExtendedTestResult()
 
708
        terminal = testtools.tests.helpers.ExtendedTestResult()
726
709
        result = tests.ProfileResult(terminal)
727
710
        class Sample(tests.TestCase):
728
711
            def a(self):
745
728
                descriptions=0,
746
729
                verbosity=1,
747
730
                )
748
 
        capture = testtools.testresult.doubles.ExtendedTestResult()
 
731
        capture = testtools.tests.helpers.ExtendedTestResult()
749
732
        test_case.run(MultiTestResult(result, capture))
750
733
        run_case = capture._events[0][1]
751
734
        timed_string = result._testTimeString(run_case)
772
755
        self.check_timing(ShortDelayTestCase('test_short_delay'),
773
756
                          r"^ +[0-9]+ms$")
774
757
 
 
758
    def _patch_get_bzr_source_tree(self):
 
759
        # Reading from the actual source tree breaks isolation, but we don't
 
760
        # want to assume that thats *all* that would happen.
 
761
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', lambda: None)
 
762
 
 
763
    def test_assigned_benchmark_file_stores_date(self):
 
764
        self._patch_get_bzr_source_tree()
 
765
        output = StringIO()
 
766
        result = bzrlib.tests.TextTestResult(self._log_file,
 
767
                                        descriptions=0,
 
768
                                        verbosity=1,
 
769
                                        bench_history=output
 
770
                                        )
 
771
        output_string = output.getvalue()
 
772
        # if you are wondering about the regexp please read the comment in
 
773
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
774
        # XXX: what comment?  -- Andrew Bennetts
 
775
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
776
 
 
777
    def test_benchhistory_records_test_times(self):
 
778
        self._patch_get_bzr_source_tree()
 
779
        result_stream = StringIO()
 
780
        result = bzrlib.tests.TextTestResult(
 
781
            self._log_file,
 
782
            descriptions=0,
 
783
            verbosity=1,
 
784
            bench_history=result_stream
 
785
            )
 
786
 
 
787
        # we want profile a call and check that its test duration is recorded
 
788
        # make a new test instance that when run will generate a benchmark
 
789
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
790
        # execute the test, which should succeed and record times
 
791
        example_test_case.run(result)
 
792
        lines = result_stream.getvalue().splitlines()
 
793
        self.assertEqual(2, len(lines))
 
794
        self.assertContainsRe(lines[1],
 
795
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
796
            "._time_hello_world_encoding")
 
797
 
775
798
    def _time_hello_world_encoding(self):
776
799
        """Profile two sleep calls
777
800
 
1046
1069
        test = unittest.TestSuite()
1047
1070
        test.addTest(Test("known_failure_test"))
1048
1071
        def failing_test():
1049
 
            raise AssertionError('foo')
 
1072
            self.fail('foo')
1050
1073
        test.addTest(unittest.FunctionTestCase(failing_test))
1051
1074
        stream = StringIO()
1052
1075
        runner = tests.TextTestRunner(stream=stream)
1060
1083
            '^----------------------------------------------------------------------\n'
1061
1084
            'Traceback \\(most recent call last\\):\n'
1062
1085
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1063
 
            '    raise AssertionError\\(\'foo\'\\)\n'
 
1086
            '    self.fail\\(\'foo\'\\)\n'
1064
1087
            '.*'
1065
1088
            '^----------------------------------------------------------------------\n'
1066
1089
            '.*'
1072
1095
        # the final output.
1073
1096
        class Test(tests.TestCase):
1074
1097
            def known_failure_test(self):
1075
 
                self.knownFailure("Never works...")
 
1098
                self.expectFailure('failed', self.assertTrue, False)
1076
1099
        test = Test("known_failure_test")
1077
1100
        stream = StringIO()
1078
1101
        runner = tests.TextTestRunner(stream=stream)
1084
1107
            '\n'
1085
1108
            'OK \\(known_failures=1\\)\n')
1086
1109
 
1087
 
    def test_unexpected_success_bad(self):
1088
 
        class Test(tests.TestCase):
1089
 
            def test_truth(self):
1090
 
                self.expectFailure("No absolute truth", self.assertTrue, True)
1091
 
        runner = tests.TextTestRunner(stream=StringIO())
1092
 
        result = self.run_test_runner(runner, Test("test_truth"))
1093
 
        self.assertContainsRe(runner.stream.getvalue(),
1094
 
            "=+\n"
1095
 
            "FAIL: \\S+\.test_truth\n"
1096
 
            "-+\n"
1097
 
            "(?:.*\n)*"
1098
 
            "No absolute truth\n"
1099
 
            "(?:.*\n)*"
1100
 
            "-+\n"
1101
 
            "Ran 1 test in .*\n"
1102
 
            "\n"
1103
 
            "FAILED \\(failures=1\\)\n\\Z")
1104
 
 
1105
1110
    def test_result_decorator(self):
1106
1111
        # decorate results
1107
1112
        calls = []
1214
1219
            ],
1215
1220
            lines[-3:])
1216
1221
 
 
1222
    def _patch_get_bzr_source_tree(self):
 
1223
        # Reading from the actual source tree breaks isolation, but we don't
 
1224
        # want to assume that thats *all* that would happen.
 
1225
        self._get_source_tree_calls = []
 
1226
        def new_get():
 
1227
            self._get_source_tree_calls.append("called")
 
1228
            return None
 
1229
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree',  new_get)
 
1230
 
 
1231
    def test_bench_history(self):
 
1232
        # tests that the running the benchmark passes bench_history into
 
1233
        # the test result object. We can tell that happens if
 
1234
        # _get_bzr_source_tree is called.
 
1235
        self._patch_get_bzr_source_tree()
 
1236
        test = TestRunner('dummy_test')
 
1237
        output = StringIO()
 
1238
        runner = tests.TextTestRunner(stream=self._log_file,
 
1239
                                      bench_history=output)
 
1240
        result = self.run_test_runner(runner, test)
 
1241
        output_string = output.getvalue()
 
1242
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
1243
        self.assertLength(1, self._get_source_tree_calls)
 
1244
 
1217
1245
    def test_verbose_test_count(self):
1218
1246
        """A verbose test run reports the right test count at the start"""
1219
1247
        suite = TestUtil.TestSuite([
1254
1282
        result = self.run_test_runner(runner, test)
1255
1283
        self.assertLength(1, calls)
1256
1284
 
1257
 
    def test_unicode_test_output_on_ascii_stream(self):
1258
 
        """Showing results should always succeed even on an ascii console"""
1259
 
        class FailureWithUnicode(tests.TestCase):
1260
 
            def test_log_unicode(self):
1261
 
                self.log(u"\u2606")
1262
 
                self.fail("Now print that log!")
1263
 
        out = StringIO()
1264
 
        self.overrideAttr(osutils, "get_terminal_encoding",
1265
 
            lambda trace=False: "ascii")
1266
 
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
1267
 
            FailureWithUnicode("test_log_unicode"))
1268
 
        self.assertContainsRe(out.getvalue(),
1269
 
            "Text attachment: log\n"
1270
 
            "-+\n"
1271
 
            "\d+\.\d+  \\\\u2606\n"
1272
 
            "-+\n")
1273
 
 
1274
1285
 
1275
1286
class SampleTestCase(tests.TestCase):
1276
1287
 
1464
1475
        # Note this test won't fail with hooks that the core library doesn't
1465
1476
        # use - but it trigger with a plugin that adds hooks, so its still a
1466
1477
        # useful warning in that case.
1467
 
        self.assertEqual(bzrlib.branch.BranchHooks(), bzrlib.branch.Branch.hooks)
1468
 
        self.assertEqual(
1469
 
            bzrlib.smart.server.SmartServerHooks(),
 
1478
        self.assertEqual(bzrlib.branch.BranchHooks(),
 
1479
            bzrlib.branch.Branch.hooks)
 
1480
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1470
1481
            bzrlib.smart.server.SmartTCPServer.hooks)
1471
 
        self.assertEqual(
1472
 
            bzrlib.commands.CommandHooks(), bzrlib.commands.Command.hooks)
 
1482
        self.assertEqual(bzrlib.commands.CommandHooks(),
 
1483
            bzrlib.commands.Command.hooks)
1473
1484
 
1474
1485
    def test__gather_lsprof_in_benchmarks(self):
1475
1486
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1953
1964
    def test_make_branch_and_tree_with_format(self):
1954
1965
        # we should be able to supply a format to make_branch_and_tree
1955
1966
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
 
1967
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1956
1968
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1957
1969
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
1970
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
 
1971
                              bzrlib.bzrdir.BzrDirFormat6)
1958
1972
 
1959
1973
    def test_make_branch_and_memory_tree(self):
1960
1974
        # we should be able to get a new branch and a mutable tree from
2038
2052
 
2039
2053
    def test_lsprof_tests(self):
2040
2054
        self.requireFeature(test_lsprof.LSProfFeature)
2041
 
        results = []
 
2055
        calls = []
2042
2056
        class Test(object):
2043
2057
            def __call__(test, result):
2044
2058
                test.run(result)
2045
2059
            def run(test, result):
2046
 
                results.append(result)
 
2060
                self.assertIsInstance(result, ExtendedToOriginalDecorator)
 
2061
                calls.append("called")
2047
2062
            def countTestCases(self):
2048
2063
                return 1
2049
2064
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
2050
 
        self.assertLength(1, results)
2051
 
        self.assertIsInstance(results.pop(), ExtendedToOriginalDecorator)
 
2065
        self.assertLength(1, calls)
2052
2066
 
2053
2067
    def test_random(self):
2054
2068
        # test randomising by listing a number of tests.
2196
2210
        content, result = self.run_subunit_stream('test_unexpected_success')
2197
2211
        self.assertContainsRe(content, '(?m)^log$')
2198
2212
        self.assertContainsRe(content, 'test with unexpected success')
2199
 
        # GZ 2011-05-18: Old versions of subunit treat unexpected success as a
2200
 
        #                success, if a min version check is added remove this
2201
 
        from subunit import TestProtocolClient as _Client
2202
 
        if _Client.addUnexpectedSuccess.im_func is _Client.addSuccess.im_func:
2203
 
            self.expectFailure('subunit treats "unexpectedSuccess"'
2204
 
                               ' as a plain success',
2205
 
                self.assertEqual, 1, len(result.unexpectedSuccesses))
 
2213
        self.expectFailure('subunit treats "unexpectedSuccess"'
 
2214
                           ' as a plain success',
 
2215
            self.assertEqual, 1, len(result.unexpectedSuccesses))
2206
2216
        self.assertEqual(1, len(result.unexpectedSuccesses))
2207
2217
        test = result.unexpectedSuccesses[0]
2208
2218
        # RemotedTestCase doesn't preserve the "details"
2343
2353
        # stdout and stderr of the invoked run_bzr
2344
2354
        current_factory = bzrlib.ui.ui_factory
2345
2355
        self.run_bzr(['foo'])
2346
 
        self.assertFalse(current_factory is self.factory)
 
2356
        self.failIf(current_factory is self.factory)
2347
2357
        self.assertNotEqual(sys.stdout, self.factory.stdout)
2348
2358
        self.assertNotEqual(sys.stderr, self.factory.stderr)
2349
2359
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
2506
2516
 
2507
2517
 
2508
2518
class TestStartBzrSubProcess(tests.TestCase):
2509
 
    """Stub test start_bzr_subprocess."""
2510
2519
 
2511
 
    def _subprocess_log_cleanup(self):
2512
 
        """Inhibits the base version as we don't produce a log file."""
 
2520
    def check_popen_state(self):
 
2521
        """Replace to make assertions when popen is called."""
2513
2522
 
2514
2523
    def _popen(self, *args, **kwargs):
2515
 
        """Override the base version to record the command that is run.
2516
 
 
2517
 
        From there we can ensure it is correct without spawning a real process.
2518
 
        """
 
2524
        """Record the command that is run, so that we can ensure it is correct"""
2519
2525
        self.check_popen_state()
2520
2526
        self._popen_args = args
2521
2527
        self._popen_kwargs = kwargs
2522
2528
        raise _DontSpawnProcess()
2523
2529
 
2524
 
    def check_popen_state(self):
2525
 
        """Replace to make assertions when popen is called."""
2526
 
 
2527
2530
    def test_run_bzr_subprocess_no_plugins(self):
2528
2531
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2529
2532
        command = self._popen_args[0]
2533
2536
 
2534
2537
    def test_allow_plugins(self):
2535
2538
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2536
 
                          allow_plugins=True)
 
2539
            allow_plugins=True)
2537
2540
        command = self._popen_args[0]
2538
2541
        self.assertEqual([], command[2:])
2539
2542
 
2540
2543
    def test_set_env(self):
2541
 
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2544
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
2542
2545
        # set in the child
2543
2546
        def check_environment():
2544
2547
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2545
2548
        self.check_popen_state = check_environment
2546
2549
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2547
 
                          env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2550
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
2548
2551
        # not set in theparent
2549
2552
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2550
2553
 
2551
2554
    def test_run_bzr_subprocess_env_del(self):
2552
2555
        """run_bzr_subprocess can remove environment variables too."""
2553
 
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2556
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
2554
2557
        def check_environment():
2555
2558
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2556
2559
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2557
2560
        self.check_popen_state = check_environment
2558
2561
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2559
 
                          env_changes={'EXISTANT_ENV_VAR':None})
 
2562
            env_changes={'EXISTANT_ENV_VAR':None})
2560
2563
        # Still set in parent
2561
2564
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2562
2565
        del os.environ['EXISTANT_ENV_VAR']
2563
2566
 
2564
2567
    def test_env_del_missing(self):
2565
 
        self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
 
2568
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2566
2569
        def check_environment():
2567
2570
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2568
2571
        self.check_popen_state = check_environment
2569
2572
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2570
 
                          env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2573
            env_changes={'NON_EXISTANT_ENV_VAR':None})
2571
2574
 
2572
2575
    def test_working_dir(self):
2573
2576
        """Test that we can specify the working dir for the child"""
2576
2579
        chdirs = []
2577
2580
        def chdir(path):
2578
2581
            chdirs.append(path)
2579
 
        self.overrideAttr(os, 'chdir', chdir)
2580
 
        def getcwd():
2581
 
            return 'current'
2582
 
        self.overrideAttr(osutils, 'getcwd', getcwd)
2583
 
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2584
 
                          working_dir='foo')
 
2582
        os.chdir = chdir
 
2583
        try:
 
2584
            def getcwd():
 
2585
                return 'current'
 
2586
            osutils.getcwd = getcwd
 
2587
            try:
 
2588
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2589
                    working_dir='foo')
 
2590
            finally:
 
2591
                osutils.getcwd = orig_getcwd
 
2592
        finally:
 
2593
            os.chdir = orig_chdir
2585
2594
        self.assertEqual(['foo', 'current'], chdirs)
2586
2595
 
2587
2596
    def test_get_bzr_path_with_cwd_bzrlib(self):
2837
2846
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2838
2847
 
2839
2848
 
2840
 
class TestCheckTreeShape(tests.TestCaseWithTransport):
 
2849
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2841
2850
 
2842
 
    def test_check_tree_shape(self):
 
2851
    def test_check_inventory_shape(self):
2843
2852
        files = ['a', 'b/', 'b/c']
2844
2853
        tree = self.make_branch_and_tree('.')
2845
2854
        self.build_tree(files)
2846
2855
        tree.add(files)
2847
2856
        tree.lock_read()
2848
2857
        try:
2849
 
            self.check_tree_shape(tree, files)
 
2858
            self.check_inventory_shape(tree.inventory, files)
2850
2859
        finally:
2851
2860
            tree.unlock()
2852
2861
 
3184
3193
        tpr.register('bar', 'bBB.aAA.rRR')
3185
3194
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
3186
3195
        self.assertThat(self.get_log(),
3187
 
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR",
3188
 
                           doctest.ELLIPSIS))
 
3196
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR", ELLIPSIS))
3189
3197
 
3190
3198
    def test_get_unknown_prefix(self):
3191
3199
        tpr = self._get_registry()
3226
3234
        class Test(unittest.TestCase):
3227
3235
            def runTest(self):
3228
3236
                pass
 
3237
            addCleanup = None # for when on Python 2.7 with native addCleanup
3229
3238
        result = self.LeakRecordingResult()
3230
3239
        test = Test()
 
3240
        self.assertIs(getattr(test, "addCleanup", None), None)
3231
3241
        result.startTestRun()
3232
3242
        test.run(result)
3233
3243
        result.stopTestRun()
3360
3370
        result = tests.ExtendedTestResult(StringIO(), 0, 1)
3361
3371
        post_mortem_calls = []
3362
3372
        self.overrideAttr(pdb, "post_mortem", post_mortem_calls.append)
3363
 
        self.overrideEnv('BZR_TEST_PDB', None)
 
3373
        self.addCleanup(osutils.set_or_unset_env, "BZR_TEST_PDB",
 
3374
            osutils.set_or_unset_env("BZR_TEST_PDB", None))
3364
3375
        result._post_mortem(1)
3365
 
        self.overrideEnv('BZR_TEST_PDB', 'on')
 
3376
        os.environ["BZR_TEST_PDB"] = "on"
3366
3377
        result._post_mortem(2)
3367
3378
        self.assertEqual([2], post_mortem_calls)
3368
3379
 
3383
3394
                                                self.verbosity)
3384
3395
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
3385
3396
        self.assertLength(1, calls)
3386
 
 
3387
 
 
3388
 
class TestEnvironHandling(tests.TestCase):
3389
 
 
3390
 
    def test_overrideEnv_None_called_twice_doesnt_leak(self):
3391
 
        self.assertFalse('MYVAR' in os.environ)
3392
 
        self.overrideEnv('MYVAR', '42')
3393
 
        # We use an embedded test to make sure we fix the _captureVar bug
3394
 
        class Test(tests.TestCase):
3395
 
            def test_me(self):
3396
 
                # The first call save the 42 value
3397
 
                self.overrideEnv('MYVAR', None)
3398
 
                self.assertEquals(None, os.environ.get('MYVAR'))
3399
 
                # Make sure we can call it twice
3400
 
                self.overrideEnv('MYVAR', None)
3401
 
                self.assertEquals(None, os.environ.get('MYVAR'))
3402
 
        output = StringIO()
3403
 
        result = tests.TextTestResult(output, 0, 1)
3404
 
        Test('test_me').run(result)
3405
 
        if not result.wasStrictlySuccessful():
3406
 
            self.fail(output.getvalue())
3407
 
        # We get our value back
3408
 
        self.assertEquals('42', os.environ.get('MYVAR'))
3409
 
 
3410
 
 
3411
 
class TestIsolatedEnv(tests.TestCase):
3412
 
    """Test isolating tests from os.environ.
3413
 
 
3414
 
    Since we use tests that are already isolated from os.environ a bit of care
3415
 
    should be taken when designing the tests to avoid bootstrap side-effects.
3416
 
    The tests start an already clean os.environ which allow doing valid
3417
 
    assertions about which variables are present or not and design tests around
3418
 
    these assertions.
3419
 
    """
3420
 
 
3421
 
    class ScratchMonkey(tests.TestCase):
3422
 
 
3423
 
        def test_me(self):
3424
 
            pass
3425
 
 
3426
 
    def test_basics(self):
3427
 
        # Make sure we know the definition of BZR_HOME: not part of os.environ
3428
 
        # for tests.TestCase.
3429
 
        self.assertTrue('BZR_HOME' in tests.isolated_environ)
3430
 
        self.assertEquals(None, tests.isolated_environ['BZR_HOME'])
3431
 
        # Being part of isolated_environ, BZR_HOME should not appear here
3432
 
        self.assertFalse('BZR_HOME' in os.environ)
3433
 
        # Make sure we know the definition of LINES: part of os.environ for
3434
 
        # tests.TestCase
3435
 
        self.assertTrue('LINES' in tests.isolated_environ)
3436
 
        self.assertEquals('25', tests.isolated_environ['LINES'])
3437
 
        self.assertEquals('25', os.environ['LINES'])
3438
 
 
3439
 
    def test_injecting_unknown_variable(self):
3440
 
        # BZR_HOME is known to be absent from os.environ
3441
 
        test = self.ScratchMonkey('test_me')
3442
 
        tests.override_os_environ(test, {'BZR_HOME': 'foo'})
3443
 
        self.assertEquals('foo', os.environ['BZR_HOME'])
3444
 
        tests.restore_os_environ(test)
3445
 
        self.assertFalse('BZR_HOME' in os.environ)
3446
 
 
3447
 
    def test_injecting_known_variable(self):
3448
 
        test = self.ScratchMonkey('test_me')
3449
 
        # LINES is known to be present in os.environ
3450
 
        tests.override_os_environ(test, {'LINES': '42'})
3451
 
        self.assertEquals('42', os.environ['LINES'])
3452
 
        tests.restore_os_environ(test)
3453
 
        self.assertEquals('25', os.environ['LINES'])
3454
 
 
3455
 
    def test_deleting_variable(self):
3456
 
        test = self.ScratchMonkey('test_me')
3457
 
        # LINES is known to be present in os.environ
3458
 
        tests.override_os_environ(test, {'LINES': None})
3459
 
        self.assertTrue('LINES' not in os.environ)
3460
 
        tests.restore_os_environ(test)
3461
 
        self.assertEquals('25', os.environ['LINES'])
3462
 
 
3463
 
 
3464
 
class TestDocTestSuiteIsolation(tests.TestCase):
3465
 
    """Test that `tests.DocTestSuite` isolates doc tests from os.environ.
3466
 
 
3467
 
    Since tests.TestCase alreay provides an isolation from os.environ, we use
3468
 
    the clean environment as a base for testing. To precisely capture the
3469
 
    isolation provided by tests.DocTestSuite, we use doctest.DocTestSuite to
3470
 
    compare against.
3471
 
 
3472
 
    We want to make sure `tests.DocTestSuite` respect `tests.isolated_environ`,
3473
 
    not `os.environ` so each test overrides it to suit its needs.
3474
 
 
3475
 
    """
3476
 
 
3477
 
    def get_doctest_suite_for_string(self, klass, string):
3478
 
        class Finder(doctest.DocTestFinder):
3479
 
 
3480
 
            def find(*args, **kwargs):
3481
 
                test = doctest.DocTestParser().get_doctest(
3482
 
                    string, {}, 'foo', 'foo.py', 0)
3483
 
                return [test]
3484
 
 
3485
 
        suite = klass(test_finder=Finder())
3486
 
        return suite
3487
 
 
3488
 
    def run_doctest_suite_for_string(self, klass, string):
3489
 
        suite = self.get_doctest_suite_for_string(klass, string)
3490
 
        output = StringIO()
3491
 
        result = tests.TextTestResult(output, 0, 1)
3492
 
        suite.run(result)
3493
 
        return result, output
3494
 
 
3495
 
    def assertDocTestStringSucceds(self, klass, string):
3496
 
        result, output = self.run_doctest_suite_for_string(klass, string)
3497
 
        if not result.wasStrictlySuccessful():
3498
 
            self.fail(output.getvalue())
3499
 
 
3500
 
    def assertDocTestStringFails(self, klass, string):
3501
 
        result, output = self.run_doctest_suite_for_string(klass, string)
3502
 
        if result.wasStrictlySuccessful():
3503
 
            self.fail(output.getvalue())
3504
 
 
3505
 
    def test_injected_variable(self):
3506
 
        self.overrideAttr(tests, 'isolated_environ', {'LINES': '42'})
3507
 
        test = """
3508
 
            >>> import os
3509
 
            >>> os.environ['LINES']
3510
 
            '42'
3511
 
            """
3512
 
        # doctest.DocTestSuite fails as it sees '25'
3513
 
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
3514
 
        # tests.DocTestSuite sees '42'
3515
 
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
3516
 
 
3517
 
    def test_deleted_variable(self):
3518
 
        self.overrideAttr(tests, 'isolated_environ', {'LINES': None})
3519
 
        test = """
3520
 
            >>> import os
3521
 
            >>> os.environ.get('LINES')
3522
 
            """
3523
 
        # doctest.DocTestSuite fails as it sees '25'
3524
 
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
3525
 
        # tests.DocTestSuite sees None
3526
 
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
3527
 
 
3528
 
 
3529
 
class TestSelftestExcludePatterns(tests.TestCase):
3530
 
 
3531
 
    def setUp(self):
3532
 
        super(TestSelftestExcludePatterns, self).setUp()
3533
 
        self.overrideAttr(tests, 'test_suite', self.suite_factory)
3534
 
 
3535
 
    def suite_factory(self, keep_only=None, starting_with=None):
3536
 
        """A test suite factory with only a few tests."""
3537
 
        class Test(tests.TestCase):
3538
 
            def id(self):
3539
 
                # We don't need the full class path
3540
 
                return self._testMethodName
3541
 
            def a(self):
3542
 
                pass
3543
 
            def b(self):
3544
 
                pass
3545
 
            def c(self):
3546
 
                pass
3547
 
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
3548
 
 
3549
 
    def assertTestList(self, expected, *selftest_args):
3550
 
        # We rely on setUp installing the right test suite factory so we can
3551
 
        # test at the command level without loading the whole test suite
3552
 
        out, err = self.run_bzr(('selftest', '--list') + selftest_args)
3553
 
        actual = out.splitlines()
3554
 
        self.assertEquals(expected, actual)
3555
 
 
3556
 
    def test_full_list(self):
3557
 
        self.assertTestList(['a', 'b', 'c'])
3558
 
 
3559
 
    def test_single_exclude(self):
3560
 
        self.assertTestList(['b', 'c'], '-x', 'a')
3561
 
 
3562
 
    def test_mutiple_excludes(self):
3563
 
        self.assertTestList(['c'], '-x', 'a', '-x', 'b')
3564
 
 
3565
 
 
3566
 
class TestCounterHooks(tests.TestCase, SelfTestHelper):
3567
 
 
3568
 
    _test_needs_features = [features.subunit]
3569
 
 
3570
 
    def setUp(self):
3571
 
        super(TestCounterHooks, self).setUp()
3572
 
        class Test(tests.TestCase):
3573
 
 
3574
 
            def setUp(self):
3575
 
                super(Test, self).setUp()
3576
 
                self.hooks = hooks.Hooks()
3577
 
                self.hooks.add_hook('myhook', 'Foo bar blah', (2,4))
3578
 
                self.install_counter_hook(self.hooks, 'myhook')
3579
 
 
3580
 
            def no_hook(self):
3581
 
                pass
3582
 
 
3583
 
            def run_hook_once(self):
3584
 
                for hook in self.hooks['myhook']:
3585
 
                    hook(self)
3586
 
 
3587
 
        self.test_class = Test
3588
 
 
3589
 
    def assertHookCalls(self, expected_calls, test_name):
3590
 
        test = self.test_class(test_name)
3591
 
        result = unittest.TestResult()
3592
 
        test.run(result)
3593
 
        self.assertTrue(hasattr(test, '_counters'))
3594
 
        self.assertTrue(test._counters.has_key('myhook'))
3595
 
        self.assertEquals(expected_calls, test._counters['myhook'])
3596
 
 
3597
 
    def test_no_hook(self):
3598
 
        self.assertHookCalls(0, 'no_hook')
3599
 
 
3600
 
    def test_run_hook_once(self):
3601
 
        tt = features.testtools
3602
 
        if tt.module.__version__ < (0, 9, 8):
3603
 
            raise tests.TestSkipped('testtools-0.9.8 required for addDetail')
3604
 
        self.assertHookCalls(1, 'run_hook_once')