/breezy/unstable

To get this branch, use:
bzr branch https://code.breezy-vcs.org/breezy/unstable

« back to all changes in this revision

Viewing changes to breezy/tests/test_selftest.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-24 01:39:33 UTC
  • mfrom: (3815.3776.6)
  • Revision ID: jelmer@jelmer.uk-20170524013933-ir4y4tqtrsiz2ka2
New upstream snapshot.

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
20
19
import gc
21
20
import doctest
22
21
import os
39
38
    )
40
39
import testtools.testresult.doubles
41
40
 
42
 
import bzrlib
43
 
from bzrlib import (
 
41
import breezy
 
42
from .. import (
44
43
    branchbuilder,
45
44
    bzrdir,
46
45
    controldir,
58
57
    workingtree_3,
59
58
    workingtree_4,
60
59
    )
61
 
from bzrlib.repofmt import (
 
60
from ..repofmt import (
62
61
    groupcompress_repo,
63
62
    )
64
 
from bzrlib.symbol_versioning import (
 
63
from ..sixish import (
 
64
    BytesIO,
 
65
    )
 
66
from ..symbol_versioning import (
65
67
    deprecated_function,
66
68
    deprecated_in,
67
69
    deprecated_method,
68
70
    )
69
 
from bzrlib.tests import (
 
71
from . import (
70
72
    features,
71
73
    test_lsprof,
72
74
    test_server,
73
75
    TestUtil,
74
76
    )
75
 
from bzrlib.trace import note, mutter
76
 
from bzrlib.transport import memory
 
77
from ..trace import note, mutter
 
78
from ..transport import memory
77
79
 
78
80
 
79
81
def _test_ids(test_suite):
106
108
 
107
109
 
108
110
class TestClassesAvailable(tests.TestCase):
109
 
    """As a convenience we expose Test* classes from bzrlib.tests"""
 
111
    """As a convenience we expose Test* classes from breezy.tests"""
110
112
 
111
113
    def test_test_case(self):
112
 
        from bzrlib.tests import TestCase
 
114
        from . import TestCase
113
115
 
114
116
    def test_test_loader(self):
115
 
        from bzrlib.tests import TestLoader
 
117
        from . import TestLoader
116
118
 
117
119
    def test_test_suite(self):
118
 
        from bzrlib.tests import TestSuite
 
120
        from . import TestSuite
119
121
 
120
122
 
121
123
class TestTransportScenarios(tests.TestCase):
135
137
            def get_test_permutations(self):
136
138
                return sample_permutation
137
139
        sample_permutation = [(1,2), (3,4)]
138
 
        from bzrlib.tests.per_transport import get_transport_test_permutations
 
140
        from .per_transport import get_transport_test_permutations
139
141
        self.assertEqual(sample_permutation,
140
142
                         get_transport_test_permutations(MockModule()))
141
143
 
144
146
        # as there are in all the registered transport modules - we assume if
145
147
        # this matches its probably doing the right thing especially in
146
148
        # combination with the tests for setting the right classes below.
147
 
        from bzrlib.tests.per_transport import transport_test_permutations
148
 
        from bzrlib.transport import _get_transport_modules
 
149
        from .per_transport import transport_test_permutations
 
150
        from ..transport import _get_transport_modules
149
151
        modules = _get_transport_modules()
150
152
        permutation_count = 0
151
153
        for module in modules:
162
164
        # This test used to know about all the possible transports and the
163
165
        # order they were returned but that seems overly brittle (mbp
164
166
        # 20060307)
165
 
        from bzrlib.tests.per_transport import transport_test_permutations
 
167
        from .per_transport import transport_test_permutations
166
168
        scenarios = transport_test_permutations()
167
169
        # there are at least that many builtin transports
168
170
        self.assertTrue(len(scenarios) > 6)
169
171
        one_scenario = scenarios[0]
170
172
        self.assertIsInstance(one_scenario[0], str)
171
173
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
172
 
                                   bzrlib.transport.Transport))
 
174
                                   breezy.transport.Transport))
173
175
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
174
 
                                   bzrlib.transport.Server))
 
176
                                   breezy.transport.Server))
175
177
 
176
178
 
177
179
class TestBranchScenarios(tests.TestCase):
179
181
    def test_scenarios(self):
180
182
        # check that constructor parameters are passed through to the adapted
181
183
        # test.
182
 
        from bzrlib.tests.per_branch import make_scenarios
 
184
        from .per_branch import make_scenarios
183
185
        server1 = "a"
184
186
        server2 = "b"
185
187
        formats = [("c", "C"), ("d", "D")]
204
206
    def test_scenarios(self):
205
207
        # check that constructor parameters are passed through to the adapted
206
208
        # test.
207
 
        from bzrlib.tests.per_controldir import make_scenarios
 
209
        from .per_controldir import make_scenarios
208
210
        vfs_factory = "v"
209
211
        server1 = "a"
210
212
        server2 = "b"
227
229
class TestRepositoryScenarios(tests.TestCase):
228
230
 
229
231
    def test_formats_to_scenarios(self):
230
 
        from bzrlib.tests.per_repository import formats_to_scenarios
 
232
        from .per_repository import formats_to_scenarios
231
233
        formats = [("(c)", remote.RemoteRepositoryFormat()),
232
234
                   ("(d)", repository.format_registry.get(
233
235
                    'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
268
270
    """Tests for the test adaption facilities."""
269
271
 
270
272
    def test_apply_scenario(self):
271
 
        from bzrlib.tests import apply_scenario
 
273
        from breezy.tests import apply_scenario
272
274
        input_test = TestTestScenarioApplication("test_apply_scenario")
273
275
        # setup two adapted tests
274
276
        adapted_test1 = apply_scenario(input_test,
290
292
        self.assertEqual("readonly-server",
291
293
            adapted_test1.transport_readonly_server)
292
294
        self.assertEqual(
293
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
295
            "breezy.tests.test_selftest.TestTestScenarioApplication."
294
296
            "test_apply_scenario(new id)",
295
297
            adapted_test1.id())
296
298
        self.assertEqual(None, adapted_test2.bzrdir_format)
297
299
        self.assertEqual(
298
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
300
            "breezy.tests.test_selftest.TestTestScenarioApplication."
299
301
            "test_apply_scenario(new id 2)",
300
302
            adapted_test2.id())
301
303
 
305
307
    def test_scenarios(self):
306
308
        # check that constructor parameters are passed through to the adapted
307
309
        # test.
308
 
        from bzrlib.tests.per_interrepository import make_scenarios
 
310
        from .per_interrepository import make_scenarios
309
311
        server1 = "a"
310
312
        server2 = "b"
311
313
        formats = [("C0", "C1", "C2", "C3"), ("D0", "D1", "D2", "D3")]
331
333
    def test_scenarios(self):
332
334
        # check that constructor parameters are passed through to the adapted
333
335
        # test.
334
 
        from bzrlib.tests.per_workingtree import make_scenarios
 
336
        from .per_workingtree import make_scenarios
335
337
        server1 = "a"
336
338
        server2 = "b"
337
339
        formats = [workingtree_4.WorkingTreeFormat4(),
378
380
        # 'return_parameter' and the revision one set to
379
381
        # revision_tree_from_workingtree.
380
382
 
381
 
        from bzrlib.tests.per_tree import (
 
383
        from .per_tree import (
382
384
            _dirstate_tree_from_workingtree,
383
385
            make_scenarios,
384
386
            preview_tree_pre,
473
475
        # unlike the TestProviderAdapter we dont want to automatically add a
474
476
        # parameterized one for WorkingTree - the optimisers will tell us what
475
477
        # ones to add.
476
 
        from bzrlib.tests.per_tree import (
 
478
        from .per_tree import (
477
479
            return_parameter,
478
480
            )
479
 
        from bzrlib.tests.per_intertree import (
 
481
        from .per_intertree import (
480
482
            make_scenarios,
481
483
            )
482
 
        from bzrlib.workingtree_3 import WorkingTreeFormat3
483
 
        from bzrlib.workingtree_4 import WorkingTreeFormat4
 
484
        from ..workingtree_3 import WorkingTreeFormat3
 
485
        from ..workingtree_4 import WorkingTreeFormat4
484
486
        input_test = TestInterTreeScenarios(
485
487
            "test_scenarios")
486
488
        server1 = "a"
525
527
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
526
528
 
527
529
    def test_assertEqualStat_equal(self):
528
 
        from bzrlib.tests.test_dirstate import _FakeStat
 
530
        from .test_dirstate import _FakeStat
529
531
        self.build_tree(["foo"])
530
532
        real = os.lstat("foo")
531
533
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
563
565
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
564
566
 
565
567
        This is because TestCaseWithMemoryTransport is for tests that do not
566
 
        need any disk resources: they should be hooked into bzrlib in such a
 
568
        need any disk resources: they should be hooked into breezy in such a
567
569
        way that no global settings are being changed by the test (only a
568
570
        few tests should need to do that), and having a missing dir as home is
569
571
        an effective way to ensure that this is the case.
578
580
        cwd = osutils.getcwd()
579
581
        self.assertIsSameRealPath(self.test_dir, cwd)
580
582
 
581
 
    def test_BZR_HOME_and_HOME_are_bytestrings(self):
582
 
        """The $BZR_HOME and $HOME environment variables should not be unicode.
 
583
    def test_BRZ_HOME_and_HOME_are_bytestrings(self):
 
584
        """The $BRZ_HOME and $HOME environment variables should not be unicode.
583
585
 
584
586
        See https://bugs.launchpad.net/bzr/+bug/464174
585
587
        """
586
 
        self.assertIsInstance(os.environ['BZR_HOME'], str)
 
588
        self.assertIsInstance(os.environ['BRZ_HOME'], str)
587
589
        self.assertIsInstance(os.environ['HOME'], str)
588
590
 
589
591
    def test_make_branch_and_memory_tree(self):
669
671
    """Tests for the convenience functions TestCaseWithTransport introduces."""
670
672
 
671
673
    def test_get_readonly_url_none(self):
672
 
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
 
674
        from ..transport.readonly import ReadonlyTransportDecorator
673
675
        self.vfs_transport_factory = memory.MemoryServer
674
676
        self.transport_readonly_server = None
675
677
        # calling get_readonly_transport() constructs a decorator on the url
683
685
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
684
686
 
685
687
    def test_get_readonly_url_http(self):
686
 
        from bzrlib.tests.http_server import HttpServer
687
 
        from bzrlib.transport.http import HttpTransportBase
 
688
        from .http_server import HttpServer
 
689
        from ..transport.http import HttpTransportBase
688
690
        self.transport_server = test_server.LocalURLServer
689
691
        self.transport_readonly_server = HttpServer
690
692
        # calling get_readonly_transport() gives us a HTTP server instance.
764
766
class TestTestResult(tests.TestCase):
765
767
 
766
768
    def check_timing(self, test_case, expected_re):
767
 
        result = bzrlib.tests.TextTestResult(self._log_file,
 
769
        result = breezy.tests.TextTestResult(self._log_file,
768
770
                descriptions=0,
769
771
                verbosity=1,
770
772
                )
788
790
                          r"^ +[0-9]+ms\*$")
789
791
 
790
792
    def test_unittest_reporting_unittest_class(self):
791
 
        # getting the time from a non-bzrlib test works ok
 
793
        # getting the time from a non-breezy test works ok
792
794
        class ShortDelayTestCase(unittest.TestCase):
793
795
            def test_short_delay(self):
794
796
                time.sleep(0.003)
806
808
    def test_lsprofiling(self):
807
809
        """Verbose test result prints lsprof statistics from test cases."""
808
810
        self.requireFeature(features.lsprof_feature)
809
 
        result_stream = StringIO()
810
 
        result = bzrlib.tests.VerboseTestResult(
 
811
        result_stream = BytesIO()
 
812
        result = breezy.tests.VerboseTestResult(
811
813
            result_stream,
812
814
            descriptions=0,
813
815
            verbosity=2,
851
853
                self.time(datetime.datetime.utcfromtimestamp(51.147))
852
854
                super(TimeAddedVerboseTestResult, self).addSuccess(test)
853
855
            def report_tests_starting(self): pass
854
 
        sio = StringIO()
 
856
        sio = BytesIO()
855
857
        self.get_passing_test().run(TimeAddedVerboseTestResult(sio, 0, 2))
856
858
        self.assertEndsWith(sio.getvalue(), "OK    50002ms\n")
857
859
 
881
883
 
882
884
    def test_verbose_report_known_failure(self):
883
885
        # verbose test output formatting
884
 
        result_stream = StringIO()
885
 
        result = bzrlib.tests.VerboseTestResult(
 
886
        result_stream = BytesIO()
 
887
        result = breezy.tests.VerboseTestResult(
886
888
            result_stream,
887
889
            descriptions=0,
888
890
            verbosity=2,
928
930
 
929
931
    def test_verbose_report_unsupported(self):
930
932
        # verbose test output formatting
931
 
        result_stream = StringIO()
932
 
        result = bzrlib.tests.VerboseTestResult(
 
933
        result_stream = BytesIO()
 
934
        result = breezy.tests.VerboseTestResult(
933
935
            result_stream,
934
936
            descriptions=0,
935
937
            verbosity=2,
968
970
        self.assertEqual(0, result.error_count)
969
971
 
970
972
    def test_strict_with_unsupported_feature(self):
971
 
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
973
        result = breezy.tests.TextTestResult(self._log_file, descriptions=0,
972
974
                                             verbosity=1)
973
975
        test = self.get_passing_test()
974
976
        feature = "Unsupported Feature"
977
979
        self.assertEqual(None, result._extractBenchmarkTime(test))
978
980
 
979
981
    def test_strict_with_known_failure(self):
980
 
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
982
        result = breezy.tests.TextTestResult(self._log_file, descriptions=0,
981
983
                                             verbosity=1)
982
984
        test = _get_test("test_xfail")
983
985
        test.run(result)
985
987
        self.assertEqual(None, result._extractBenchmarkTime(test))
986
988
 
987
989
    def test_strict_with_success(self):
988
 
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
990
        result = breezy.tests.TextTestResult(self._log_file, descriptions=0,
989
991
                                             verbosity=1)
990
992
        test = self.get_passing_test()
991
993
        result.addSuccess(test)
1030
1032
        TestCaseInTempDir.TEST_ROOT
1031
1033
 
1032
1034
        There should be no tests in this file that use
1033
 
        bzrlib.tests.TextTestRunner without using this convenience method,
 
1035
        breezy.tests.TextTestRunner without using this convenience method,
1034
1036
        because of our use of global state.
1035
1037
        """
1036
1038
        old_root = tests.TestCaseInTempDir.TEST_ROOT
1051
1053
        def failing_test():
1052
1054
            raise AssertionError('foo')
1053
1055
        test.addTest(unittest.FunctionTestCase(failing_test))
1054
 
        stream = StringIO()
 
1056
        stream = BytesIO()
1055
1057
        runner = tests.TextTestRunner(stream=stream)
1056
1058
        result = self.run_test_runner(runner, test)
1057
1059
        lines = stream.getvalue().splitlines()
1058
1060
        self.assertContainsRe(stream.getvalue(),
1059
 
            '(?sm)^bzr selftest.*$'
 
1061
            '(?sm)^brz selftest.*$'
1060
1062
            '.*'
1061
1063
            '^======================================================================\n'
1062
1064
            '^FAIL: failing_test\n'
1077
1079
            def known_failure_test(self):
1078
1080
                self.knownFailure("Never works...")
1079
1081
        test = Test("known_failure_test")
1080
 
        stream = StringIO()
 
1082
        stream = BytesIO()
1081
1083
        runner = tests.TextTestRunner(stream=stream)
1082
1084
        result = self.run_test_runner(runner, test)
1083
1085
        self.assertContainsRe(stream.getvalue(),
1091
1093
        class Test(tests.TestCase):
1092
1094
            def test_truth(self):
1093
1095
                self.expectFailure("No absolute truth", self.assertTrue, True)
1094
 
        runner = tests.TextTestRunner(stream=StringIO())
 
1096
        runner = tests.TextTestRunner(stream=BytesIO())
1095
1097
        result = self.run_test_runner(runner, Test("test_truth"))
1096
1098
        self.assertContainsRe(runner.stream.getvalue(),
1097
1099
            "=+\n"
1116
1118
                ExtendedToOriginalDecorator.startTest(self, test)
1117
1119
                calls.append('start')
1118
1120
        test = unittest.FunctionTestCase(lambda:None)
1119
 
        stream = StringIO()
 
1121
        stream = BytesIO()
1120
1122
        runner = tests.TextTestRunner(stream=stream,
1121
1123
            result_decorators=[LoggingDecorator])
1122
1124
        result = self.run_test_runner(runner, test)
1183
1185
        class Test(tests.TestCase):
1184
1186
            def not_applicable_test(self):
1185
1187
                raise tests.TestNotApplicable('this test never runs')
1186
 
        out = StringIO()
 
1188
        out = BytesIO()
1187
1189
        runner = tests.TextTestRunner(stream=out, verbosity=2)
1188
1190
        test = Test("not_applicable_test")
1189
1191
        result = self.run_test_runner(runner, test)
1209
1211
        test = unittest.TestSuite()
1210
1212
        test.addTest(test1)
1211
1213
        test.addTest(test2)
1212
 
        stream = StringIO()
 
1214
        stream = BytesIO()
1213
1215
        runner = tests.TextTestRunner(stream=stream)
1214
1216
        result = self.run_test_runner(runner, test)
1215
1217
        lines = stream.getvalue().splitlines()
1226
1228
            unittest.FunctionTestCase(lambda:None),
1227
1229
            unittest.FunctionTestCase(lambda:None)])
1228
1230
        self.assertEqual(suite.countTestCases(), 2)
1229
 
        stream = StringIO()
 
1231
        stream = BytesIO()
1230
1232
        runner = tests.TextTestRunner(stream=stream, verbosity=2)
1231
1233
        # Need to use the CountingDecorator as that's what sets num_tests
1232
1234
        result = self.run_test_runner(runner, tests.CountingDecorator(suite))
1240
1242
                ExtendedToOriginalDecorator.startTestRun(self)
1241
1243
                calls.append('startTestRun')
1242
1244
        test = unittest.FunctionTestCase(lambda:None)
1243
 
        stream = StringIO()
 
1245
        stream = BytesIO()
1244
1246
        runner = tests.TextTestRunner(stream=stream,
1245
1247
            result_decorators=[LoggingDecorator])
1246
1248
        result = self.run_test_runner(runner, test)
1254
1256
                ExtendedToOriginalDecorator.stopTestRun(self)
1255
1257
                calls.append('stopTestRun')
1256
1258
        test = unittest.FunctionTestCase(lambda:None)
1257
 
        stream = StringIO()
 
1259
        stream = BytesIO()
1258
1260
        runner = tests.TextTestRunner(stream=stream,
1259
1261
            result_decorators=[LoggingDecorator])
1260
1262
        result = self.run_test_runner(runner, test)
1266
1268
            def test_log_unicode(self):
1267
1269
                self.log(u"\u2606")
1268
1270
                self.fail("Now print that log!")
1269
 
        out = StringIO()
 
1271
        out = BytesIO()
1270
1272
        self.overrideAttr(osutils, "get_terminal_encoding",
1271
1273
            lambda trace=False: "ascii")
1272
1274
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
1288
1290
 
1289
1291
 
1290
1292
class TestTestCase(tests.TestCase):
1291
 
    """Tests that test the core bzrlib TestCase."""
 
1293
    """Tests that test the core breezy TestCase."""
1292
1294
 
1293
1295
    def test_assertLength_matches_empty(self):
1294
1296
        a_list = []
1334
1336
        self.assertEqual(1, result.testsRun)
1335
1337
 
1336
1338
    def test_debug_flags_sanitised(self):
1337
 
        """The bzrlib debug flags should be sanitised by setUp."""
 
1339
        """The breezy debug flags should be sanitised by setUp."""
1338
1340
        if 'allow_debug' in tests.selftest_debug_flags:
1339
1341
            raise tests.TestNotApplicable(
1340
1342
                '-Eallow_debug option prevents debug flag sanitisation')
1344
1346
        flags = set()
1345
1347
        if self._lock_check_thorough:
1346
1348
            flags.add('strict_locks')
1347
 
        self.assertEqual(flags, bzrlib.debug.debug_flags)
 
1349
        self.assertEqual(flags, breezy.debug.debug_flags)
1348
1350
 
1349
1351
    def change_selftest_debug_flags(self, new_flags):
1350
1352
        self.overrideAttr(tests, 'selftest_debug_flags', set(new_flags))
1351
1353
 
1352
1354
    def test_allow_debug_flag(self):
1353
 
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
 
1355
        """The -Eallow_debug flag prevents breezy.debug.debug_flags from being
1354
1356
        sanitised (i.e. cleared) before running a test.
1355
1357
        """
1356
 
        self.change_selftest_debug_flags(set(['allow_debug']))
1357
 
        bzrlib.debug.debug_flags = set(['a-flag'])
 
1358
        self.change_selftest_debug_flags({'allow_debug'})
 
1359
        breezy.debug.debug_flags = {'a-flag'}
1358
1360
        class TestThatRecordsFlags(tests.TestCase):
1359
1361
            def test_foo(nested_self):
1360
 
                self.flags = set(bzrlib.debug.debug_flags)
 
1362
                self.flags = set(breezy.debug.debug_flags)
1361
1363
        test = TestThatRecordsFlags('test_foo')
1362
1364
        test.run(self.make_test_result())
1363
 
        flags = set(['a-flag'])
 
1365
        flags = {'a-flag'}
1364
1366
        if 'disable_lock_checks' not in tests.selftest_debug_flags:
1365
1367
            flags.add('strict_locks')
1366
1368
        self.assertEqual(flags, self.flags)
1369
1371
        """The -Edisable_lock_checks flag disables thorough checks."""
1370
1372
        class TestThatRecordsFlags(tests.TestCase):
1371
1373
            def test_foo(nested_self):
1372
 
                self.flags = set(bzrlib.debug.debug_flags)
 
1374
                self.flags = set(breezy.debug.debug_flags)
1373
1375
                self.test_lock_check_thorough = nested_self._lock_check_thorough
1374
1376
        self.change_selftest_debug_flags(set())
1375
1377
        test = TestThatRecordsFlags('test_foo')
1377
1379
        # By default we do strict lock checking and thorough lock/unlock
1378
1380
        # tracking.
1379
1381
        self.assertTrue(self.test_lock_check_thorough)
1380
 
        self.assertEqual(set(['strict_locks']), self.flags)
 
1382
        self.assertEqual({'strict_locks'}, self.flags)
1381
1383
        # Now set the disable_lock_checks flag, and show that this changed.
1382
 
        self.change_selftest_debug_flags(set(['disable_lock_checks']))
 
1384
        self.change_selftest_debug_flags({'disable_lock_checks'})
1383
1385
        test = TestThatRecordsFlags('test_foo')
1384
1386
        test.run(self.make_test_result())
1385
1387
        self.assertFalse(self.test_lock_check_thorough)
1388
1390
    def test_this_fails_strict_lock_check(self):
1389
1391
        class TestThatRecordsFlags(tests.TestCase):
1390
1392
            def test_foo(nested_self):
1391
 
                self.flags1 = set(bzrlib.debug.debug_flags)
 
1393
                self.flags1 = set(breezy.debug.debug_flags)
1392
1394
                self.thisFailsStrictLockCheck()
1393
 
                self.flags2 = set(bzrlib.debug.debug_flags)
 
1395
                self.flags2 = set(breezy.debug.debug_flags)
1394
1396
        # Make sure lock checking is active
1395
1397
        self.change_selftest_debug_flags(set())
1396
1398
        test = TestThatRecordsFlags('test_foo')
1397
1399
        test.run(self.make_test_result())
1398
 
        self.assertEqual(set(['strict_locks']), self.flags1)
 
1400
        self.assertEqual({'strict_locks'}, self.flags1)
1399
1401
        self.assertEqual(set(), self.flags2)
1400
1402
 
1401
1403
    def test_debug_flags_restored(self):
1402
 
        """The bzrlib debug flags should be restored to their original state
 
1404
        """The breezy debug flags should be restored to their original state
1403
1405
        after the test was run, even if allow_debug is set.
1404
1406
        """
1405
 
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1407
        self.change_selftest_debug_flags({'allow_debug'})
1406
1408
        # Now run a test that modifies debug.debug_flags.
1407
 
        bzrlib.debug.debug_flags = set(['original-state'])
 
1409
        breezy.debug.debug_flags = {'original-state'}
1408
1410
        class TestThatModifiesFlags(tests.TestCase):
1409
1411
            def test_foo(self):
1410
 
                bzrlib.debug.debug_flags = set(['modified'])
 
1412
                breezy.debug.debug_flags = {'modified'}
1411
1413
        test = TestThatModifiesFlags('test_foo')
1412
1414
        test.run(self.make_test_result())
1413
 
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
 
1415
        self.assertEqual({'original-state'}, breezy.debug.debug_flags)
1414
1416
 
1415
1417
    def make_test_result(self):
1416
1418
        """Get a test result that writes to the test log file."""
1441
1443
        # one child, we should instead see the bad result inside our test with
1442
1444
        # the two children.
1443
1445
        # the outer child test
1444
 
        original_trace = bzrlib.trace._trace_file
 
1446
        original_trace = breezy.trace._trace_file
1445
1447
        outer_test = TestTestCase("outer_child")
1446
1448
        result = self.make_test_result()
1447
1449
        outer_test.run(result)
1448
 
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
 
1450
        self.assertEqual(original_trace, breezy.trace._trace_file)
1449
1451
 
1450
1452
    def method_that_times_a_bit_twice(self):
1451
1453
        # call self.time twice to ensure it aggregates
1455
1457
    def test_time_creates_benchmark_in_result(self):
1456
1458
        """Test that the TestCase.time() method accumulates a benchmark time."""
1457
1459
        sample_test = TestTestCase("method_that_times_a_bit_twice")
1458
 
        output_stream = StringIO()
1459
 
        result = bzrlib.tests.VerboseTestResult(
 
1460
        output_stream = BytesIO()
 
1461
        result = breezy.tests.VerboseTestResult(
1460
1462
            output_stream,
1461
1463
            descriptions=0,
1462
1464
            verbosity=2)
1466
1468
            r"\d+ms\*\n$")
1467
1469
 
1468
1470
    def test_hooks_sanitised(self):
1469
 
        """The bzrlib hooks should be sanitised by setUp."""
 
1471
        """The breezy hooks should be sanitised by setUp."""
1470
1472
        # Note this test won't fail with hooks that the core library doesn't
1471
1473
        # use - but it trigger with a plugin that adds hooks, so its still a
1472
1474
        # useful warning in that case.
1473
 
        self.assertEqual(bzrlib.branch.BranchHooks(), bzrlib.branch.Branch.hooks)
1474
 
        self.assertEqual(
1475
 
            bzrlib.smart.server.SmartServerHooks(),
1476
 
            bzrlib.smart.server.SmartTCPServer.hooks)
1477
 
        self.assertEqual(
1478
 
            bzrlib.commands.CommandHooks(), bzrlib.commands.Command.hooks)
 
1475
        self.assertEqual(breezy.branch.BranchHooks(), breezy.branch.Branch.hooks)
 
1476
        self.assertEqual(
 
1477
            breezy.smart.server.SmartServerHooks(),
 
1478
            breezy.smart.server.SmartTCPServer.hooks)
 
1479
        self.assertEqual(
 
1480
            breezy.commands.CommandHooks(), breezy.commands.Command.hooks)
1479
1481
 
1480
1482
    def test__gather_lsprof_in_benchmarks(self):
1481
1483
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1491
1493
        self.assertEqual(2, len(self._benchcalls))
1492
1494
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1493
1495
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1494
 
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1495
 
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
 
1496
        self.assertIsInstance(self._benchcalls[0][1], breezy.lsprof.Stats)
 
1497
        self.assertIsInstance(self._benchcalls[1][1], breezy.lsprof.Stats)
1496
1498
        del self._benchcalls[:]
1497
1499
 
1498
1500
    def test_knownFailure(self):
1727
1729
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
1728
1730
 
1729
1731
    def test_recordCalls(self):
1730
 
        from bzrlib.tests import test_selftest
 
1732
        from breezy.tests import test_selftest
1731
1733
        calls = self.recordCalls(
1732
1734
            test_selftest, '_add_numbers')
1733
1735
        self.assertEqual(test_selftest._add_numbers(2, 10),
1906
1908
 
1907
1909
 
1908
1910
class TestExtraAssertions(tests.TestCase):
1909
 
    """Tests for new test assertions in bzrlib test suite"""
 
1911
    """Tests for new test assertions in breezy test suite"""
1910
1912
 
1911
1913
    def test_assert_isinstance(self):
1912
1914
        self.assertIsInstance(2, int)
2009
2011
 
2010
2012
    def test_make_branch_and_tree_with_format(self):
2011
2013
        # we should be able to supply a format to make_branch_and_tree
2012
 
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
2013
 
        self.assertIsInstance(bzrlib.controldir.ControlDir.open('a')._format,
2014
 
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
2014
        self.make_branch_and_tree('a', format=breezy.bzrdir.BzrDirMetaFormat1())
 
2015
        self.assertIsInstance(breezy.controldir.ControlDir.open('a')._format,
 
2016
                              breezy.bzrdir.BzrDirMetaFormat1)
2015
2017
 
2016
2018
    def test_make_branch_and_memory_tree(self):
2017
2019
        # we should be able to get a new branch and a mutable tree from
2018
2020
        # TestCaseWithTransport
2019
2021
        tree = self.make_branch_and_memory_tree('a')
2020
 
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
 
2022
        self.assertIsInstance(tree, breezy.memorytree.MemoryTree)
2021
2023
 
2022
2024
    def test_make_tree_for_local_vfs_backed_transport(self):
2023
2025
        # make_branch_and_tree has to use local branch and repositories
2038
2040
 
2039
2041
    def run_selftest(self, **kwargs):
2040
2042
        """Run selftest returning its output."""
2041
 
        output = StringIO()
2042
 
        old_transport = bzrlib.tests.default_transport
 
2043
        output = BytesIO()
 
2044
        old_transport = breezy.tests.default_transport
2043
2045
        old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
2044
2046
        tests.TestCaseWithMemoryTransport.TEST_ROOT = None
2045
2047
        try:
2046
2048
            self.assertEqual(True, tests.selftest(stream=output, **kwargs))
2047
2049
        finally:
2048
 
            bzrlib.tests.default_transport = old_transport
 
2050
            breezy.tests.default_transport = old_transport
2049
2051
            tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
2050
2052
        output.seek(0)
2051
2053
        return output
2052
2054
 
2053
2055
 
2054
2056
class TestSelftest(tests.TestCase, SelfTestHelper):
2055
 
    """Tests of bzrlib.tests.selftest."""
 
2057
    """Tests of breezy.tests.selftest."""
2056
2058
 
2057
2059
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
2058
2060
        factory_called = []
2059
2061
        def factory():
2060
2062
            factory_called.append(True)
2061
2063
            return TestUtil.TestSuite()
2062
 
        out = StringIO()
2063
 
        err = StringIO()
2064
 
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
 
2064
        out = BytesIO()
 
2065
        err = BytesIO()
 
2066
        self.apply_redirected(out, err, None, breezy.tests.selftest,
2065
2067
            test_suite_factory=factory)
2066
2068
        self.assertEqual([True], factory_called)
2067
2069
 
2138
2140
 
2139
2141
    def test_starting_with_single_argument(self):
2140
2142
        output = self.run_selftest(test_suite_factory=self.factory,
2141
 
            starting_with=['bzrlib.tests.test_selftest.Test.a'],
 
2143
            starting_with=['breezy.tests.test_selftest.Test.a'],
2142
2144
            list_only=True)
2143
 
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
 
2145
        self.assertEqual('breezy.tests.test_selftest.Test.a\n',
2144
2146
            output.getvalue())
2145
2147
 
2146
2148
    def test_starting_with_multiple_argument(self):
2147
2149
        output = self.run_selftest(test_suite_factory=self.factory,
2148
 
            starting_with=['bzrlib.tests.test_selftest.Test.a',
2149
 
                'bzrlib.tests.test_selftest.Test.b'],
 
2150
            starting_with=['breezy.tests.test_selftest.Test.a',
 
2151
                'breezy.tests.test_selftest.Test.b'],
2150
2152
            list_only=True)
2151
 
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
2152
 
            'bzrlib.tests.test_selftest.Test.b\n',
 
2153
        self.assertEqual('breezy.tests.test_selftest.Test.a\n'
 
2154
            'breezy.tests.test_selftest.Test.b\n',
2153
2155
            output.getvalue())
2154
2156
 
2155
2157
    def check_transport_set(self, transport_server):
2158
2160
            captured_transport.append(a_transport)
2159
2161
        class Capture(tests.TestCase):
2160
2162
            def a(self):
2161
 
                seen_transport(bzrlib.tests.default_transport)
 
2163
                seen_transport(breezy.tests.default_transport)
2162
2164
        def factory():
2163
2165
            return TestUtil.TestSuite([Capture("a")])
2164
2166
        self.run_selftest(transport=transport_server, test_suite_factory=factory)
2166
2168
 
2167
2169
    def test_transport_sftp(self):
2168
2170
        self.requireFeature(features.paramiko)
2169
 
        from bzrlib.tests import stub_sftp
 
2171
        from breezy.tests import stub_sftp
2170
2172
        self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
2171
2173
 
2172
2174
    def test_transport_memory(self):
2257
2259
        # GZ 2011-05-18: Old versions of subunit treat unexpected success as a
2258
2260
        #                success, if a min version check is added remove this
2259
2261
        from subunit import TestProtocolClient as _Client
2260
 
        if _Client.addUnexpectedSuccess.im_func is _Client.addSuccess.im_func:
 
2262
        if _Client.addUnexpectedSuccess.__func__ is _Client.addSuccess.__func__:
2261
2263
            self.expectFailure('subunit treats "unexpectedSuccess"'
2262
2264
                               ' as a plain success',
2263
2265
                self.assertEqual, 1, len(result.unexpectedSuccesses))
2375
2377
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2376
2378
                         a_callable=None, *args, **kwargs):
2377
2379
        self.stdin = stdin
2378
 
        self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2379
 
        self.factory = bzrlib.ui.ui_factory
 
2380
        self.factory_stdin = getattr(breezy.ui.ui_factory, "stdin", None)
 
2381
        self.factory = breezy.ui.ui_factory
2380
2382
        self.working_dir = osutils.getcwd()
2381
2383
        stdout.write('foo\n')
2382
2384
        stderr.write('bar\n')
2384
2386
 
2385
2387
    def test_stdin(self):
2386
2388
        # test that the stdin keyword to _run_bzr_core is passed through to
2387
 
        # apply_redirected as a StringIO. We do this by overriding
 
2389
        # apply_redirected as a BytesIO. We do this by overriding
2388
2390
        # apply_redirected in this class, and then calling _run_bzr_core,
2389
2391
        # which calls apply_redirected.
2390
2392
        self.run_bzr(['foo', 'bar'], stdin='gam')
2399
2401
        # own UI factory, which is an instance of TestUIFactory,
2400
2402
        # with stdin, stdout and stderr attached to the stdin,
2401
2403
        # stdout and stderr of the invoked run_bzr
2402
 
        current_factory = bzrlib.ui.ui_factory
 
2404
        current_factory = breezy.ui.ui_factory
2403
2405
        self.run_bzr(['foo'])
2404
2406
        self.assertFalse(current_factory is self.factory)
2405
2407
        self.assertNotEqual(sys.stdout, self.factory.stdout)
2586
2588
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2587
2589
        command = self._popen_args[0]
2588
2590
        self.assertEqual(sys.executable, command[0])
2589
 
        self.assertEqual(self.get_bzr_path(), command[1])
 
2591
        self.assertEqual(self.get_brz_path(), command[1])
2590
2592
        self.assertEqual(['--no-plugins'], command[2:])
2591
2593
 
2592
2594
    def test_allow_plugins(self):
2642
2644
                          working_dir='foo')
2643
2645
        self.assertEqual(['foo', 'current'], chdirs)
2644
2646
 
2645
 
    def test_get_bzr_path_with_cwd_bzrlib(self):
 
2647
    def test_get_brz_path_with_cwd_breezy(self):
2646
2648
        self.get_source_path = lambda: ""
2647
2649
        self.overrideAttr(os.path, "isfile", lambda path: True)
2648
 
        self.assertEqual(self.get_bzr_path(), "bzr")
 
2650
        self.assertEqual(self.get_brz_path(), "brz")
2649
2651
 
2650
2652
 
2651
2653
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2662
2664
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2663
2665
                                            retcode=3)
2664
2666
        self.assertEqual('', result[0])
2665
 
        self.assertEqual('bzr: interrupted\n', result[1])
 
2667
        self.assertEqual('brz: interrupted\n', result[1])
2666
2668
 
2667
2669
 
2668
2670
class TestSelftestFiltering(tests.TestCase):
2672
2674
        self.suite = TestUtil.TestSuite()
2673
2675
        self.loader = TestUtil.TestLoader()
2674
2676
        self.suite.addTest(self.loader.loadTestsFromModule(
2675
 
            sys.modules['bzrlib.tests.test_selftest']))
 
2677
            sys.modules['breezy.tests.test_selftest']))
2676
2678
        self.all_names = _test_ids(self.suite)
2677
2679
 
2678
2680
    def test_condition_id_re(self):
2679
 
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2681
        test_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2680
2682
            'test_condition_id_re')
2681
2683
        filtered_suite = tests.filter_suite_by_condition(
2682
2684
            self.suite, tests.condition_id_re('test_condition_id_re'))
2683
2685
        self.assertEqual([test_name], _test_ids(filtered_suite))
2684
2686
 
2685
2687
    def test_condition_id_in_list(self):
2686
 
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2688
        test_names = ['breezy.tests.test_selftest.TestSelftestFiltering.'
2687
2689
                      'test_condition_id_in_list']
2688
2690
        id_list = tests.TestIdList(test_names)
2689
2691
        filtered_suite = tests.filter_suite_by_condition(
2693
2695
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2694
2696
 
2695
2697
    def test_condition_id_startswith(self):
2696
 
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2698
        klass = 'breezy.tests.test_selftest.TestSelftestFiltering.'
2697
2699
        start1 = klass + 'test_condition_id_starts'
2698
2700
        start2 = klass + 'test_condition_id_in'
2699
2701
        test_names = [ klass + 'test_condition_id_in_list',
2706
2708
    def test_condition_isinstance(self):
2707
2709
        filtered_suite = tests.filter_suite_by_condition(
2708
2710
            self.suite, tests.condition_isinstance(self.__class__))
2709
 
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2711
        class_pattern = 'breezy.tests.test_selftest.TestSelftestFiltering.'
2710
2712
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
2711
2713
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2712
2714
 
2713
2715
    def test_exclude_tests_by_condition(self):
2714
 
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2716
        excluded_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2715
2717
            'test_exclude_tests_by_condition')
2716
2718
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
2717
2719
            lambda x:x.id() == excluded_name)
2726
2728
        self.all_names = _test_ids(self.suite)
2727
2729
        filtered_suite = tests.exclude_tests_by_re(self.suite,
2728
2730
                                                   'exclude_tests_by_re')
2729
 
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2731
        excluded_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2730
2732
            'test_exclude_tests_by_re')
2731
2733
        self.assertEqual(len(self.all_names) - 1,
2732
2734
            filtered_suite.countTestCases())
2736
2738
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
2737
2739
 
2738
2740
    def test_filter_suite_by_condition(self):
2739
 
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2741
        test_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2740
2742
            'test_filter_suite_by_condition')
2741
2743
        filtered_suite = tests.filter_suite_by_condition(self.suite,
2742
2744
            lambda x:x.id() == test_name)
2746
2748
        filtered_suite = tests.filter_suite_by_re(self.suite,
2747
2749
                                                  'test_filter_suite_by_r')
2748
2750
        filtered_names = _test_ids(filtered_suite)
2749
 
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
 
2751
        self.assertEqual(filtered_names, ['breezy.tests.test_selftest.'
2750
2752
            'TestSelftestFiltering.test_filter_suite_by_re'])
2751
2753
 
2752
2754
    def test_filter_suite_by_id_list(self):
2753
 
        test_list = ['bzrlib.tests.test_selftest.'
 
2755
        test_list = ['breezy.tests.test_selftest.'
2754
2756
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
2755
2757
        filtered_suite = tests.filter_suite_by_id_list(
2756
2758
            self.suite, tests.TestIdList(test_list))
2757
2759
        filtered_names = _test_ids(filtered_suite)
2758
2760
        self.assertEqual(
2759
2761
            filtered_names,
2760
 
            ['bzrlib.tests.test_selftest.'
 
2762
            ['breezy.tests.test_selftest.'
2761
2763
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
2762
2764
 
2763
2765
    def test_filter_suite_by_id_startswith(self):
2764
2766
        # By design this test may fail if another test is added whose name also
2765
2767
        # begins with one of the start value used.
2766
 
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2768
        klass = 'breezy.tests.test_selftest.TestSelftestFiltering.'
2767
2769
        start1 = klass + 'test_filter_suite_by_id_starts'
2768
2770
        start2 = klass + 'test_filter_suite_by_id_li'
2769
2771
        test_list = [klass + 'test_filter_suite_by_id_list',
2800
2802
        self.all_names = _test_ids(self.suite)
2801
2803
        condition = tests.condition_id_re('test_filter_suite_by_r')
2802
2804
        split_suite = tests.split_suite_by_condition(self.suite, condition)
2803
 
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2805
        filtered_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2804
2806
            'test_filter_suite_by_re')
2805
2807
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2806
2808
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2812
2814
        self.all_names = _test_ids(self.suite)
2813
2815
        split_suite = tests.split_suite_by_re(self.suite,
2814
2816
                                              'test_filter_suite_by_r')
2815
 
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2817
        filtered_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2816
2818
            'test_filter_suite_by_re')
2817
2819
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2818
2820
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2863
2865
        out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
2864
2866
        self.assertEqual(out, '')
2865
2867
        self.assertContainsRe(err,
2866
 
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
 
2868
            'brz: ERROR: Not a branch: ".*nonexistantpath/".\n')
2867
2869
 
2868
2870
 
2869
2871
class TestTestLoader(tests.TestCase):
2880
2882
            pass
2881
2883
        MyModule.a_class = Stub
2882
2884
        module = MyModule()
 
2885
        module.__name__ = 'fake_module'
2883
2886
        return loader, module
2884
2887
 
2885
2888
    def test_module_no_load_tests_attribute_loads_classes(self):
2888
2891
 
2889
2892
    def test_module_load_tests_attribute_gets_called(self):
2890
2893
        loader, module = self._get_loader_and_module()
2891
 
        # 'self' is here because we're faking the module with a class. Regular
2892
 
        # load_tests do not need that :)
2893
 
        def load_tests(self, standard_tests, module, loader):
 
2894
        def load_tests(loader, standard_tests, pattern):
2894
2895
            result = loader.suiteClass()
2895
2896
            for test in tests.iter_suite_tests(standard_tests):
2896
2897
                result.addTests([test, test])
2897
2898
            return result
2898
2899
        # add a load_tests() method which multiplies the tests from the module.
2899
 
        module.__class__.load_tests = load_tests
2900
 
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
 
2900
        module.__class__.load_tests = staticmethod(load_tests)
 
2901
        self.assertEqual(
 
2902
            2 * [str(module.a_class('test_foo'))],
 
2903
            list(map(str, loader.loadTestsFromModule(module))))
2901
2904
 
2902
2905
    def test_load_tests_from_module_name_smoke_test(self):
2903
2906
        loader = TestUtil.TestLoader()
2904
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2905
 
        self.assertEqual(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2907
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
2908
        self.assertEqual(['breezy.tests.test_sampler.DemoTest.test_nothing'],
2906
2909
                          _test_ids(suite))
2907
2910
 
2908
2911
    def test_load_tests_from_module_name_with_bogus_module_name(self):
2967
2970
 
2968
2971
    def test_test_suite_matches_id_list_with_unknown(self):
2969
2972
        loader = TestUtil.TestLoader()
2970
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2971
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
 
2973
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
2974
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing',
2972
2975
                     'bogus']
2973
2976
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2974
2977
        self.assertEqual(['bogus'], not_found)
2976
2979
 
2977
2980
    def test_suite_matches_id_list_with_duplicates(self):
2978
2981
        loader = TestUtil.TestLoader()
2979
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2982
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
2980
2983
        dupes = loader.suiteClass()
2981
2984
        for test in tests.iter_suite_tests(suite):
2982
2985
            dupes.addTest(test)
2983
2986
            dupes.addTest(test) # Add it again
2984
2987
 
2985
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
 
2988
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing',]
2986
2989
        not_found, duplicates = tests.suite_matches_id_list(
2987
2990
            dupes, test_list)
2988
2991
        self.assertEqual([], not_found)
2989
 
        self.assertEqual(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2992
        self.assertEqual(['breezy.tests.test_sampler.DemoTest.test_nothing'],
2990
2993
                          duplicates)
2991
2994
 
2992
2995
 
2997
3000
        # by _test_suite_testmod_names.
2998
3001
        test_list = tests._test_suite_testmod_names()
2999
3002
        self.assertSubset([
3000
 
            'bzrlib.tests.blackbox',
3001
 
            'bzrlib.tests.per_transport',
3002
 
            'bzrlib.tests.test_selftest',
 
3003
            'breezy.tests.blackbox',
 
3004
            'breezy.tests.per_transport',
 
3005
            'breezy.tests.test_selftest',
3003
3006
            ],
3004
3007
            test_list)
3005
3008
 
3012
3015
            self.assertEqual([], test_list)
3013
3016
            return
3014
3017
        self.assertSubset([
3015
 
            'bzrlib.timestamp',
 
3018
            'breezy.timestamp',
3016
3019
            ],
3017
3020
            test_list)
3018
3021
 
3026
3029
        def testmod_names():
3027
3030
            calls.append("testmod_names")
3028
3031
            return [
3029
 
                'bzrlib.tests.blackbox.test_branch',
3030
 
                'bzrlib.tests.per_transport',
3031
 
                'bzrlib.tests.test_selftest',
 
3032
                'breezy.tests.blackbox.test_branch',
 
3033
                'breezy.tests.per_transport',
 
3034
                'breezy.tests.test_selftest',
3032
3035
                ]
3033
3036
        self.overrideAttr(tests, '_test_suite_testmod_names', testmod_names)
3034
3037
        def doctests():
3035
3038
            calls.append("modules_to_doctest")
3036
3039
            if __doc__ is None:
3037
3040
                return []
3038
 
            return ['bzrlib.timestamp']
 
3041
            return ['breezy.timestamp']
3039
3042
        self.overrideAttr(tests, '_test_suite_modules_to_doctest', doctests)
3040
3043
        expected_test_list = [
3041
3044
            # testmod_names
3042
 
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
3043
 
            ('bzrlib.tests.per_transport.TransportTests'
 
3045
            'breezy.tests.blackbox.test_branch.TestBranch.test_branch',
 
3046
            ('breezy.tests.per_transport.TransportTests'
3044
3047
             '.test_abspath(LocalTransport,LocalURLServer)'),
3045
 
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
 
3048
            'breezy.tests.test_selftest.TestTestSuite.test_test_suite',
3046
3049
            # plugins can't be tested that way since selftest may be run with
3047
3050
            # --no-plugins
3048
3051
            ]
3049
3052
        if __doc__ is not None:
3050
3053
            expected_test_list.extend([
3051
3054
                # modules_to_doctest
3052
 
                'bzrlib.timestamp.format_highres_date',
 
3055
                'breezy.timestamp.format_highres_date',
3053
3056
                ])
3054
3057
        suite = tests.test_suite()
3055
 
        self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
 
3058
        self.assertEqual({"testmod_names", "modules_to_doctest"},
3056
3059
            set(calls))
3057
3060
        self.assertSubset(expected_test_list, _test_ids(suite))
3058
3061
 
3061
3064
        # to know that starting_with == None works. So a second load is
3062
3065
        # incurred - note that the starting_with parameter causes a partial load
3063
3066
        # rather than a full load so this test should be pretty quick.
3064
 
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
 
3067
        test_list = ['breezy.tests.test_selftest.TestTestSuite.test_test_suite']
3065
3068
        suite = tests.test_suite(test_list,
3066
 
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
 
3069
                                 ['breezy.tests.test_selftest.TestTestSuite'])
3067
3070
        # test_test_suite_list_and_start is not included 
3068
3071
        self.assertEqual(test_list, _test_ids(suite))
3069
3072
 
3109
3112
        return loader
3110
3113
 
3111
3114
    def test_load_tests(self):
3112
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
3115
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
3113
3116
        loader = self._create_loader(test_list)
3114
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
3117
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
3115
3118
        self.assertEqual(test_list, _test_ids(suite))
3116
3119
 
3117
3120
    def test_exclude_tests(self):
3118
3121
        test_list = ['bogus']
3119
3122
        loader = self._create_loader(test_list)
3120
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
3123
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
3121
3124
        self.assertEqual([], _test_ids(suite))
3122
3125
 
3123
3126
 
3130
3133
        return loader
3131
3134
 
3132
3135
    def test_load_tests(self):
3133
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
3134
 
        loader = self._create_loader('bzrlib.tests.test_samp')
 
3136
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
 
3137
        loader = self._create_loader('breezy.tests.test_samp')
3135
3138
 
3136
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
3139
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
3137
3140
        self.assertEqual(test_list, _test_ids(suite))
3138
3141
 
3139
3142
    def test_load_tests_inside_module(self):
3140
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
3141
 
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
 
3143
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
 
3144
        loader = self._create_loader('breezy.tests.test_sampler.Demo')
3142
3145
 
3143
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
3146
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
3144
3147
        self.assertEqual(test_list, _test_ids(suite))
3145
3148
 
3146
3149
    def test_exclude_tests(self):
3147
3150
        test_list = ['bogus']
3148
3151
        loader = self._create_loader('bogus')
3149
3152
 
3150
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
3153
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
3151
3154
        self.assertEqual([], _test_ids(suite))
3152
3155
 
3153
3156
 
3187
3190
 
3188
3191
    def test_predefined_prefixes(self):
3189
3192
        tpr = tests.test_prefix_alias_registry
3190
 
        self.assertEqual('bzrlib', tpr.resolve_alias('bzrlib'))
3191
 
        self.assertEqual('bzrlib.doc', tpr.resolve_alias('bd'))
3192
 
        self.assertEqual('bzrlib.utils', tpr.resolve_alias('bu'))
3193
 
        self.assertEqual('bzrlib.tests', tpr.resolve_alias('bt'))
3194
 
        self.assertEqual('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
3195
 
        self.assertEqual('bzrlib.plugins', tpr.resolve_alias('bp'))
 
3193
        self.assertEqual('breezy', tpr.resolve_alias('breezy'))
 
3194
        self.assertEqual('breezy.doc', tpr.resolve_alias('bd'))
 
3195
        self.assertEqual('breezy.utils', tpr.resolve_alias('bu'))
 
3196
        self.assertEqual('breezy.tests', tpr.resolve_alias('bt'))
 
3197
        self.assertEqual('breezy.tests.blackbox', tpr.resolve_alias('bb'))
 
3198
        self.assertEqual('breezy.plugins', tpr.resolve_alias('bp'))
3196
3199
 
3197
3200
 
3198
3201
class TestThreadLeakDetection(tests.TestCase):
3200
3203
 
3201
3204
    class LeakRecordingResult(tests.ExtendedTestResult):
3202
3205
        def __init__(self):
3203
 
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
 
3206
            tests.ExtendedTestResult.__init__(self, BytesIO(), 0, 1)
3204
3207
            self.leaks = []
3205
3208
        def _report_thread_leak(self, test, leaks, alive):
3206
3209
            self.leaks.append((test, leaks))
3240
3243
        result.stopTestRun()
3241
3244
        self.assertEqual(result._tests_leaking_threads_count, 1)
3242
3245
        self.assertEqual(result._first_thread_leaker_id, test.id())
3243
 
        self.assertEqual(result.leaks, [(test, set([thread]))])
 
3246
        self.assertEqual(result.leaks, [(test, {thread})])
3244
3247
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
3245
3248
 
3246
3249
    def test_multiple_leaks(self):
3276
3279
        self.assertEqual(result._tests_leaking_threads_count, 2)
3277
3280
        self.assertEqual(result._first_thread_leaker_id, first_test.id())
3278
3281
        self.assertEqual(result.leaks, [
3279
 
            (first_test, set([thread_b])),
3280
 
            (third_test, set([thread_a, thread_c]))])
 
3282
            (first_test, {thread_b}),
 
3283
            (third_test, {thread_a, thread_c})])
3281
3284
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
3282
3285
 
3283
3286
 
3286
3289
 
3287
3290
    class TracebackRecordingResult(tests.ExtendedTestResult):
3288
3291
        def __init__(self):
3289
 
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
 
3292
            tests.ExtendedTestResult.__init__(self, BytesIO(), 0, 1)
3290
3293
            self.postcode = None
3291
3294
        def _post_mortem(self, tb=None):
3292
3295
            """Record the code object at the end of the current traceback"""
3309
3312
                raise RuntimeError
3310
3313
        result = self.TracebackRecordingResult()
3311
3314
        Test().run(result)
3312
 
        self.assertEqual(result.postcode, Test.runTest.func_code)
 
3315
        self.assertEqual(result.postcode, Test.runTest.__code__)
3313
3316
 
3314
3317
    def test_location_unittest_failure(self):
3315
3318
        """Needs right post mortem traceback with failing unittest case"""
3318
3321
                raise self.failureException
3319
3322
        result = self.TracebackRecordingResult()
3320
3323
        Test().run(result)
3321
 
        self.assertEqual(result.postcode, Test.runTest.func_code)
 
3324
        self.assertEqual(result.postcode, Test.runTest.__code__)
3322
3325
 
3323
3326
    def test_location_bt_error(self):
3324
 
        """Needs right post mortem traceback with erroring bzrlib.tests case"""
 
3327
        """Needs right post mortem traceback with erroring breezy.tests case"""
3325
3328
        class Test(tests.TestCase):
3326
3329
            def test_error(self):
3327
3330
                raise RuntimeError
3328
3331
        result = self.TracebackRecordingResult()
3329
3332
        Test("test_error").run(result)
3330
 
        self.assertEqual(result.postcode, Test.test_error.func_code)
 
3333
        self.assertEqual(result.postcode, Test.test_error.__code__)
3331
3334
 
3332
3335
    def test_location_bt_failure(self):
3333
 
        """Needs right post mortem traceback with failing bzrlib.tests case"""
 
3336
        """Needs right post mortem traceback with failing breezy.tests case"""
3334
3337
        class Test(tests.TestCase):
3335
3338
            def test_failure(self):
3336
3339
                raise self.failureException
3337
3340
        result = self.TracebackRecordingResult()
3338
3341
        Test("test_failure").run(result)
3339
 
        self.assertEqual(result.postcode, Test.test_failure.func_code)
 
3342
        self.assertEqual(result.postcode, Test.test_failure.__code__)
3340
3343
 
3341
3344
    def test_env_var_triggers_post_mortem(self):
3342
 
        """Check pdb.post_mortem is called iff BZR_TEST_PDB is set"""
 
3345
        """Check pdb.post_mortem is called iff BRZ_TEST_PDB is set"""
3343
3346
        import pdb
3344
 
        result = tests.ExtendedTestResult(StringIO(), 0, 1)
 
3347
        result = tests.ExtendedTestResult(BytesIO(), 0, 1)
3345
3348
        post_mortem_calls = []
3346
3349
        self.overrideAttr(pdb, "post_mortem", post_mortem_calls.append)
3347
 
        self.overrideEnv('BZR_TEST_PDB', None)
 
3350
        self.overrideEnv('BRZ_TEST_PDB', None)
3348
3351
        result._post_mortem(1)
3349
 
        self.overrideEnv('BZR_TEST_PDB', 'on')
 
3352
        self.overrideEnv('BRZ_TEST_PDB', 'on')
3350
3353
        result._post_mortem(2)
3351
3354
        self.assertEqual([2], post_mortem_calls)
3352
3355
 
3365
3368
                calls.append(test)
3366
3369
                return tests.ExtendedTestResult(self.stream, self.descriptions,
3367
3370
                                                self.verbosity)
3368
 
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
 
3371
        tests.run_suite(suite, runner_class=MyRunner, stream=BytesIO())
3369
3372
        self.assertLength(1, calls)
3370
3373
 
3371
3374
 
3376
3379
        """To be overridden by subclasses that run tests out of process"""
3377
3380
 
3378
3381
    def _run_selftest(self, **kwargs):
3379
 
        sio = StringIO()
 
3382
        sio = BytesIO()
3380
3383
        self._inject_stream_into_subunit(sio)
3381
3384
        tests.selftest(stream=sio, stop_on_failure=False, **kwargs)
3382
3385
        return sio.getvalue()
3443
3446
        def test_self_ref(self):
3444
3447
            self.also_self = self.test_self_ref
3445
3448
        def test_skip(self):
3446
 
            self.skip("Don't need")
 
3449
            self.skipTest("Don't need")
3447
3450
 
3448
3451
    def _get_suite(self):
3449
3452
        return TestUtil.TestSuite([
3525
3528
                # Make sure we can call it twice
3526
3529
                self.overrideEnv('MYVAR', None)
3527
3530
                self.assertEqual(None, os.environ.get('MYVAR'))
3528
 
        output = StringIO()
 
3531
        output = BytesIO()
3529
3532
        result = tests.TextTestResult(output, 0, 1)
3530
3533
        Test('test_me').run(result)
3531
3534
        if not result.wasStrictlySuccessful():
3550
3553
            pass
3551
3554
 
3552
3555
    def test_basics(self):
3553
 
        # Make sure we know the definition of BZR_HOME: not part of os.environ
 
3556
        # Make sure we know the definition of BRZ_HOME: not part of os.environ
3554
3557
        # for tests.TestCase.
3555
 
        self.assertTrue('BZR_HOME' in tests.isolated_environ)
3556
 
        self.assertEqual(None, tests.isolated_environ['BZR_HOME'])
3557
 
        # Being part of isolated_environ, BZR_HOME should not appear here
3558
 
        self.assertFalse('BZR_HOME' in os.environ)
 
3558
        self.assertTrue('BRZ_HOME' in tests.isolated_environ)
 
3559
        self.assertEqual(None, tests.isolated_environ['BRZ_HOME'])
 
3560
        # Being part of isolated_environ, BRZ_HOME should not appear here
 
3561
        self.assertFalse('BRZ_HOME' in os.environ)
3559
3562
        # Make sure we know the definition of LINES: part of os.environ for
3560
3563
        # tests.TestCase
3561
3564
        self.assertTrue('LINES' in tests.isolated_environ)
3563
3566
        self.assertEqual('25', os.environ['LINES'])
3564
3567
 
3565
3568
    def test_injecting_unknown_variable(self):
3566
 
        # BZR_HOME is known to be absent from os.environ
 
3569
        # BRZ_HOME is known to be absent from os.environ
3567
3570
        test = self.ScratchMonkey('test_me')
3568
 
        tests.override_os_environ(test, {'BZR_HOME': 'foo'})
3569
 
        self.assertEqual('foo', os.environ['BZR_HOME'])
 
3571
        tests.override_os_environ(test, {'BRZ_HOME': 'foo'})
 
3572
        self.assertEqual('foo', os.environ['BRZ_HOME'])
3570
3573
        tests.restore_os_environ(test)
3571
 
        self.assertFalse('BZR_HOME' in os.environ)
 
3574
        self.assertFalse('BRZ_HOME' in os.environ)
3572
3575
 
3573
3576
    def test_injecting_known_variable(self):
3574
3577
        test = self.ScratchMonkey('test_me')
3613
3616
 
3614
3617
    def run_doctest_suite_for_string(self, klass, string):
3615
3618
        suite = self.get_doctest_suite_for_string(klass, string)
3616
 
        output = StringIO()
 
3619
        output = BytesIO()
3617
3620
        result = tests.TextTestResult(output, 0, 1)
3618
3621
        suite.run(result)
3619
3622
        return result, output
3717
3720
        result = unittest.TestResult()
3718
3721
        test.run(result)
3719
3722
        self.assertTrue(hasattr(test, '_counters'))
3720
 
        self.assertTrue(test._counters.has_key('myhook'))
 
3723
        self.assertTrue('myhook' in test._counters)
3721
3724
        self.assertEqual(expected_calls, test._counters['myhook'])
3722
3725
 
3723
3726
    def test_no_hook(self):