~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

merge 2.0 branch rev 4647

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""Tests for the test framework."""
18
18
 
19
 
import cStringIO
 
19
from cStringIO import StringIO
20
20
import os
21
 
from StringIO import StringIO
 
21
import signal
22
22
import sys
23
23
import time
24
24
import unittest
33
33
    lockdir,
34
34
    memorytree,
35
35
    osutils,
 
36
    progress,
36
37
    remote,
37
38
    repository,
38
39
    symbol_versioning,
39
40
    tests,
40
41
    workingtree,
41
42
    )
42
 
from bzrlib.progress import _BaseProgressBar
43
43
from bzrlib.repofmt import (
 
44
    groupcompress_repo,
44
45
    pack_repo,
45
46
    weaverepo,
46
47
    )
50
51
    deprecated_method,
51
52
    )
52
53
from bzrlib.tests import (
53
 
                          ChrootedTestCase,
54
 
                          ExtendedTestResult,
55
 
                          Feature,
56
 
                          KnownFailure,
57
 
                          TestCase,
58
 
                          TestCaseInTempDir,
59
 
                          TestCaseWithMemoryTransport,
60
 
                          TestCaseWithTransport,
61
 
                          TestNotApplicable,
62
 
                          TestSkipped,
63
 
                          TestSuite,
64
 
                          TestUtil,
65
 
                          TextTestRunner,
66
 
                          UnavailableFeature,
67
 
                          condition_id_re,
68
 
                          condition_isinstance,
69
 
                          exclude_tests_by_condition,
70
 
                          exclude_tests_by_re,
71
 
                          filter_suite_by_condition,
72
 
                          filter_suite_by_re,
73
 
                          iter_suite_tests,
74
 
                          preserve_input,
75
 
                          randomize_suite,
76
 
                          run_suite,
77
 
                          split_suite_by_condition,
78
 
                          split_suite_by_re,
79
 
                          test_lsprof,
80
 
                          test_suite,
81
 
                          )
82
 
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
83
 
from bzrlib.tests.TestUtil import _load_module_by_name
 
54
    SubUnitFeature,
 
55
    test_lsprof,
 
56
    test_sftp_transport,
 
57
    TestUtil,
 
58
    )
84
59
from bzrlib.trace import note
85
60
from bzrlib.transport.memory import MemoryServer, MemoryTransport
86
61
from bzrlib.version import _get_bzr_source_tree
88
63
 
89
64
def _test_ids(test_suite):
90
65
    """Get the ids for the tests in a test suite."""
91
 
    return [t.id() for t in iter_suite_tests(test_suite)]
92
 
 
93
 
 
94
 
class SelftestTests(TestCase):
 
66
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
67
 
 
68
 
 
69
class SelftestTests(tests.TestCase):
95
70
 
96
71
    def test_import_tests(self):
97
 
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
 
72
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
98
73
        self.assertEqual(mod.SelftestTests, SelftestTests)
99
74
 
100
75
    def test_import_test_failure(self):
101
76
        self.assertRaises(ImportError,
102
 
                          _load_module_by_name,
 
77
                          TestUtil._load_module_by_name,
103
78
                          'bzrlib.no-name-yet')
104
79
 
105
 
class MetaTestLog(TestCase):
 
80
class MetaTestLog(tests.TestCase):
106
81
 
107
82
    def test_logging(self):
108
83
        """Test logs are captured when a test fails."""
112
87
                              'a test message\n')
113
88
 
114
89
 
115
 
class TestUnicodeFilename(TestCase):
 
90
class TestUnicodeFilename(tests.TestCase):
116
91
 
117
92
    def test_probe_passes(self):
118
93
        """UnicodeFilename._probe passes."""
121
96
        tests.UnicodeFilename._probe()
122
97
 
123
98
 
124
 
class TestTreeShape(TestCaseInTempDir):
 
99
class TestTreeShape(tests.TestCaseInTempDir):
125
100
 
126
101
    def test_unicode_paths(self):
127
102
        self.requireFeature(tests.UnicodeFilename)
131
106
        self.failUnlessExists(filename)
132
107
 
133
108
 
134
 
class TestTransportScenarios(TestCase):
 
109
class TestTransportScenarios(tests.TestCase):
135
110
    """A group of tests that test the transport implementation adaption core.
136
111
 
137
112
    This is a meta test that the tests are applied to all available
148
123
            def get_test_permutations(self):
149
124
                return sample_permutation
150
125
        sample_permutation = [(1,2), (3,4)]
151
 
        from bzrlib.tests.test_transport_implementations \
152
 
            import get_transport_test_permutations
 
126
        from bzrlib.tests.per_transport import get_transport_test_permutations
153
127
        self.assertEqual(sample_permutation,
154
128
                         get_transport_test_permutations(MockModule()))
155
129
 
156
 
    def test_scenarios_invlude_all_modules(self):
 
130
    def test_scenarios_include_all_modules(self):
157
131
        # this checks that the scenario generator returns as many permutations
158
132
        # as there are in all the registered transport modules - we assume if
159
133
        # this matches its probably doing the right thing especially in
160
134
        # combination with the tests for setting the right classes below.
161
 
        from bzrlib.tests.test_transport_implementations \
162
 
            import transport_test_permutations
 
135
        from bzrlib.tests.per_transport import transport_test_permutations
163
136
        from bzrlib.transport import _get_transport_modules
164
137
        modules = _get_transport_modules()
165
138
        permutation_count = 0
177
150
        # This test used to know about all the possible transports and the
178
151
        # order they were returned but that seems overly brittle (mbp
179
152
        # 20060307)
180
 
        from bzrlib.tests.test_transport_implementations \
181
 
            import transport_test_permutations
 
153
        from bzrlib.tests.per_transport import transport_test_permutations
182
154
        scenarios = transport_test_permutations()
183
155
        # there are at least that many builtin transports
184
156
        self.assertTrue(len(scenarios) > 6)
190
162
                                   bzrlib.transport.Server))
191
163
 
192
164
 
193
 
class TestBranchScenarios(TestCase):
 
165
class TestBranchScenarios(tests.TestCase):
194
166
 
195
167
    def test_scenarios(self):
196
168
        # check that constructor parameters are passed through to the adapted
197
169
        # test.
198
 
        from bzrlib.tests.branch_implementations import make_scenarios
 
170
        from bzrlib.tests.per_branch import make_scenarios
199
171
        server1 = "a"
200
172
        server2 = "b"
201
173
        formats = [("c", "C"), ("d", "D")]
215
187
            scenarios)
216
188
 
217
189
 
218
 
class TestBzrDirScenarios(TestCase):
 
190
class TestBzrDirScenarios(tests.TestCase):
219
191
 
220
192
    def test_scenarios(self):
221
193
        # check that constructor parameters are passed through to the adapted
222
194
        # test.
223
 
        from bzrlib.tests.bzrdir_implementations import make_scenarios
 
195
        from bzrlib.tests.per_bzrdir import make_scenarios
224
196
        vfs_factory = "v"
225
197
        server1 = "a"
226
198
        server2 = "b"
240
212
            scenarios)
241
213
 
242
214
 
243
 
class TestRepositoryScenarios(TestCase):
 
215
class TestRepositoryScenarios(tests.TestCase):
244
216
 
245
217
    def test_formats_to_scenarios(self):
246
218
        from bzrlib.tests.per_repository import formats_to_scenarios
247
219
        formats = [("(c)", remote.RemoteRepositoryFormat()),
248
220
                   ("(d)", repository.format_registry.get(
249
 
                        'Bazaar pack repository format 1 (needs bzr 0.92)\n'))]
 
221
                    'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
250
222
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
251
223
            None)
252
224
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
253
225
            vfs_transport_factory="vfs")
254
226
        # no_vfs generate scenarios without vfs_transport_factory
255
 
        self.assertEqual([
 
227
        expected = [
256
228
            ('RemoteRepositoryFormat(c)',
257
229
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
258
230
              'repository_format': remote.RemoteRepositoryFormat(),
259
231
              'transport_readonly_server': 'readonly',
260
232
              'transport_server': 'server'}),
261
 
            ('RepositoryFormatKnitPack1(d)',
 
233
            ('RepositoryFormat2a(d)',
262
234
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
263
 
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
 
235
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
264
236
              'transport_readonly_server': 'readonly',
265
 
              'transport_server': 'server'})],
266
 
            no_vfs_scenarios)
 
237
              'transport_server': 'server'})]
 
238
        self.assertEqual(expected, no_vfs_scenarios)
267
239
        self.assertEqual([
268
240
            ('RemoteRepositoryFormat(c)',
269
241
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
271
243
              'transport_readonly_server': 'readonly',
272
244
              'transport_server': 'server',
273
245
              'vfs_transport_factory': 'vfs'}),
274
 
            ('RepositoryFormatKnitPack1(d)',
 
246
            ('RepositoryFormat2a(d)',
275
247
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
276
 
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
 
248
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
277
249
              'transport_readonly_server': 'readonly',
278
250
              'transport_server': 'server',
279
251
              'vfs_transport_factory': 'vfs'})],
280
252
            vfs_scenarios)
281
253
 
282
254
 
283
 
class TestTestScenarioApplication(TestCase):
 
255
class TestTestScenarioApplication(tests.TestCase):
284
256
    """Tests for the test adaption facilities."""
285
257
 
286
258
    def test_apply_scenario(self):
316
288
            adapted_test2.id())
317
289
 
318
290
 
319
 
class TestInterRepositoryScenarios(TestCase):
 
291
class TestInterRepositoryScenarios(tests.TestCase):
320
292
 
321
293
    def test_scenarios(self):
322
294
        # check that constructor parameters are passed through to the adapted
323
295
        # test.
324
 
        from bzrlib.tests.interrepository_implementations import \
325
 
            make_scenarios
 
296
        from bzrlib.tests.per_interrepository import make_scenarios
326
297
        server1 = "a"
327
298
        server2 = "b"
328
 
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
299
        formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
329
300
        scenarios = make_scenarios(server1, server2, formats)
330
301
        self.assertEqual([
331
 
            ('str,str,str',
332
 
             {'interrepo_class': str,
333
 
              'repository_format': 'C1',
 
302
            ('C0,str,str',
 
303
             {'repository_format': 'C1',
334
304
              'repository_format_to': 'C2',
335
305
              'transport_readonly_server': 'b',
336
306
              'transport_server': 'a'}),
337
 
            ('int,str,str',
338
 
             {'interrepo_class': int,
339
 
              'repository_format': 'D1',
 
307
            ('D0,str,str',
 
308
             {'repository_format': 'D1',
340
309
              'repository_format_to': 'D2',
341
310
              'transport_readonly_server': 'b',
342
311
              'transport_server': 'a'})],
343
312
            scenarios)
344
313
 
345
314
 
346
 
class TestWorkingTreeScenarios(TestCase):
 
315
class TestWorkingTreeScenarios(tests.TestCase):
347
316
 
348
317
    def test_scenarios(self):
349
318
        # check that constructor parameters are passed through to the adapted
350
319
        # test.
351
 
        from bzrlib.tests.workingtree_implementations \
352
 
            import make_scenarios
 
320
        from bzrlib.tests.per_workingtree import make_scenarios
353
321
        server1 = "a"
354
322
        server2 = "b"
355
323
        formats = [workingtree.WorkingTreeFormat2(),
369
337
            scenarios)
370
338
 
371
339
 
372
 
class TestTreeScenarios(TestCase):
 
340
class TestTreeScenarios(tests.TestCase):
373
341
 
374
342
    def test_scenarios(self):
375
343
        # the tree implementation scenario generator is meant to setup one
379
347
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
380
348
        # revision one set to revision_tree_from_workingtree.
381
349
 
382
 
        from bzrlib.tests.tree_implementations import (
 
350
        from bzrlib.tests.per_tree import (
383
351
            _dirstate_tree_from_workingtree,
384
352
            make_scenarios,
385
353
            preview_tree_pre,
448
416
        self.assertEqual(expected_scenarios, scenarios)
449
417
 
450
418
 
451
 
class TestInterTreeScenarios(TestCase):
 
419
class TestInterTreeScenarios(tests.TestCase):
452
420
    """A group of tests that test the InterTreeTestAdapter."""
453
421
 
454
422
    def test_scenarios(self):
461
429
        # unlike the TestProviderAdapter we dont want to automatically add a
462
430
        # parameterized one for WorkingTree - the optimisers will tell us what
463
431
        # ones to add.
464
 
        from bzrlib.tests.tree_implementations import (
 
432
        from bzrlib.tests.per_tree import (
465
433
            return_parameter,
466
434
            revision_tree_from_workingtree
467
435
            )
468
 
        from bzrlib.tests.intertree_implementations import (
 
436
        from bzrlib.tests.per_intertree import (
469
437
            make_scenarios,
470
438
            )
471
439
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
504
472
        self.assertEqual(scenarios, expected_scenarios)
505
473
 
506
474
 
507
 
class TestTestCaseInTempDir(TestCaseInTempDir):
 
475
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
508
476
 
509
477
    def test_home_is_not_working(self):
510
478
        self.assertNotEqual(self.test_dir, self.test_home_dir)
526
494
            os.lstat("foo"), os.lstat("bar"))
527
495
 
528
496
 
529
 
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
 
497
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
530
498
 
531
499
    def test_home_is_non_existant_dir_under_root(self):
532
500
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
622
590
        self.assertRaises(AssertionError, self._check_safety_net)
623
591
 
624
592
    def test_dangling_locks_cause_failures(self):
625
 
        class TestDanglingLock(TestCaseWithMemoryTransport):
 
593
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
626
594
            def test_function(self):
627
595
                t = self.get_transport('.')
628
596
                l = lockdir.LockDir(t, 'lock')
630
598
                l.attempt_lock()
631
599
        test = TestDanglingLock('test_function')
632
600
        result = test.run()
633
 
        self.assertEqual(1, len(result.errors))
634
 
 
635
 
 
636
 
class TestTestCaseWithTransport(TestCaseWithTransport):
 
601
        if self._lock_check_thorough:
 
602
            self.assertEqual(1, len(result.errors))
 
603
        else:
 
604
            # When _lock_check_thorough is disabled, then we don't trigger a
 
605
            # failure
 
606
            self.assertEqual(0, len(result.errors))
 
607
 
 
608
 
 
609
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
637
610
    """Tests for the convenience functions TestCaseWithTransport introduces."""
638
611
 
639
612
    def test_get_readonly_url_none(self):
690
663
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
691
664
 
692
665
 
693
 
class TestTestCaseTransports(TestCaseWithTransport):
 
666
class TestTestCaseTransports(tests.TestCaseWithTransport):
694
667
 
695
668
    def setUp(self):
696
669
        super(TestTestCaseTransports, self).setUp()
705
678
        self.failIfExists('subdir')
706
679
 
707
680
 
708
 
class TestChrootedTest(ChrootedTestCase):
 
681
class TestChrootedTest(tests.ChrootedTestCase):
709
682
 
710
683
    def test_root_is_root(self):
711
684
        from bzrlib.transport import get_transport
714
687
        self.assertEqual(url, t.clone('..').base)
715
688
 
716
689
 
717
 
class MockProgress(_BaseProgressBar):
718
 
    """Progress-bar standin that records calls.
719
 
 
720
 
    Useful for testing pb using code.
721
 
    """
722
 
 
723
 
    def __init__(self):
724
 
        _BaseProgressBar.__init__(self)
725
 
        self.calls = []
726
 
 
727
 
    def tick(self):
728
 
        self.calls.append(('tick',))
729
 
 
730
 
    def update(self, msg=None, current=None, total=None):
731
 
        self.calls.append(('update', msg, current, total))
732
 
 
733
 
    def clear(self):
734
 
        self.calls.append(('clear',))
735
 
 
736
 
    def note(self, msg, *args):
737
 
        self.calls.append(('note', msg, args))
738
 
 
739
 
 
740
 
class TestTestResult(TestCase):
 
690
class TestTestResult(tests.TestCase):
741
691
 
742
692
    def check_timing(self, test_case, expected_re):
743
693
        result = bzrlib.tests.TextTestResult(self._log_file,
749
699
        self.assertContainsRe(timed_string, expected_re)
750
700
 
751
701
    def test_test_reporting(self):
752
 
        class ShortDelayTestCase(TestCase):
 
702
        class ShortDelayTestCase(tests.TestCase):
753
703
            def test_short_delay(self):
754
704
                time.sleep(0.003)
755
705
            def test_short_benchmark(self):
756
706
                self.time(time.sleep, 0.003)
757
707
        self.check_timing(ShortDelayTestCase('test_short_delay'),
758
708
                          r"^ +[0-9]+ms$")
759
 
        # if a benchmark time is given, we want a x of y style result.
 
709
        # if a benchmark time is given, we now show just that time followed by
 
710
        # a star
760
711
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
761
 
                          r"^ +[0-9]+ms/ +[0-9]+ms$")
 
712
                          r"^ +[0-9]+ms\*$")
762
713
 
763
714
    def test_unittest_reporting_unittest_class(self):
764
715
        # getting the time from a non-bzrlib test works ok
848
799
 
849
800
    def test_known_failure(self):
850
801
        """A KnownFailure being raised should trigger several result actions."""
851
 
        class InstrumentedTestResult(ExtendedTestResult):
 
802
        class InstrumentedTestResult(tests.ExtendedTestResult):
852
803
            def done(self): pass
853
804
            def startTests(self): pass
854
805
            def report_test_start(self, test): pass
856
807
                self._call = test, err
857
808
        result = InstrumentedTestResult(None, None, None, None)
858
809
        def test_function():
859
 
            raise KnownFailure('failed!')
 
810
            raise tests.KnownFailure('failed!')
860
811
        test = unittest.FunctionTestCase(test_function)
861
812
        test.run(result)
862
813
        # it should invoke 'report_known_failure'.
863
814
        self.assertEqual(2, len(result._call))
864
815
        self.assertEqual(test, result._call[0])
865
 
        self.assertEqual(KnownFailure, result._call[1][0])
866
 
        self.assertIsInstance(result._call[1][1], KnownFailure)
 
816
        self.assertEqual(tests.KnownFailure, result._call[1][0])
 
817
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
867
818
        # we dont introspec the traceback, if the rest is ok, it would be
868
819
        # exceptional for it not to be.
869
820
        # it should update the known_failure_count on the object.
886
837
        # (class, exception object, traceback)
887
838
        # KnownFailures dont get their tracebacks shown though, so we
888
839
        # can skip that.
889
 
        err = (KnownFailure, KnownFailure('foo'), None)
 
840
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
890
841
        result.report_known_failure(test, err)
891
842
        output = result_stream.getvalue()[prefix:]
892
843
        lines = output.splitlines()
894
845
        self.assertEqual(lines[1], '    foo')
895
846
        self.assertEqual(2, len(lines))
896
847
 
897
 
    def test_text_report_known_failure(self):
898
 
        # text test output formatting
899
 
        pb = MockProgress()
900
 
        result = bzrlib.tests.TextTestResult(
901
 
            StringIO(),
902
 
            descriptions=0,
903
 
            verbosity=1,
904
 
            pb=pb,
905
 
            )
906
 
        test = self.get_passing_test()
907
 
        # this seeds the state to handle reporting the test.
908
 
        result.startTest(test)
909
 
        # the err parameter has the shape:
910
 
        # (class, exception object, traceback)
911
 
        # KnownFailures dont get their tracebacks shown though, so we
912
 
        # can skip that.
913
 
        err = (KnownFailure, KnownFailure('foo'), None)
914
 
        result.report_known_failure(test, err)
915
 
        self.assertEqual(
916
 
            [
917
 
            ('update', '[1 in 0s] passing_test', None, None),
918
 
            ('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
919
 
            ],
920
 
            pb.calls)
921
 
        # known_failures should be printed in the summary, so if we run a test
922
 
        # after there are some known failures, the update prefix should match
923
 
        # this.
924
 
        result.known_failure_count = 3
925
 
        test.run(result)
926
 
        self.assertEqual(
927
 
            [
928
 
            ('update', '[2 in 0s] passing_test', None, None),
929
 
            ],
930
 
            pb.calls[2:])
931
 
 
932
848
    def get_passing_test(self):
933
849
        """Return a test object that can't be run usefully."""
934
850
        def passing_test():
937
853
 
938
854
    def test_add_not_supported(self):
939
855
        """Test the behaviour of invoking addNotSupported."""
940
 
        class InstrumentedTestResult(ExtendedTestResult):
 
856
        class InstrumentedTestResult(tests.ExtendedTestResult):
941
857
            def done(self): pass
942
858
            def startTests(self): pass
943
859
            def report_test_start(self, test): pass
945
861
                self._call = test, feature
946
862
        result = InstrumentedTestResult(None, None, None, None)
947
863
        test = SampleTestCase('_test_pass')
948
 
        feature = Feature()
 
864
        feature = tests.Feature()
949
865
        result.startTest(test)
950
866
        result.addNotSupported(test, feature)
951
867
        # it should invoke 'report_unsupported'.
970
886
            verbosity=2,
971
887
            )
972
888
        test = self.get_passing_test()
973
 
        feature = Feature()
 
889
        feature = tests.Feature()
974
890
        result.startTest(test)
975
891
        prefix = len(result_stream.getvalue())
976
892
        result.report_unsupported(test, feature)
977
893
        output = result_stream.getvalue()[prefix:]
978
894
        lines = output.splitlines()
979
 
        self.assertEqual(lines, ['NODEP                   0ms', "    The feature 'Feature' is not available."])
980
 
 
981
 
    def test_text_report_unsupported(self):
982
 
        # text test output formatting
983
 
        pb = MockProgress()
984
 
        result = bzrlib.tests.TextTestResult(
985
 
            StringIO(),
986
 
            descriptions=0,
987
 
            verbosity=1,
988
 
            pb=pb,
989
 
            )
990
 
        test = self.get_passing_test()
991
 
        feature = Feature()
992
 
        # this seeds the state to handle reporting the test.
993
 
        result.startTest(test)
994
 
        result.report_unsupported(test, feature)
995
 
        # no output on unsupported features
996
 
        self.assertEqual(
997
 
            [('update', '[1 in 0s] passing_test', None, None)
998
 
            ],
999
 
            pb.calls)
1000
 
        # the number of missing features should be printed in the progress
1001
 
        # summary, so check for that.
1002
 
        result.unsupported = {'foo':0, 'bar':0}
1003
 
        test.run(result)
1004
 
        self.assertEqual(
1005
 
            [
1006
 
            ('update', '[2 in 0s, 2 missing] passing_test', None, None),
1007
 
            ],
1008
 
            pb.calls[1:])
 
895
        self.assertEqual(lines, ['NODEP        0ms',
 
896
                                 "    The feature 'Feature' is not available."])
1009
897
 
1010
898
    def test_unavailable_exception(self):
1011
899
        """An UnavailableFeature being raised should invoke addNotSupported."""
1012
 
        class InstrumentedTestResult(ExtendedTestResult):
 
900
        class InstrumentedTestResult(tests.ExtendedTestResult):
1013
901
            def done(self): pass
1014
902
            def startTests(self): pass
1015
903
            def report_test_start(self, test): pass
1016
904
            def addNotSupported(self, test, feature):
1017
905
                self._call = test, feature
1018
906
        result = InstrumentedTestResult(None, None, None, None)
1019
 
        feature = Feature()
 
907
        feature = tests.Feature()
1020
908
        def test_function():
1021
 
            raise UnavailableFeature(feature)
 
909
            raise tests.UnavailableFeature(feature)
1022
910
        test = unittest.FunctionTestCase(test_function)
1023
911
        test.run(result)
1024
912
        # it should invoke 'addNotSupported'.
1041
929
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1042
930
                                             verbosity=1)
1043
931
        test = self.get_passing_test()
1044
 
        err = (KnownFailure, KnownFailure('foo'), None)
 
932
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
1045
933
        result._addKnownFailure(test, err)
1046
934
        self.assertFalse(result.wasStrictlySuccessful())
1047
935
        self.assertEqual(None, result._extractBenchmarkTime(test))
1056
944
 
1057
945
    def test_startTests(self):
1058
946
        """Starting the first test should trigger startTests."""
1059
 
        class InstrumentedTestResult(ExtendedTestResult):
 
947
        class InstrumentedTestResult(tests.ExtendedTestResult):
1060
948
            calls = 0
1061
949
            def startTests(self): self.calls += 1
1062
950
            def report_test_start(self, test): pass
1068
956
        self.assertEquals(1, result.calls)
1069
957
 
1070
958
 
1071
 
class TestUnicodeFilenameFeature(TestCase):
 
959
class TestUnicodeFilenameFeature(tests.TestCase):
1072
960
 
1073
961
    def test_probe_passes(self):
1074
962
        """UnicodeFilenameFeature._probe passes."""
1077
965
        tests.UnicodeFilenameFeature._probe()
1078
966
 
1079
967
 
1080
 
class TestRunner(TestCase):
 
968
class TestRunner(tests.TestCase):
1081
969
 
1082
970
    def dummy_test(self):
1083
971
        pass
1088
976
        This current saves and restores:
1089
977
        TestCaseInTempDir.TEST_ROOT
1090
978
 
1091
 
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
1092
 
        without using this convenience method, because of our use of global state.
 
979
        There should be no tests in this file that use
 
980
        bzrlib.tests.TextTestRunner without using this convenience method,
 
981
        because of our use of global state.
1093
982
        """
1094
 
        old_root = TestCaseInTempDir.TEST_ROOT
 
983
        old_root = tests.TestCaseInTempDir.TEST_ROOT
1095
984
        try:
1096
 
            TestCaseInTempDir.TEST_ROOT = None
 
985
            tests.TestCaseInTempDir.TEST_ROOT = None
1097
986
            return testrunner.run(test)
1098
987
        finally:
1099
 
            TestCaseInTempDir.TEST_ROOT = old_root
 
988
            tests.TestCaseInTempDir.TEST_ROOT = old_root
1100
989
 
1101
990
    def test_known_failure_failed_run(self):
1102
991
        # run a test that generates a known failure which should be printed in
1103
992
        # the final output when real failures occur.
1104
993
        def known_failure_test():
1105
 
            raise KnownFailure('failed')
 
994
            raise tests.KnownFailure('failed')
1106
995
        test = unittest.TestSuite()
1107
996
        test.addTest(unittest.FunctionTestCase(known_failure_test))
1108
997
        def failing_test():
1109
998
            raise AssertionError('foo')
1110
999
        test.addTest(unittest.FunctionTestCase(failing_test))
1111
1000
        stream = StringIO()
1112
 
        runner = TextTestRunner(stream=stream)
 
1001
        runner = tests.TextTestRunner(stream=stream)
1113
1002
        result = self.run_test_runner(runner, test)
1114
1003
        lines = stream.getvalue().splitlines()
1115
 
        self.assertEqual([
1116
 
            '',
1117
 
            '======================================================================',
1118
 
            'FAIL: unittest.FunctionTestCase (failing_test)',
1119
 
            '----------------------------------------------------------------------',
1120
 
            'Traceback (most recent call last):',
1121
 
            '    raise AssertionError(\'foo\')',
1122
 
            'AssertionError: foo',
1123
 
            '',
1124
 
            '----------------------------------------------------------------------',
1125
 
            '',
1126
 
            'FAILED (failures=1, known_failure_count=1)'],
1127
 
            lines[3:8] + lines[9:13] + lines[14:])
 
1004
        self.assertContainsRe(stream.getvalue(),
 
1005
            '(?sm)^testing.*$'
 
1006
            '.*'
 
1007
            '^======================================================================\n'
 
1008
            '^FAIL: unittest.FunctionTestCase \\(failing_test\\)\n'
 
1009
            '^----------------------------------------------------------------------\n'
 
1010
            'Traceback \\(most recent call last\\):\n'
 
1011
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
 
1012
            '    raise AssertionError\\(\'foo\'\\)\n'
 
1013
            '.*'
 
1014
            '^----------------------------------------------------------------------\n'
 
1015
            '.*'
 
1016
            'FAILED \\(failures=1, known_failure_count=1\\)'
 
1017
            )
1128
1018
 
1129
1019
    def test_known_failure_ok_run(self):
1130
1020
        # run a test that generates a known failure which should be printed in the final output.
1131
1021
        def known_failure_test():
1132
 
            raise KnownFailure('failed')
 
1022
            raise tests.KnownFailure('failed')
1133
1023
        test = unittest.FunctionTestCase(known_failure_test)
1134
1024
        stream = StringIO()
1135
 
        runner = TextTestRunner(stream=stream)
 
1025
        runner = tests.TextTestRunner(stream=stream)
1136
1026
        result = self.run_test_runner(runner, test)
1137
1027
        self.assertContainsRe(stream.getvalue(),
1138
1028
            '\n'
1145
1035
        # run a test that is skipped, and check the suite as a whole still
1146
1036
        # succeeds.
1147
1037
        # skipping_test must be hidden in here so it's not run as a real test
1148
 
        class SkippingTest(TestCase):
 
1038
        class SkippingTest(tests.TestCase):
1149
1039
            def skipping_test(self):
1150
 
                raise TestSkipped('test intentionally skipped')
1151
 
        runner = TextTestRunner(stream=self._log_file)
 
1040
                raise tests.TestSkipped('test intentionally skipped')
 
1041
        runner = tests.TextTestRunner(stream=self._log_file)
1152
1042
        test = SkippingTest("skipping_test")
1153
1043
        result = self.run_test_runner(runner, test)
1154
1044
        self.assertTrue(result.wasSuccessful())
1155
1045
 
1156
1046
    def test_skipped_from_setup(self):
1157
1047
        calls = []
1158
 
        class SkippedSetupTest(TestCase):
 
1048
        class SkippedSetupTest(tests.TestCase):
1159
1049
 
1160
1050
            def setUp(self):
1161
1051
                calls.append('setUp')
1162
1052
                self.addCleanup(self.cleanup)
1163
 
                raise TestSkipped('skipped setup')
 
1053
                raise tests.TestSkipped('skipped setup')
1164
1054
 
1165
1055
            def test_skip(self):
1166
1056
                self.fail('test reached')
1168
1058
            def cleanup(self):
1169
1059
                calls.append('cleanup')
1170
1060
 
1171
 
        runner = TextTestRunner(stream=self._log_file)
 
1061
        runner = tests.TextTestRunner(stream=self._log_file)
1172
1062
        test = SkippedSetupTest('test_skip')
1173
1063
        result = self.run_test_runner(runner, test)
1174
1064
        self.assertTrue(result.wasSuccessful())
1177
1067
 
1178
1068
    def test_skipped_from_test(self):
1179
1069
        calls = []
1180
 
        class SkippedTest(TestCase):
 
1070
        class SkippedTest(tests.TestCase):
1181
1071
 
1182
1072
            def setUp(self):
1183
 
                TestCase.setUp(self)
 
1073
                tests.TestCase.setUp(self)
1184
1074
                calls.append('setUp')
1185
1075
                self.addCleanup(self.cleanup)
1186
1076
 
1187
1077
            def test_skip(self):
1188
 
                raise TestSkipped('skipped test')
 
1078
                raise tests.TestSkipped('skipped test')
1189
1079
 
1190
1080
            def cleanup(self):
1191
1081
                calls.append('cleanup')
1192
1082
 
1193
 
        runner = TextTestRunner(stream=self._log_file)
 
1083
        runner = tests.TextTestRunner(stream=self._log_file)
1194
1084
        test = SkippedTest('test_skip')
1195
1085
        result = self.run_test_runner(runner, test)
1196
1086
        self.assertTrue(result.wasSuccessful())
1200
1090
    def test_not_applicable(self):
1201
1091
        # run a test that is skipped because it's not applicable
1202
1092
        def not_applicable_test():
1203
 
            from bzrlib.tests import TestNotApplicable
1204
 
            raise TestNotApplicable('this test never runs')
 
1093
            raise tests.TestNotApplicable('this test never runs')
1205
1094
        out = StringIO()
1206
 
        runner = TextTestRunner(stream=out, verbosity=2)
 
1095
        runner = tests.TextTestRunner(stream=out, verbosity=2)
1207
1096
        test = unittest.FunctionTestCase(not_applicable_test)
1208
1097
        result = self.run_test_runner(runner, test)
1209
1098
        self._log_file.write(out.getvalue())
1216
1105
 
1217
1106
    def test_not_applicable_demo(self):
1218
1107
        # just so you can see it in the test output
1219
 
        raise TestNotApplicable('this test is just a demonstation')
 
1108
        raise tests.TestNotApplicable('this test is just a demonstation')
1220
1109
 
1221
1110
    def test_unsupported_features_listed(self):
1222
1111
        """When unsupported features are encountered they are detailed."""
1223
 
        class Feature1(Feature):
 
1112
        class Feature1(tests.Feature):
1224
1113
            def _probe(self): return False
1225
 
        class Feature2(Feature):
 
1114
        class Feature2(tests.Feature):
1226
1115
            def _probe(self): return False
1227
1116
        # create sample tests
1228
1117
        test1 = SampleTestCase('_test_pass')
1233
1122
        test.addTest(test1)
1234
1123
        test.addTest(test2)
1235
1124
        stream = StringIO()
1236
 
        runner = TextTestRunner(stream=stream)
 
1125
        runner = tests.TextTestRunner(stream=stream)
1237
1126
        result = self.run_test_runner(runner, test)
1238
1127
        lines = stream.getvalue().splitlines()
1239
1128
        self.assertEqual([
1250
1139
        workingtree = _get_bzr_source_tree()
1251
1140
        test = TestRunner('dummy_test')
1252
1141
        output = StringIO()
1253
 
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
 
1142
        runner = tests.TextTestRunner(stream=self._log_file,
 
1143
                                      bench_history=output)
1254
1144
        result = self.run_test_runner(runner, test)
1255
1145
        output_string = output.getvalue()
1256
1146
        self.assertContainsRe(output_string, "--date [0-9.]+")
1267
1157
    def test_success_log_deleted(self):
1268
1158
        """Successful tests have their log deleted"""
1269
1159
 
1270
 
        class LogTester(TestCase):
 
1160
        class LogTester(tests.TestCase):
1271
1161
 
1272
1162
            def test_success(self):
1273
1163
                self.log('this will be removed\n')
1274
1164
 
1275
 
        sio = cStringIO.StringIO()
1276
 
        runner = TextTestRunner(stream=sio)
 
1165
        sio = StringIO()
 
1166
        runner = tests.TextTestRunner(stream=sio)
1277
1167
        test = LogTester('test_success')
1278
1168
        result = self.run_test_runner(runner, test)
1279
1169
 
1282
1172
    def test_skipped_log_deleted(self):
1283
1173
        """Skipped tests have their log deleted"""
1284
1174
 
1285
 
        class LogTester(TestCase):
 
1175
        class LogTester(tests.TestCase):
1286
1176
 
1287
1177
            def test_skipped(self):
1288
1178
                self.log('this will be removed\n')
1289
1179
                raise tests.TestSkipped()
1290
1180
 
1291
 
        sio = cStringIO.StringIO()
1292
 
        runner = TextTestRunner(stream=sio)
 
1181
        sio = StringIO()
 
1182
        runner = tests.TextTestRunner(stream=sio)
1293
1183
        test = LogTester('test_skipped')
1294
1184
        result = self.run_test_runner(runner, test)
1295
1185
 
1298
1188
    def test_not_aplicable_log_deleted(self):
1299
1189
        """Not applicable tests have their log deleted"""
1300
1190
 
1301
 
        class LogTester(TestCase):
 
1191
        class LogTester(tests.TestCase):
1302
1192
 
1303
1193
            def test_not_applicable(self):
1304
1194
                self.log('this will be removed\n')
1305
1195
                raise tests.TestNotApplicable()
1306
1196
 
1307
 
        sio = cStringIO.StringIO()
1308
 
        runner = TextTestRunner(stream=sio)
 
1197
        sio = StringIO()
 
1198
        runner = tests.TextTestRunner(stream=sio)
1309
1199
        test = LogTester('test_not_applicable')
1310
1200
        result = self.run_test_runner(runner, test)
1311
1201
 
1314
1204
    def test_known_failure_log_deleted(self):
1315
1205
        """Know failure tests have their log deleted"""
1316
1206
 
1317
 
        class LogTester(TestCase):
 
1207
        class LogTester(tests.TestCase):
1318
1208
 
1319
1209
            def test_known_failure(self):
1320
1210
                self.log('this will be removed\n')
1321
1211
                raise tests.KnownFailure()
1322
1212
 
1323
 
        sio = cStringIO.StringIO()
1324
 
        runner = TextTestRunner(stream=sio)
 
1213
        sio = StringIO()
 
1214
        runner = tests.TextTestRunner(stream=sio)
1325
1215
        test = LogTester('test_known_failure')
1326
1216
        result = self.run_test_runner(runner, test)
1327
1217
 
1330
1220
    def test_fail_log_kept(self):
1331
1221
        """Failed tests have their log kept"""
1332
1222
 
1333
 
        class LogTester(TestCase):
 
1223
        class LogTester(tests.TestCase):
1334
1224
 
1335
1225
            def test_fail(self):
1336
1226
                self.log('this will be kept\n')
1337
1227
                self.fail('this test fails')
1338
1228
 
1339
 
        sio = cStringIO.StringIO()
1340
 
        runner = TextTestRunner(stream=sio)
 
1229
        sio = StringIO()
 
1230
        runner = tests.TextTestRunner(stream=sio)
1341
1231
        test = LogTester('test_fail')
1342
1232
        result = self.run_test_runner(runner, test)
1343
1233
 
1352
1242
    def test_error_log_kept(self):
1353
1243
        """Tests with errors have their log kept"""
1354
1244
 
1355
 
        class LogTester(TestCase):
 
1245
        class LogTester(tests.TestCase):
1356
1246
 
1357
1247
            def test_error(self):
1358
1248
                self.log('this will be kept\n')
1359
1249
                raise ValueError('random exception raised')
1360
1250
 
1361
 
        sio = cStringIO.StringIO()
1362
 
        runner = TextTestRunner(stream=sio)
 
1251
        sio = StringIO()
 
1252
        runner = tests.TextTestRunner(stream=sio)
1363
1253
        test = LogTester('test_error')
1364
1254
        result = self.run_test_runner(runner, test)
1365
1255
 
1372
1262
        self.assertEqual(log, test._log_contents)
1373
1263
 
1374
1264
 
1375
 
class SampleTestCase(TestCase):
 
1265
class SampleTestCase(tests.TestCase):
1376
1266
 
1377
1267
    def _test_pass(self):
1378
1268
        pass
1380
1270
class _TestException(Exception):
1381
1271
    pass
1382
1272
 
1383
 
class TestTestCase(TestCase):
 
1273
 
 
1274
class TestTestCase(tests.TestCase):
1384
1275
    """Tests that test the core bzrlib TestCase."""
1385
1276
 
1386
1277
    def test_assertLength_matches_empty(self):
1403
1294
            exception.args[0])
1404
1295
 
1405
1296
    def test_base_setUp_not_called_causes_failure(self):
1406
 
        class TestCaseWithBrokenSetUp(TestCase):
 
1297
        class TestCaseWithBrokenSetUp(tests.TestCase):
1407
1298
            def setUp(self):
1408
1299
                pass # does not call TestCase.setUp
1409
1300
            def test_foo(self):
1415
1306
        self.assertEqual(1, result.testsRun)
1416
1307
 
1417
1308
    def test_base_tearDown_not_called_causes_failure(self):
1418
 
        class TestCaseWithBrokenTearDown(TestCase):
 
1309
        class TestCaseWithBrokenTearDown(tests.TestCase):
1419
1310
            def tearDown(self):
1420
1311
                pass # does not call TestCase.tearDown
1421
1312
            def test_foo(self):
1429
1320
    def test_debug_flags_sanitised(self):
1430
1321
        """The bzrlib debug flags should be sanitised by setUp."""
1431
1322
        if 'allow_debug' in tests.selftest_debug_flags:
1432
 
            raise TestNotApplicable(
 
1323
            raise tests.TestNotApplicable(
1433
1324
                '-Eallow_debug option prevents debug flag sanitisation')
1434
1325
        # we could set something and run a test that will check
1435
1326
        # it gets santised, but this is probably sufficient for now:
1436
1327
        # if someone runs the test with -Dsomething it will error.
1437
 
        self.assertEqual(set(), bzrlib.debug.debug_flags)
 
1328
        flags = set()
 
1329
        if self._lock_check_thorough:
 
1330
            flags.add('strict_locks')
 
1331
        self.assertEqual(flags, bzrlib.debug.debug_flags)
1438
1332
 
1439
1333
    def change_selftest_debug_flags(self, new_flags):
1440
1334
        orig_selftest_flags = tests.selftest_debug_flags
1450
1344
        """
1451
1345
        self.change_selftest_debug_flags(set(['allow_debug']))
1452
1346
        bzrlib.debug.debug_flags = set(['a-flag'])
1453
 
        class TestThatRecordsFlags(TestCase):
1454
 
            def test_foo(nested_self):
1455
 
                self.flags = set(bzrlib.debug.debug_flags)
1456
 
        test = TestThatRecordsFlags('test_foo')
1457
 
        test.run(self.make_test_result())
1458
 
        self.assertEqual(set(['a-flag']), self.flags)
 
1347
        class TestThatRecordsFlags(tests.TestCase):
 
1348
            def test_foo(nested_self):
 
1349
                self.flags = set(bzrlib.debug.debug_flags)
 
1350
        test = TestThatRecordsFlags('test_foo')
 
1351
        test.run(self.make_test_result())
 
1352
        flags = set(['a-flag'])
 
1353
        if 'disable_lock_checks' not in tests.selftest_debug_flags:
 
1354
            flags.add('strict_locks')
 
1355
        self.assertEqual(flags, self.flags)
 
1356
 
 
1357
    def test_disable_lock_checks(self):
 
1358
        """The -Edisable_lock_checks flag disables thorough checks."""
 
1359
        class TestThatRecordsFlags(tests.TestCase):
 
1360
            def test_foo(nested_self):
 
1361
                self.flags = set(bzrlib.debug.debug_flags)
 
1362
                self.test_lock_check_thorough = nested_self._lock_check_thorough
 
1363
        self.change_selftest_debug_flags(set())
 
1364
        test = TestThatRecordsFlags('test_foo')
 
1365
        test.run(self.make_test_result())
 
1366
        # By default we do strict lock checking and thorough lock/unlock
 
1367
        # tracking.
 
1368
        self.assertTrue(self.test_lock_check_thorough)
 
1369
        self.assertEqual(set(['strict_locks']), self.flags)
 
1370
        # Now set the disable_lock_checks flag, and show that this changed.
 
1371
        self.change_selftest_debug_flags(set(['disable_lock_checks']))
 
1372
        test = TestThatRecordsFlags('test_foo')
 
1373
        test.run(self.make_test_result())
 
1374
        self.assertFalse(self.test_lock_check_thorough)
 
1375
        self.assertEqual(set(), self.flags)
 
1376
 
 
1377
    def test_this_fails_strict_lock_check(self):
 
1378
        class TestThatRecordsFlags(tests.TestCase):
 
1379
            def test_foo(nested_self):
 
1380
                self.flags1 = set(bzrlib.debug.debug_flags)
 
1381
                self.thisFailsStrictLockCheck()
 
1382
                self.flags2 = set(bzrlib.debug.debug_flags)
 
1383
        # Make sure lock checking is active
 
1384
        self.change_selftest_debug_flags(set())
 
1385
        test = TestThatRecordsFlags('test_foo')
 
1386
        test.run(self.make_test_result())
 
1387
        self.assertEqual(set(['strict_locks']), self.flags1)
 
1388
        self.assertEqual(set(), self.flags2)
1459
1389
 
1460
1390
    def test_debug_flags_restored(self):
1461
1391
        """The bzrlib debug flags should be restored to their original state
1464
1394
        self.change_selftest_debug_flags(set(['allow_debug']))
1465
1395
        # Now run a test that modifies debug.debug_flags.
1466
1396
        bzrlib.debug.debug_flags = set(['original-state'])
1467
 
        class TestThatModifiesFlags(TestCase):
 
1397
        class TestThatModifiesFlags(tests.TestCase):
1468
1398
            def test_foo(self):
1469
1399
                bzrlib.debug.debug_flags = set(['modified'])
1470
1400
        test = TestThatModifiesFlags('test_foo')
1472
1402
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1473
1403
 
1474
1404
    def make_test_result(self):
1475
 
        return bzrlib.tests.TextTestResult(
1476
 
            self._log_file, descriptions=0, verbosity=1)
 
1405
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1477
1406
 
1478
1407
    def inner_test(self):
1479
1408
        # the inner child test
1517
1446
        result = bzrlib.tests.VerboseTestResult(
1518
1447
            unittest._WritelnDecorator(output_stream),
1519
1448
            descriptions=0,
1520
 
            verbosity=2,
1521
 
            num_tests=sample_test.countTestCases())
 
1449
            verbosity=2)
1522
1450
        sample_test.run(result)
1523
1451
        self.assertContainsRe(
1524
1452
            output_stream.getvalue(),
1525
 
            r"\d+ms/ +\d+ms\n$")
 
1453
            r"\d+ms\*\n$")
1526
1454
 
1527
1455
    def test_hooks_sanitised(self):
1528
1456
        """The bzrlib hooks should be sanitised by setUp."""
1555
1483
 
1556
1484
    def test_knownFailure(self):
1557
1485
        """Self.knownFailure() should raise a KnownFailure exception."""
1558
 
        self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
 
1486
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
1559
1487
 
1560
1488
    def test_requireFeature_available(self):
1561
1489
        """self.requireFeature(available) is a no-op."""
1562
 
        class Available(Feature):
 
1490
        class Available(tests.Feature):
1563
1491
            def _probe(self):return True
1564
1492
        feature = Available()
1565
1493
        self.requireFeature(feature)
1566
1494
 
1567
1495
    def test_requireFeature_unavailable(self):
1568
1496
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1569
 
        class Unavailable(Feature):
 
1497
        class Unavailable(tests.Feature):
1570
1498
            def _probe(self):return False
1571
1499
        feature = Unavailable()
1572
 
        self.assertRaises(UnavailableFeature, self.requireFeature, feature)
 
1500
        self.assertRaises(tests.UnavailableFeature,
 
1501
                          self.requireFeature, feature)
1573
1502
 
1574
1503
    def test_run_no_parameters(self):
1575
1504
        test = SampleTestCase('_test_pass')
1711
1640
        return sample_deprecated_function()
1712
1641
 
1713
1642
 
1714
 
class TestExtraAssertions(TestCase):
 
1643
class TestExtraAssertions(tests.TestCase):
1715
1644
    """Tests for new test assertions in bzrlib test suite"""
1716
1645
 
1717
1646
    def test_assert_isinstance(self):
1718
1647
        self.assertIsInstance(2, int)
1719
1648
        self.assertIsInstance(u'', basestring)
1720
 
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1649
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1650
        self.assertEquals(str(e),
 
1651
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
1721
1652
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
 
1653
        e = self.assertRaises(AssertionError,
 
1654
            self.assertIsInstance, None, int, "it's just not")
 
1655
        self.assertEquals(str(e),
 
1656
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
 
1657
            ": it's just not")
1722
1658
 
1723
1659
    def test_assertEndsWith(self):
1724
1660
        self.assertEndsWith('foo', 'oo')
1772
1708
        self.callDeprecated([], testfunc, be_deprecated=False)
1773
1709
 
1774
1710
 
1775
 
class TestWarningTests(TestCase):
 
1711
class TestWarningTests(tests.TestCase):
1776
1712
    """Tests for calling methods that raise warnings."""
1777
1713
 
1778
1714
    def test_callCatchWarnings(self):
1788
1724
        self.assertEquals("this is your last warning", str(w0))
1789
1725
 
1790
1726
 
1791
 
class TestConvenienceMakers(TestCaseWithTransport):
 
1727
class TestConvenienceMakers(tests.TestCaseWithTransport):
1792
1728
    """Test for the make_* convenience functions."""
1793
1729
 
1794
1730
    def test_make_branch_and_tree_with_format(self):
1807
1743
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1808
1744
 
1809
1745
 
1810
 
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
 
1746
class TestSFTPMakeBranchAndTree(test_sftp_transport.TestCaseWithSFTPServer):
1811
1747
 
1812
1748
    def test_make_tree_for_sftp_branch(self):
1813
1749
        """Transports backed by local directories create local trees."""
1814
 
 
 
1750
        # NB: This is arguably a bug in the definition of make_branch_and_tree.
1815
1751
        tree = self.make_branch_and_tree('t1')
1816
1752
        base = tree.bzrdir.root_transport.base
1817
1753
        self.failIf(base.startswith('sftp'),
1822
1758
                tree.branch.repository.bzrdir.root_transport)
1823
1759
 
1824
1760
 
1825
 
class TestSelftest(TestCase):
 
1761
class SelfTestHelper:
 
1762
 
 
1763
    def run_selftest(self, **kwargs):
 
1764
        """Run selftest returning its output."""
 
1765
        output = StringIO()
 
1766
        old_transport = bzrlib.tests.default_transport
 
1767
        old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
 
1768
        tests.TestCaseWithMemoryTransport.TEST_ROOT = None
 
1769
        try:
 
1770
            self.assertEqual(True, tests.selftest(stream=output, **kwargs))
 
1771
        finally:
 
1772
            bzrlib.tests.default_transport = old_transport
 
1773
            tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
 
1774
        output.seek(0)
 
1775
        return output
 
1776
 
 
1777
 
 
1778
class TestSelftest(tests.TestCase, SelfTestHelper):
1826
1779
    """Tests of bzrlib.tests.selftest."""
1827
1780
 
1828
1781
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1829
1782
        factory_called = []
1830
1783
        def factory():
1831
1784
            factory_called.append(True)
1832
 
            return TestSuite()
 
1785
            return TestUtil.TestSuite()
1833
1786
        out = StringIO()
1834
1787
        err = StringIO()
1835
1788
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1836
1789
            test_suite_factory=factory)
1837
1790
        self.assertEqual([True], factory_called)
1838
1791
 
1839
 
 
1840
 
class TestKnownFailure(TestCase):
 
1792
    def factory(self):
 
1793
        """A test suite factory."""
 
1794
        class Test(tests.TestCase):
 
1795
            def a(self):
 
1796
                pass
 
1797
            def b(self):
 
1798
                pass
 
1799
            def c(self):
 
1800
                pass
 
1801
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
 
1802
 
 
1803
    def test_list_only(self):
 
1804
        output = self.run_selftest(test_suite_factory=self.factory,
 
1805
            list_only=True)
 
1806
        self.assertEqual(3, len(output.readlines()))
 
1807
 
 
1808
    def test_list_only_filtered(self):
 
1809
        output = self.run_selftest(test_suite_factory=self.factory,
 
1810
            list_only=True, pattern="Test.b")
 
1811
        self.assertEndsWith(output.getvalue(), "Test.b\n")
 
1812
        self.assertLength(1, output.readlines())
 
1813
 
 
1814
    def test_list_only_excludes(self):
 
1815
        output = self.run_selftest(test_suite_factory=self.factory,
 
1816
            list_only=True, exclude_pattern="Test.b")
 
1817
        self.assertNotContainsRe("Test.b", output.getvalue())
 
1818
        self.assertLength(2, output.readlines())
 
1819
 
 
1820
    def test_random(self):
 
1821
        # test randomising by listing a number of tests.
 
1822
        output_123 = self.run_selftest(test_suite_factory=self.factory,
 
1823
            list_only=True, random_seed="123")
 
1824
        output_234 = self.run_selftest(test_suite_factory=self.factory,
 
1825
            list_only=True, random_seed="234")
 
1826
        self.assertNotEqual(output_123, output_234)
 
1827
        # "Randominzing test order..\n\n
 
1828
        self.assertLength(5, output_123.readlines())
 
1829
        self.assertLength(5, output_234.readlines())
 
1830
 
 
1831
    def test_random_reuse_is_same_order(self):
 
1832
        # test randomising by listing a number of tests.
 
1833
        expected = self.run_selftest(test_suite_factory=self.factory,
 
1834
            list_only=True, random_seed="123")
 
1835
        repeated = self.run_selftest(test_suite_factory=self.factory,
 
1836
            list_only=True, random_seed="123")
 
1837
        self.assertEqual(expected.getvalue(), repeated.getvalue())
 
1838
 
 
1839
    def test_runner_class(self):
 
1840
        self.requireFeature(SubUnitFeature)
 
1841
        from subunit import ProtocolTestCase
 
1842
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
 
1843
            test_suite_factory=self.factory)
 
1844
        test = ProtocolTestCase(stream)
 
1845
        result = unittest.TestResult()
 
1846
        test.run(result)
 
1847
        self.assertEqual(3, result.testsRun)
 
1848
 
 
1849
    def test_starting_with_single_argument(self):
 
1850
        output = self.run_selftest(test_suite_factory=self.factory,
 
1851
            starting_with=['bzrlib.tests.test_selftest.Test.a'],
 
1852
            list_only=True)
 
1853
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
 
1854
            output.getvalue())
 
1855
 
 
1856
    def test_starting_with_multiple_argument(self):
 
1857
        output = self.run_selftest(test_suite_factory=self.factory,
 
1858
            starting_with=['bzrlib.tests.test_selftest.Test.a',
 
1859
                'bzrlib.tests.test_selftest.Test.b'],
 
1860
            list_only=True)
 
1861
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
 
1862
            'bzrlib.tests.test_selftest.Test.b\n',
 
1863
            output.getvalue())
 
1864
 
 
1865
    def check_transport_set(self, transport_server):
 
1866
        captured_transport = []
 
1867
        def seen_transport(a_transport):
 
1868
            captured_transport.append(a_transport)
 
1869
        class Capture(tests.TestCase):
 
1870
            def a(self):
 
1871
                seen_transport(bzrlib.tests.default_transport)
 
1872
        def factory():
 
1873
            return TestUtil.TestSuite([Capture("a")])
 
1874
        self.run_selftest(transport=transport_server, test_suite_factory=factory)
 
1875
        self.assertEqual(transport_server, captured_transport[0])
 
1876
 
 
1877
    def test_transport_sftp(self):
 
1878
        try:
 
1879
            import bzrlib.transport.sftp
 
1880
        except ParamikoNotPresent:
 
1881
            raise TestSkipped("Paramiko not present")
 
1882
        self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
 
1883
 
 
1884
    def test_transport_memory(self):
 
1885
        self.check_transport_set(bzrlib.transport.memory.MemoryServer)
 
1886
 
 
1887
 
 
1888
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
 
1889
    # Does IO: reads test.list
 
1890
 
 
1891
    def test_load_list(self):
 
1892
        # Provide a list with one test - this test.
 
1893
        test_id_line = '%s\n' % self.id()
 
1894
        self.build_tree_contents([('test.list', test_id_line)])
 
1895
        # And generate a list of the tests in  the suite.
 
1896
        stream = self.run_selftest(load_list='test.list', list_only=True)
 
1897
        self.assertEqual(test_id_line, stream.getvalue())
 
1898
 
 
1899
    def test_load_unknown(self):
 
1900
        # Provide a list with one test - this test.
 
1901
        # And generate a list of the tests in  the suite.
 
1902
        err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
 
1903
            load_list='missing file name', list_only=True)
 
1904
 
 
1905
 
 
1906
class TestRunBzr(tests.TestCase):
 
1907
 
 
1908
    out = ''
 
1909
    err = ''
 
1910
 
 
1911
    def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
 
1912
                         working_dir=None):
 
1913
        """Override _run_bzr_core to test how it is invoked by run_bzr.
 
1914
 
 
1915
        Attempts to run bzr from inside this class don't actually run it.
 
1916
 
 
1917
        We test how run_bzr actually invokes bzr in another location.
 
1918
        Here we only need to test that it is run_bzr passes the right
 
1919
        parameters to run_bzr.
 
1920
        """
 
1921
        self.argv = list(argv)
 
1922
        self.retcode = retcode
 
1923
        self.encoding = encoding
 
1924
        self.stdin = stdin
 
1925
        self.working_dir = working_dir
 
1926
        return self.out, self.err
 
1927
 
 
1928
    def test_run_bzr_error(self):
 
1929
        self.out = "It sure does!\n"
 
1930
        out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
 
1931
        self.assertEqual(['rocks'], self.argv)
 
1932
        self.assertEqual(34, self.retcode)
 
1933
        self.assertEqual(out, 'It sure does!\n')
 
1934
 
 
1935
    def test_run_bzr_error_regexes(self):
 
1936
        self.out = ''
 
1937
        self.err = "bzr: ERROR: foobarbaz is not versioned"
 
1938
        out, err = self.run_bzr_error(
 
1939
                ["bzr: ERROR: foobarbaz is not versioned"],
 
1940
                ['file-id', 'foobarbaz'])
 
1941
 
 
1942
    def test_encoding(self):
 
1943
        """Test that run_bzr passes encoding to _run_bzr_core"""
 
1944
        self.run_bzr('foo bar')
 
1945
        self.assertEqual(None, self.encoding)
 
1946
        self.assertEqual(['foo', 'bar'], self.argv)
 
1947
 
 
1948
        self.run_bzr('foo bar', encoding='baz')
 
1949
        self.assertEqual('baz', self.encoding)
 
1950
        self.assertEqual(['foo', 'bar'], self.argv)
 
1951
 
 
1952
    def test_retcode(self):
 
1953
        """Test that run_bzr passes retcode to _run_bzr_core"""
 
1954
        # Default is retcode == 0
 
1955
        self.run_bzr('foo bar')
 
1956
        self.assertEqual(0, self.retcode)
 
1957
        self.assertEqual(['foo', 'bar'], self.argv)
 
1958
 
 
1959
        self.run_bzr('foo bar', retcode=1)
 
1960
        self.assertEqual(1, self.retcode)
 
1961
        self.assertEqual(['foo', 'bar'], self.argv)
 
1962
 
 
1963
        self.run_bzr('foo bar', retcode=None)
 
1964
        self.assertEqual(None, self.retcode)
 
1965
        self.assertEqual(['foo', 'bar'], self.argv)
 
1966
 
 
1967
        self.run_bzr(['foo', 'bar'], retcode=3)
 
1968
        self.assertEqual(3, self.retcode)
 
1969
        self.assertEqual(['foo', 'bar'], self.argv)
 
1970
 
 
1971
    def test_stdin(self):
 
1972
        # test that the stdin keyword to run_bzr is passed through to
 
1973
        # _run_bzr_core as-is. We do this by overriding
 
1974
        # _run_bzr_core in this class, and then calling run_bzr,
 
1975
        # which is a convenience function for _run_bzr_core, so
 
1976
        # should invoke it.
 
1977
        self.run_bzr('foo bar', stdin='gam')
 
1978
        self.assertEqual('gam', self.stdin)
 
1979
        self.assertEqual(['foo', 'bar'], self.argv)
 
1980
 
 
1981
        self.run_bzr('foo bar', stdin='zippy')
 
1982
        self.assertEqual('zippy', self.stdin)
 
1983
        self.assertEqual(['foo', 'bar'], self.argv)
 
1984
 
 
1985
    def test_working_dir(self):
 
1986
        """Test that run_bzr passes working_dir to _run_bzr_core"""
 
1987
        self.run_bzr('foo bar')
 
1988
        self.assertEqual(None, self.working_dir)
 
1989
        self.assertEqual(['foo', 'bar'], self.argv)
 
1990
 
 
1991
        self.run_bzr('foo bar', working_dir='baz')
 
1992
        self.assertEqual('baz', self.working_dir)
 
1993
        self.assertEqual(['foo', 'bar'], self.argv)
 
1994
 
 
1995
    def test_reject_extra_keyword_arguments(self):
 
1996
        self.assertRaises(TypeError, self.run_bzr, "foo bar",
 
1997
                          error_regex=['error message'])
 
1998
 
 
1999
 
 
2000
class TestRunBzrCaptured(tests.TestCaseWithTransport):
 
2001
    # Does IO when testing the working_dir parameter.
 
2002
 
 
2003
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
2004
                         a_callable=None, *args, **kwargs):
 
2005
        self.stdin = stdin
 
2006
        self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
 
2007
        self.factory = bzrlib.ui.ui_factory
 
2008
        self.working_dir = osutils.getcwd()
 
2009
        stdout.write('foo\n')
 
2010
        stderr.write('bar\n')
 
2011
        return 0
 
2012
 
 
2013
    def test_stdin(self):
 
2014
        # test that the stdin keyword to _run_bzr_core is passed through to
 
2015
        # apply_redirected as a StringIO. We do this by overriding
 
2016
        # apply_redirected in this class, and then calling _run_bzr_core,
 
2017
        # which calls apply_redirected.
 
2018
        self.run_bzr(['foo', 'bar'], stdin='gam')
 
2019
        self.assertEqual('gam', self.stdin.read())
 
2020
        self.assertTrue(self.stdin is self.factory_stdin)
 
2021
        self.run_bzr(['foo', 'bar'], stdin='zippy')
 
2022
        self.assertEqual('zippy', self.stdin.read())
 
2023
        self.assertTrue(self.stdin is self.factory_stdin)
 
2024
 
 
2025
    def test_ui_factory(self):
 
2026
        # each invocation of self.run_bzr should get its
 
2027
        # own UI factory, which is an instance of TestUIFactory,
 
2028
        # with stdin, stdout and stderr attached to the stdin,
 
2029
        # stdout and stderr of the invoked run_bzr
 
2030
        current_factory = bzrlib.ui.ui_factory
 
2031
        self.run_bzr(['foo'])
 
2032
        self.failIf(current_factory is self.factory)
 
2033
        self.assertNotEqual(sys.stdout, self.factory.stdout)
 
2034
        self.assertNotEqual(sys.stderr, self.factory.stderr)
 
2035
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
 
2036
        self.assertEqual('bar\n', self.factory.stderr.getvalue())
 
2037
        self.assertIsInstance(self.factory, tests.TestUIFactory)
 
2038
 
 
2039
    def test_working_dir(self):
 
2040
        self.build_tree(['one/', 'two/'])
 
2041
        cwd = osutils.getcwd()
 
2042
 
 
2043
        # Default is to work in the current directory
 
2044
        self.run_bzr(['foo', 'bar'])
 
2045
        self.assertEqual(cwd, self.working_dir)
 
2046
 
 
2047
        self.run_bzr(['foo', 'bar'], working_dir=None)
 
2048
        self.assertEqual(cwd, self.working_dir)
 
2049
 
 
2050
        # The function should be run in the alternative directory
 
2051
        # but afterwards the current working dir shouldn't be changed
 
2052
        self.run_bzr(['foo', 'bar'], working_dir='one')
 
2053
        self.assertNotEqual(cwd, self.working_dir)
 
2054
        self.assertEndsWith(self.working_dir, 'one')
 
2055
        self.assertEqual(cwd, osutils.getcwd())
 
2056
 
 
2057
        self.run_bzr(['foo', 'bar'], working_dir='two')
 
2058
        self.assertNotEqual(cwd, self.working_dir)
 
2059
        self.assertEndsWith(self.working_dir, 'two')
 
2060
        self.assertEqual(cwd, osutils.getcwd())
 
2061
 
 
2062
 
 
2063
class StubProcess(object):
 
2064
    """A stub process for testing run_bzr_subprocess."""
 
2065
    
 
2066
    def __init__(self, out="", err="", retcode=0):
 
2067
        self.out = out
 
2068
        self.err = err
 
2069
        self.returncode = retcode
 
2070
 
 
2071
    def communicate(self):
 
2072
        return self.out, self.err
 
2073
 
 
2074
 
 
2075
class TestRunBzrSubprocess(tests.TestCaseWithTransport):
 
2076
 
 
2077
    def setUp(self):
 
2078
        tests.TestCaseWithTransport.setUp(self)
 
2079
        self.subprocess_calls = []
 
2080
 
 
2081
    def start_bzr_subprocess(self, process_args, env_changes=None,
 
2082
                             skip_if_plan_to_signal=False,
 
2083
                             working_dir=None,
 
2084
                             allow_plugins=False):
 
2085
        """capture what run_bzr_subprocess tries to do."""
 
2086
        self.subprocess_calls.append({'process_args':process_args,
 
2087
            'env_changes':env_changes,
 
2088
            'skip_if_plan_to_signal':skip_if_plan_to_signal,
 
2089
            'working_dir':working_dir, 'allow_plugins':allow_plugins})
 
2090
        return self.next_subprocess
 
2091
 
 
2092
    def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
 
2093
        """Run run_bzr_subprocess with args and kwargs using a stubbed process.
 
2094
 
 
2095
        Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
 
2096
        that will return static results. This assertion method populates those
 
2097
        results and also checks the arguments run_bzr_subprocess generates.
 
2098
        """
 
2099
        self.next_subprocess = process
 
2100
        try:
 
2101
            result = self.run_bzr_subprocess(*args, **kwargs)
 
2102
        except:
 
2103
            self.next_subprocess = None
 
2104
            for key, expected in expected_args.iteritems():
 
2105
                self.assertEqual(expected, self.subprocess_calls[-1][key])
 
2106
            raise
 
2107
        else:
 
2108
            self.next_subprocess = None
 
2109
            for key, expected in expected_args.iteritems():
 
2110
                self.assertEqual(expected, self.subprocess_calls[-1][key])
 
2111
            return result
 
2112
 
 
2113
    def test_run_bzr_subprocess(self):
 
2114
        """The run_bzr_helper_external command behaves nicely."""
 
2115
        self.assertRunBzrSubprocess({'process_args':['--version']},
 
2116
            StubProcess(), '--version')
 
2117
        self.assertRunBzrSubprocess({'process_args':['--version']},
 
2118
            StubProcess(), ['--version'])
 
2119
        # retcode=None disables retcode checking
 
2120
        result = self.assertRunBzrSubprocess({},
 
2121
            StubProcess(retcode=3), '--version', retcode=None)
 
2122
        result = self.assertRunBzrSubprocess({},
 
2123
            StubProcess(out="is free software"), '--version')
 
2124
        self.assertContainsRe(result[0], 'is free software')
 
2125
        # Running a subcommand that is missing errors
 
2126
        self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
 
2127
            {'process_args':['--versionn']}, StubProcess(retcode=3),
 
2128
            '--versionn')
 
2129
        # Unless it is told to expect the error from the subprocess
 
2130
        result = self.assertRunBzrSubprocess({},
 
2131
            StubProcess(retcode=3), '--versionn', retcode=3)
 
2132
        # Or to ignore retcode checking
 
2133
        result = self.assertRunBzrSubprocess({},
 
2134
            StubProcess(err="unknown command", retcode=3), '--versionn',
 
2135
            retcode=None)
 
2136
        self.assertContainsRe(result[1], 'unknown command')
 
2137
 
 
2138
    def test_env_change_passes_through(self):
 
2139
        self.assertRunBzrSubprocess(
 
2140
            {'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
 
2141
            StubProcess(), '',
 
2142
            env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
 
2143
 
 
2144
    def test_no_working_dir_passed_as_None(self):
 
2145
        self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
 
2146
 
 
2147
    def test_no_working_dir_passed_through(self):
 
2148
        self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
 
2149
            working_dir='dir')
 
2150
 
 
2151
    def test_run_bzr_subprocess_no_plugins(self):
 
2152
        self.assertRunBzrSubprocess({'allow_plugins': False},
 
2153
            StubProcess(), '')
 
2154
 
 
2155
    def test_allow_plugins(self):
 
2156
        self.assertRunBzrSubprocess({'allow_plugins': True},
 
2157
            StubProcess(), '', allow_plugins=True)
 
2158
 
 
2159
 
 
2160
class _DontSpawnProcess(Exception):
 
2161
    """A simple exception which just allows us to skip unnecessary steps"""
 
2162
 
 
2163
 
 
2164
class TestStartBzrSubProcess(tests.TestCase):
 
2165
 
 
2166
    def check_popen_state(self):
 
2167
        """Replace to make assertions when popen is called."""
 
2168
 
 
2169
    def _popen(self, *args, **kwargs):
 
2170
        """Record the command that is run, so that we can ensure it is correct"""
 
2171
        self.check_popen_state()
 
2172
        self._popen_args = args
 
2173
        self._popen_kwargs = kwargs
 
2174
        raise _DontSpawnProcess()
 
2175
 
 
2176
    def test_run_bzr_subprocess_no_plugins(self):
 
2177
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
 
2178
        command = self._popen_args[0]
 
2179
        self.assertEqual(sys.executable, command[0])
 
2180
        self.assertEqual(self.get_bzr_path(), command[1])
 
2181
        self.assertEqual(['--no-plugins'], command[2:])
 
2182
 
 
2183
    def test_allow_plugins(self):
 
2184
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2185
            allow_plugins=True)
 
2186
        command = self._popen_args[0]
 
2187
        self.assertEqual([], command[2:])
 
2188
 
 
2189
    def test_set_env(self):
 
2190
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2191
        # set in the child
 
2192
        def check_environment():
 
2193
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
 
2194
        self.check_popen_state = check_environment
 
2195
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2196
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2197
        # not set in theparent
 
2198
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2199
 
 
2200
    def test_run_bzr_subprocess_env_del(self):
 
2201
        """run_bzr_subprocess can remove environment variables too."""
 
2202
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2203
        def check_environment():
 
2204
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2205
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
 
2206
        self.check_popen_state = check_environment
 
2207
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2208
            env_changes={'EXISTANT_ENV_VAR':None})
 
2209
        # Still set in parent
 
2210
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
 
2211
        del os.environ['EXISTANT_ENV_VAR']
 
2212
 
 
2213
    def test_env_del_missing(self):
 
2214
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
 
2215
        def check_environment():
 
2216
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
 
2217
        self.check_popen_state = check_environment
 
2218
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2219
            env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2220
 
 
2221
    def test_working_dir(self):
 
2222
        """Test that we can specify the working dir for the child"""
 
2223
        orig_getcwd = osutils.getcwd
 
2224
        orig_chdir = os.chdir
 
2225
        chdirs = []
 
2226
        def chdir(path):
 
2227
            chdirs.append(path)
 
2228
        os.chdir = chdir
 
2229
        try:
 
2230
            def getcwd():
 
2231
                return 'current'
 
2232
            osutils.getcwd = getcwd
 
2233
            try:
 
2234
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2235
                    working_dir='foo')
 
2236
            finally:
 
2237
                osutils.getcwd = orig_getcwd
 
2238
        finally:
 
2239
            os.chdir = orig_chdir
 
2240
        self.assertEqual(['foo', 'current'], chdirs)
 
2241
 
 
2242
 
 
2243
class TestBzrSubprocess(tests.TestCaseWithTransport):
 
2244
 
 
2245
    def test_start_and_stop_bzr_subprocess(self):
 
2246
        """We can start and perform other test actions while that process is
 
2247
        still alive.
 
2248
        """
 
2249
        process = self.start_bzr_subprocess(['--version'])
 
2250
        result = self.finish_bzr_subprocess(process)
 
2251
        self.assertContainsRe(result[0], 'is free software')
 
2252
        self.assertEqual('', result[1])
 
2253
 
 
2254
    def test_start_and_stop_bzr_subprocess_with_error(self):
 
2255
        """finish_bzr_subprocess allows specification of the desired exit code.
 
2256
        """
 
2257
        process = self.start_bzr_subprocess(['--versionn'])
 
2258
        result = self.finish_bzr_subprocess(process, retcode=3)
 
2259
        self.assertEqual('', result[0])
 
2260
        self.assertContainsRe(result[1], 'unknown command')
 
2261
 
 
2262
    def test_start_and_stop_bzr_subprocess_ignoring_retcode(self):
 
2263
        """finish_bzr_subprocess allows the exit code to be ignored."""
 
2264
        process = self.start_bzr_subprocess(['--versionn'])
 
2265
        result = self.finish_bzr_subprocess(process, retcode=None)
 
2266
        self.assertEqual('', result[0])
 
2267
        self.assertContainsRe(result[1], 'unknown command')
 
2268
 
 
2269
    def test_start_and_stop_bzr_subprocess_with_unexpected_retcode(self):
 
2270
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2271
        not the expected one.
 
2272
        """
 
2273
        process = self.start_bzr_subprocess(['--versionn'])
 
2274
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
 
2275
                          process)
 
2276
 
 
2277
    def test_start_and_stop_bzr_subprocess_send_signal(self):
 
2278
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2279
        not the expected one.
 
2280
        """
 
2281
        process = self.start_bzr_subprocess(['wait-until-signalled'],
 
2282
                                            skip_if_plan_to_signal=True)
 
2283
        self.assertEqual('running\n', process.stdout.readline())
 
2284
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
 
2285
                                            retcode=3)
 
2286
        self.assertEqual('', result[0])
 
2287
        self.assertEqual('bzr: interrupted\n', result[1])
 
2288
 
 
2289
    def test_start_and_stop_working_dir(self):
 
2290
        cwd = osutils.getcwd()
 
2291
        self.make_branch_and_tree('one')
 
2292
        process = self.start_bzr_subprocess(['root'], working_dir='one')
 
2293
        result = self.finish_bzr_subprocess(process, universal_newlines=True)
 
2294
        self.assertEndsWith(result[0], 'one\n')
 
2295
        self.assertEqual('', result[1])
 
2296
 
 
2297
 
 
2298
class TestKnownFailure(tests.TestCase):
1841
2299
 
1842
2300
    def test_known_failure(self):
1843
2301
        """Check that KnownFailure is defined appropriately."""
1844
2302
        # a KnownFailure is an assertion error for compatability with unaware
1845
2303
        # runners.
1846
 
        self.assertIsInstance(KnownFailure(""), AssertionError)
 
2304
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
1847
2305
 
1848
2306
    def test_expect_failure(self):
1849
2307
        try:
1850
2308
            self.expectFailure("Doomed to failure", self.assertTrue, False)
1851
 
        except KnownFailure, e:
 
2309
        except tests.KnownFailure, e:
1852
2310
            self.assertEqual('Doomed to failure', e.args[0])
1853
2311
        try:
1854
2312
            self.expectFailure("Doomed to failure", self.assertTrue, True)
1859
2317
            self.fail('Assertion not raised')
1860
2318
 
1861
2319
 
1862
 
class TestFeature(TestCase):
 
2320
class TestFeature(tests.TestCase):
1863
2321
 
1864
2322
    def test_caching(self):
1865
2323
        """Feature._probe is called by the feature at most once."""
1866
 
        class InstrumentedFeature(Feature):
 
2324
        class InstrumentedFeature(tests.Feature):
1867
2325
            def __init__(self):
1868
 
                Feature.__init__(self)
 
2326
                super(InstrumentedFeature, self).__init__()
1869
2327
                self.calls = []
1870
2328
            def _probe(self):
1871
2329
                self.calls.append('_probe')
1878
2336
 
1879
2337
    def test_named_str(self):
1880
2338
        """Feature.__str__ should thunk to feature_name()."""
1881
 
        class NamedFeature(Feature):
 
2339
        class NamedFeature(tests.Feature):
1882
2340
            def feature_name(self):
1883
2341
                return 'symlinks'
1884
2342
        feature = NamedFeature()
1886
2344
 
1887
2345
    def test_default_str(self):
1888
2346
        """Feature.__str__ should default to __class__.__name__."""
1889
 
        class NamedFeature(Feature):
 
2347
        class NamedFeature(tests.Feature):
1890
2348
            pass
1891
2349
        feature = NamedFeature()
1892
2350
        self.assertEqual('NamedFeature', str(feature))
1893
2351
 
1894
2352
 
1895
 
class TestUnavailableFeature(TestCase):
 
2353
class TestUnavailableFeature(tests.TestCase):
1896
2354
 
1897
2355
    def test_access_feature(self):
1898
 
        feature = Feature()
1899
 
        exception = UnavailableFeature(feature)
 
2356
        feature = tests.Feature()
 
2357
        exception = tests.UnavailableFeature(feature)
1900
2358
        self.assertIs(feature, exception.args[0])
1901
2359
 
1902
2360
 
1903
 
class TestSelftestFiltering(TestCase):
 
2361
class TestSelftestFiltering(tests.TestCase):
1904
2362
 
1905
2363
    def setUp(self):
1906
 
        TestCase.setUp(self)
 
2364
        tests.TestCase.setUp(self)
1907
2365
        self.suite = TestUtil.TestSuite()
1908
2366
        self.loader = TestUtil.TestLoader()
1909
 
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
1910
 
            'bzrlib.tests.test_selftest']))
 
2367
        self.suite.addTest(self.loader.loadTestsFromModule(
 
2368
            sys.modules['bzrlib.tests.test_selftest']))
1911
2369
        self.all_names = _test_ids(self.suite)
1912
2370
 
1913
2371
    def test_condition_id_re(self):
1914
2372
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1915
2373
            'test_condition_id_re')
1916
 
        filtered_suite = filter_suite_by_condition(self.suite,
1917
 
            condition_id_re('test_condition_id_re'))
 
2374
        filtered_suite = tests.filter_suite_by_condition(
 
2375
            self.suite, tests.condition_id_re('test_condition_id_re'))
1918
2376
        self.assertEqual([test_name], _test_ids(filtered_suite))
1919
2377
 
1920
2378
    def test_condition_id_in_list(self):
1921
2379
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1922
2380
                      'test_condition_id_in_list']
1923
2381
        id_list = tests.TestIdList(test_names)
1924
 
        filtered_suite = filter_suite_by_condition(
 
2382
        filtered_suite = tests.filter_suite_by_condition(
1925
2383
            self.suite, tests.condition_id_in_list(id_list))
1926
2384
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1927
 
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
 
2385
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
1928
2386
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1929
2387
 
1930
2388
    def test_condition_id_startswith(self):
1934
2392
        test_names = [ klass + 'test_condition_id_in_list',
1935
2393
                      klass + 'test_condition_id_startswith',
1936
2394
                     ]
1937
 
        filtered_suite = filter_suite_by_condition(
 
2395
        filtered_suite = tests.filter_suite_by_condition(
1938
2396
            self.suite, tests.condition_id_startswith([start1, start2]))
1939
2397
        self.assertEqual(test_names, _test_ids(filtered_suite))
1940
2398
 
1941
2399
    def test_condition_isinstance(self):
1942
 
        filtered_suite = filter_suite_by_condition(self.suite,
1943
 
            condition_isinstance(self.__class__))
 
2400
        filtered_suite = tests.filter_suite_by_condition(
 
2401
            self.suite, tests.condition_isinstance(self.__class__))
1944
2402
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1945
 
        re_filtered = filter_suite_by_re(self.suite, class_pattern)
 
2403
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
1946
2404
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1947
2405
 
1948
2406
    def test_exclude_tests_by_condition(self):
1949
2407
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1950
2408
            'test_exclude_tests_by_condition')
1951
 
        filtered_suite = exclude_tests_by_condition(self.suite,
 
2409
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
1952
2410
            lambda x:x.id() == excluded_name)
1953
2411
        self.assertEqual(len(self.all_names) - 1,
1954
2412
            filtered_suite.countTestCases())
1959
2417
 
1960
2418
    def test_exclude_tests_by_re(self):
1961
2419
        self.all_names = _test_ids(self.suite)
1962
 
        filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
 
2420
        filtered_suite = tests.exclude_tests_by_re(self.suite,
 
2421
                                                   'exclude_tests_by_re')
1963
2422
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1964
2423
            'test_exclude_tests_by_re')
1965
2424
        self.assertEqual(len(self.all_names) - 1,
1972
2431
    def test_filter_suite_by_condition(self):
1973
2432
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1974
2433
            'test_filter_suite_by_condition')
1975
 
        filtered_suite = filter_suite_by_condition(self.suite,
 
2434
        filtered_suite = tests.filter_suite_by_condition(self.suite,
1976
2435
            lambda x:x.id() == test_name)
1977
2436
        self.assertEqual([test_name], _test_ids(filtered_suite))
1978
2437
 
1979
2438
    def test_filter_suite_by_re(self):
1980
 
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
 
2439
        filtered_suite = tests.filter_suite_by_re(self.suite,
 
2440
                                                  'test_filter_suite_by_r')
1981
2441
        filtered_names = _test_ids(filtered_suite)
1982
2442
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1983
2443
            'TestSelftestFiltering.test_filter_suite_by_re'])
2011
2471
 
2012
2472
    def test_preserve_input(self):
2013
2473
        # NB: Surely this is something in the stdlib to do this?
2014
 
        self.assertTrue(self.suite is preserve_input(self.suite))
2015
 
        self.assertTrue("@#$" is preserve_input("@#$"))
 
2474
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
 
2475
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
2016
2476
 
2017
2477
    def test_randomize_suite(self):
2018
 
        randomized_suite = randomize_suite(self.suite)
 
2478
        randomized_suite = tests.randomize_suite(self.suite)
2019
2479
        # randomizing should not add or remove test names.
2020
2480
        self.assertEqual(set(_test_ids(self.suite)),
2021
2481
                         set(_test_ids(randomized_suite)))
2031
2491
 
2032
2492
    def test_split_suit_by_condition(self):
2033
2493
        self.all_names = _test_ids(self.suite)
2034
 
        condition = condition_id_re('test_filter_suite_by_r')
2035
 
        split_suite = split_suite_by_condition(self.suite, condition)
 
2494
        condition = tests.condition_id_re('test_filter_suite_by_r')
 
2495
        split_suite = tests.split_suite_by_condition(self.suite, condition)
2036
2496
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2037
2497
            'test_filter_suite_by_re')
2038
2498
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2043
2503
 
2044
2504
    def test_split_suit_by_re(self):
2045
2505
        self.all_names = _test_ids(self.suite)
2046
 
        split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
 
2506
        split_suite = tests.split_suite_by_re(self.suite,
 
2507
                                              'test_filter_suite_by_r')
2047
2508
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2048
2509
            'test_filter_suite_by_re')
2049
2510
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2053
2514
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2054
2515
 
2055
2516
 
2056
 
class TestCheckInventoryShape(TestCaseWithTransport):
 
2517
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2057
2518
 
2058
2519
    def test_check_inventory_shape(self):
2059
2520
        files = ['a', 'b/', 'b/c']
2067
2528
            tree.unlock()
2068
2529
 
2069
2530
 
2070
 
class TestBlackboxSupport(TestCase):
 
2531
class TestBlackboxSupport(tests.TestCase):
2071
2532
    """Tests for testsuite blackbox features."""
2072
2533
 
2073
2534
    def test_run_bzr_failure_not_caught(self):
2094
2555
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2095
2556
 
2096
2557
 
2097
 
class TestTestLoader(TestCase):
 
2558
class TestTestLoader(tests.TestCase):
2098
2559
    """Tests for the test loader."""
2099
2560
 
2100
2561
    def _get_loader_and_module(self):
2101
2562
        """Gets a TestLoader and a module with one test in it."""
2102
2563
        loader = TestUtil.TestLoader()
2103
2564
        module = {}
2104
 
        class Stub(TestCase):
 
2565
        class Stub(tests.TestCase):
2105
2566
            def test_foo(self):
2106
2567
                pass
2107
2568
        class MyModule(object):
2120
2581
        # load_tests do not need that :)
2121
2582
        def load_tests(self, standard_tests, module, loader):
2122
2583
            result = loader.suiteClass()
2123
 
            for test in iter_suite_tests(standard_tests):
 
2584
            for test in tests.iter_suite_tests(standard_tests):
2124
2585
                result.addTests([test, test])
2125
2586
            return result
2126
2587
        # add a load_tests() method which multiplies the tests from the module.
2145
2606
 
2146
2607
    def _create_suite(self, test_id_list):
2147
2608
 
2148
 
        class Stub(TestCase):
 
2609
        class Stub(tests.TestCase):
2149
2610
            def test_foo(self):
2150
2611
                pass
2151
2612
 
2161
2622
 
2162
2623
    def _test_ids(self, test_suite):
2163
2624
        """Get the ids for the tests in a test suite."""
2164
 
        return [t.id() for t in iter_suite_tests(test_suite)]
 
2625
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
2165
2626
 
2166
2627
    def test_empty_list(self):
2167
2628
        id_list = self._create_id_list([])
2193
2654
        self.assertTrue(id_list.refers_to('mod.class'))
2194
2655
        self.assertTrue(id_list.refers_to('mod.class.meth'))
2195
2656
 
2196
 
    def test_test_suite(self):
2197
 
        # This test is slow, so we do a single test with one test in each
2198
 
        # category
2199
 
        test_list = [
2200
 
            # testmod_names
2201
 
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2202
 
            'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
2203
 
            # transport implementations
2204
 
            'bzrlib.tests.test_transport_implementations.TransportTests'
2205
 
            '.test_abspath(LocalURLServer)',
2206
 
            # modules_to_doctest
2207
 
            'bzrlib.timestamp.format_highres_date',
2208
 
            # plugins can't be tested that way since selftest may be run with
2209
 
            # --no-plugins
2210
 
            ]
2211
 
        suite = tests.test_suite(test_list)
2212
 
        self.assertEquals(test_list, _test_ids(suite))
2213
 
 
2214
2657
    def test_test_suite_matches_id_list_with_unknown(self):
2215
2658
        loader = TestUtil.TestLoader()
2216
2659
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2224
2667
        loader = TestUtil.TestLoader()
2225
2668
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2226
2669
        dupes = loader.suiteClass()
2227
 
        for test in iter_suite_tests(suite):
 
2670
        for test in tests.iter_suite_tests(suite):
2228
2671
            dupes.addTest(test)
2229
2672
            dupes.addTest(test) # Add it again
2230
2673
 
2236
2679
                          duplicates)
2237
2680
 
2238
2681
 
 
2682
class TestTestSuite(tests.TestCase):
 
2683
 
 
2684
    def test_test_suite(self):
 
2685
        # This test is slow - it loads the entire test suite to operate, so we
 
2686
        # do a single test with one test in each category
 
2687
        test_list = [
 
2688
            # testmod_names
 
2689
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
 
2690
            ('bzrlib.tests.per_transport.TransportTests'
 
2691
             '.test_abspath(LocalURLServer)'),
 
2692
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
 
2693
            # modules_to_doctest
 
2694
            'bzrlib.timestamp.format_highres_date',
 
2695
            # plugins can't be tested that way since selftest may be run with
 
2696
            # --no-plugins
 
2697
            ]
 
2698
        suite = tests.test_suite(test_list)
 
2699
        self.assertEquals(test_list, _test_ids(suite))
 
2700
 
 
2701
    def test_test_suite_list_and_start(self):
 
2702
        # We cannot test this at the same time as the main load, because we want
 
2703
        # to know that starting_with == None works. So a second full load is
 
2704
        # incurred.
 
2705
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
 
2706
        suite = tests.test_suite(test_list,
 
2707
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
 
2708
        # test_test_suite_list_and_start is not included 
 
2709
        self.assertEquals(test_list, _test_ids(suite))
 
2710
 
 
2711
 
2239
2712
class TestLoadTestIdList(tests.TestCaseInTempDir):
2240
2713
 
2241
2714
    def _create_test_list_file(self, file_name, content):
2364
2837
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2365
2838
 
2366
2839
 
2367
 
class TestRunSuite(TestCase):
 
2840
class TestRunSuite(tests.TestCase):
2368
2841
 
2369
2842
    def test_runner_class(self):
2370
2843
        """run_suite accepts and uses a runner_class keyword argument."""
2371
 
        class Stub(TestCase):
 
2844
        class Stub(tests.TestCase):
2372
2845
            def test_foo(self):
2373
2846
                pass
2374
2847
        suite = Stub("test_foo")
2375
2848
        calls = []
2376
 
        class MyRunner(TextTestRunner):
 
2849
        class MyRunner(tests.TextTestRunner):
2377
2850
            def run(self, test):
2378
2851
                calls.append(test)
2379
 
                return ExtendedTestResult(self.stream, self.descriptions,
2380
 
                    self.verbosity)
2381
 
        run_suite(suite, runner_class=MyRunner, stream=StringIO())
2382
 
        self.assertEqual(calls, [suite])
 
2852
                return tests.ExtendedTestResult(self.stream, self.descriptions,
 
2853
                                                self.verbosity)
 
2854
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
 
2855
        self.assertLength(1, calls)
2383
2856
 
2384
2857
    def test_done(self):
2385
2858
        """run_suite should call result.done()"""
2388
2861
        def test_function():
2389
2862
            pass
2390
2863
        test = unittest.FunctionTestCase(test_function)
2391
 
        class InstrumentedTestResult(ExtendedTestResult):
 
2864
        class InstrumentedTestResult(tests.ExtendedTestResult):
2392
2865
            def done(self): one_more_call()
2393
 
        class MyRunner(TextTestRunner):
 
2866
        class MyRunner(tests.TextTestRunner):
2394
2867
            def run(self, test):
2395
2868
                return InstrumentedTestResult(self.stream, self.descriptions,
2396
2869
                                              self.verbosity)
2397
 
        run_suite(test, runner_class=MyRunner, stream=StringIO())
 
2870
        tests.run_suite(test, runner_class=MyRunner, stream=StringIO())
2398
2871
        self.assertEquals(1, self.calls)