~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Martin Pool
  • Date: 2010-02-17 05:12:01 UTC
  • mfrom: (4797.2.16 2.1)
  • mto: This revision was merged to the branch mainline in revision 5037.
  • Revision ID: mbp@sourcefrog.net-20100217051201-1sd9dssoujfdc6c4
merge 2.1 back to trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
"""Tests for the test framework."""
18
18
 
19
19
from cStringIO import StringIO
20
 
import doctest
 
20
from doctest import ELLIPSIS
21
21
import os
22
22
import signal
23
23
import sys
24
 
import threading
25
24
import time
26
25
import unittest
27
26
import warnings
28
27
 
29
 
from testtools import (
30
 
    ExtendedToOriginalDecorator,
31
 
    MultiTestResult,
32
 
    __version__ as testtools_version,
33
 
    )
34
 
from testtools.content import Content
 
28
from testtools import MultiTestResult
35
29
from testtools.content_type import ContentType
36
30
from testtools.matchers import (
37
31
    DocTestMatches,
38
32
    Equals,
39
33
    )
40
 
import testtools.testresult.doubles
 
34
import testtools.tests.helpers
41
35
 
42
36
import bzrlib
43
37
from bzrlib import (
44
38
    branchbuilder,
45
39
    bzrdir,
 
40
    debug,
46
41
    errors,
47
 
    hooks,
48
42
    lockdir,
49
43
    memorytree,
50
44
    osutils,
 
45
    progress,
51
46
    remote,
52
47
    repository,
53
48
    symbol_versioning,
54
49
    tests,
55
50
    transport,
56
51
    workingtree,
57
 
    workingtree_3,
58
 
    workingtree_4,
59
52
    )
60
53
from bzrlib.repofmt import (
61
54
    groupcompress_repo,
 
55
    pack_repo,
 
56
    weaverepo,
62
57
    )
63
58
from bzrlib.symbol_versioning import (
64
59
    deprecated_function,
67
62
    )
68
63
from bzrlib.tests import (
69
64
    features,
 
65
    stub_sftp,
70
66
    test_lsprof,
71
67
    test_server,
 
68
    test_sftp_transport,
72
69
    TestUtil,
73
70
    )
74
 
from bzrlib.trace import note, mutter
 
71
from bzrlib.trace import note
75
72
from bzrlib.transport import memory
 
73
from bzrlib.version import _get_bzr_source_tree
76
74
 
77
75
 
78
76
def _test_ids(test_suite):
80
78
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
81
79
 
82
80
 
 
81
class SelftestTests(tests.TestCase):
 
82
 
 
83
    def test_import_tests(self):
 
84
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
 
85
        self.assertEqual(mod.SelftestTests, SelftestTests)
 
86
 
 
87
    def test_import_test_failure(self):
 
88
        self.assertRaises(ImportError,
 
89
                          TestUtil._load_module_by_name,
 
90
                          'bzrlib.no-name-yet')
 
91
 
 
92
 
83
93
class MetaTestLog(tests.TestCase):
84
94
 
85
95
    def test_logging(self):
91
101
            "text", "plain", {"charset": "utf8"})))
92
102
        self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
93
103
        self.assertThat(self.get_log(),
94
 
            DocTestMatches(u"...a test message\n", doctest.ELLIPSIS))
 
104
            DocTestMatches(u"...a test message\n", ELLIPSIS))
 
105
 
 
106
 
 
107
class TestUnicodeFilename(tests.TestCase):
 
108
 
 
109
    def test_probe_passes(self):
 
110
        """UnicodeFilename._probe passes."""
 
111
        # We can't test much more than that because the behaviour depends
 
112
        # on the platform.
 
113
        tests.UnicodeFilename._probe()
95
114
 
96
115
 
97
116
class TestTreeShape(tests.TestCaseInTempDir):
98
117
 
99
118
    def test_unicode_paths(self):
100
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
119
        self.requireFeature(tests.UnicodeFilename)
101
120
 
102
121
        filename = u'hell\u00d8'
103
122
        self.build_tree_contents([(filename, 'contents of hello')])
104
 
        self.assertPathExists(filename)
105
 
 
106
 
 
107
 
class TestClassesAvailable(tests.TestCase):
108
 
    """As a convenience we expose Test* classes from bzrlib.tests"""
109
 
 
110
 
    def test_test_case(self):
111
 
        from bzrlib.tests import TestCase
112
 
 
113
 
    def test_test_loader(self):
114
 
        from bzrlib.tests import TestLoader
115
 
 
116
 
    def test_test_suite(self):
117
 
        from bzrlib.tests import TestSuite
 
123
        self.failUnlessExists(filename)
118
124
 
119
125
 
120
126
class TestTransportScenarios(tests.TestCase):
203
209
    def test_scenarios(self):
204
210
        # check that constructor parameters are passed through to the adapted
205
211
        # test.
206
 
        from bzrlib.tests.per_controldir import make_scenarios
 
212
        from bzrlib.tests.per_bzrdir import make_scenarios
207
213
        vfs_factory = "v"
208
214
        server1 = "a"
209
215
        server2 = "b"
307
313
        from bzrlib.tests.per_interrepository import make_scenarios
308
314
        server1 = "a"
309
315
        server2 = "b"
310
 
        formats = [("C0", "C1", "C2", "C3"), ("D0", "D1", "D2", "D3")]
 
316
        formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
311
317
        scenarios = make_scenarios(server1, server2, formats)
312
318
        self.assertEqual([
313
319
            ('C0,str,str',
314
320
             {'repository_format': 'C1',
315
321
              'repository_format_to': 'C2',
316
322
              'transport_readonly_server': 'b',
317
 
              'transport_server': 'a',
318
 
              'extra_setup': 'C3'}),
 
323
              'transport_server': 'a'}),
319
324
            ('D0,str,str',
320
325
             {'repository_format': 'D1',
321
326
              'repository_format_to': 'D2',
322
327
              'transport_readonly_server': 'b',
323
 
              'transport_server': 'a',
324
 
              'extra_setup': 'D3'})],
 
328
              'transport_server': 'a'})],
325
329
            scenarios)
326
330
 
327
331
 
333
337
        from bzrlib.tests.per_workingtree import make_scenarios
334
338
        server1 = "a"
335
339
        server2 = "b"
336
 
        formats = [workingtree_4.WorkingTreeFormat4(),
337
 
                   workingtree_3.WorkingTreeFormat3(),]
 
340
        formats = [workingtree.WorkingTreeFormat2(),
 
341
                   workingtree.WorkingTreeFormat3(),]
338
342
        scenarios = make_scenarios(server1, server2, formats)
339
343
        self.assertEqual([
340
 
            ('WorkingTreeFormat4',
 
344
            ('WorkingTreeFormat2',
341
345
             {'bzrdir_format': formats[0]._matchingbzrdir,
342
346
              'transport_readonly_server': 'b',
343
347
              'transport_server': 'a',
370
374
            )
371
375
        server1 = "a"
372
376
        server2 = "b"
373
 
        formats = [workingtree_4.WorkingTreeFormat4(),
374
 
                   workingtree_3.WorkingTreeFormat3(),]
 
377
        formats = [workingtree.WorkingTreeFormat2(),
 
378
                   workingtree.WorkingTreeFormat3(),]
375
379
        scenarios = make_scenarios(server1, server2, formats)
376
380
        self.assertEqual(7, len(scenarios))
377
 
        default_wt_format = workingtree.format_registry.get_default()
378
 
        wt4_format = workingtree_4.WorkingTreeFormat4()
379
 
        wt5_format = workingtree_4.WorkingTreeFormat5()
 
381
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
 
382
        wt4_format = workingtree.WorkingTreeFormat4()
 
383
        wt5_format = workingtree.WorkingTreeFormat5()
380
384
        expected_scenarios = [
381
 
            ('WorkingTreeFormat4',
 
385
            ('WorkingTreeFormat2',
382
386
             {'bzrdir_format': formats[0]._matchingbzrdir,
383
387
              'transport_readonly_server': 'b',
384
388
              'transport_server': 'a',
444
448
        # ones to add.
445
449
        from bzrlib.tests.per_tree import (
446
450
            return_parameter,
 
451
            revision_tree_from_workingtree
447
452
            )
448
453
        from bzrlib.tests.per_intertree import (
449
454
            make_scenarios,
450
455
            )
451
 
        from bzrlib.workingtree_3 import WorkingTreeFormat3
452
 
        from bzrlib.workingtree_4 import WorkingTreeFormat4
 
456
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
453
457
        input_test = TestInterTreeScenarios(
454
458
            "test_scenarios")
455
459
        server1 = "a"
456
460
        server2 = "b"
457
 
        format1 = WorkingTreeFormat4()
 
461
        format1 = WorkingTreeFormat2()
458
462
        format2 = WorkingTreeFormat3()
459
463
        formats = [("1", str, format1, format2, "converter1"),
460
464
            ("2", int, format2, format1, "converter2")]
506
510
        self.assertRaises(AssertionError, self.assertEqualStat,
507
511
            os.lstat("foo"), os.lstat("longname"))
508
512
 
509
 
    def test_failUnlessExists(self):
510
 
        """Deprecated failUnlessExists and failIfExists"""
511
 
        self.applyDeprecated(
512
 
            deprecated_in((2, 4)),
513
 
            self.failUnlessExists, '.')
514
 
        self.build_tree(['foo/', 'foo/bar'])
515
 
        self.applyDeprecated(
516
 
            deprecated_in((2, 4)),
517
 
            self.failUnlessExists, 'foo/bar')
518
 
        self.applyDeprecated(
519
 
            deprecated_in((2, 4)),
520
 
            self.failIfExists, 'foo/foo')
521
 
 
522
 
    def test_assertPathExists(self):
523
 
        self.assertPathExists('.')
524
 
        self.build_tree(['foo/', 'foo/bar'])
525
 
        self.assertPathExists('foo/bar')
526
 
        self.assertPathDoesNotExist('foo/foo')
527
 
 
528
513
 
529
514
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
530
515
 
564
549
        tree = self.make_branch_and_memory_tree('dir')
565
550
        # Guard against regression into MemoryTransport leaking
566
551
        # files to disk instead of keeping them in memory.
567
 
        self.assertFalse(osutils.lexists('dir'))
 
552
        self.failIf(osutils.lexists('dir'))
568
553
        self.assertIsInstance(tree, memorytree.MemoryTree)
569
554
 
570
555
    def test_make_branch_and_memory_tree_with_format(self):
571
556
        """make_branch_and_memory_tree should accept a format option."""
572
557
        format = bzrdir.BzrDirMetaFormat1()
573
 
        format.repository_format = repository.format_registry.get_default()
 
558
        format.repository_format = weaverepo.RepositoryFormat7()
574
559
        tree = self.make_branch_and_memory_tree('dir', format=format)
575
560
        # Guard against regression into MemoryTransport leaking
576
561
        # files to disk instead of keeping them in memory.
577
 
        self.assertFalse(osutils.lexists('dir'))
 
562
        self.failIf(osutils.lexists('dir'))
578
563
        self.assertIsInstance(tree, memorytree.MemoryTree)
579
564
        self.assertEqual(format.repository_format.__class__,
580
565
            tree.branch.repository._format.__class__)
584
569
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
585
570
        # Guard against regression into MemoryTransport leaking
586
571
        # files to disk instead of keeping them in memory.
587
 
        self.assertFalse(osutils.lexists('dir'))
 
572
        self.failIf(osutils.lexists('dir'))
588
573
 
589
574
    def test_make_branch_builder_with_format(self):
590
575
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
591
576
        # that the format objects are used.
592
577
        format = bzrdir.BzrDirMetaFormat1()
593
 
        repo_format = repository.format_registry.get_default()
 
578
        repo_format = weaverepo.RepositoryFormat7()
594
579
        format.repository_format = repo_format
595
580
        builder = self.make_branch_builder('dir', format=format)
596
581
        the_branch = builder.get_branch()
597
582
        # Guard against regression into MemoryTransport leaking
598
583
        # files to disk instead of keeping them in memory.
599
 
        self.assertFalse(osutils.lexists('dir'))
 
584
        self.failIf(osutils.lexists('dir'))
600
585
        self.assertEqual(format.repository_format.__class__,
601
586
                         the_branch.repository._format.__class__)
602
587
        self.assertEqual(repo_format.get_format_string(),
608
593
        the_branch = builder.get_branch()
609
594
        # Guard against regression into MemoryTransport leaking
610
595
        # files to disk instead of keeping them in memory.
611
 
        self.assertFalse(osutils.lexists('dir'))
 
596
        self.failIf(osutils.lexists('dir'))
612
597
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
613
598
        self.assertEqual(dir_format.repository_format.__class__,
614
599
                         the_branch.repository._format.__class__)
625
610
                l.attempt_lock()
626
611
        test = TestDanglingLock('test_function')
627
612
        result = test.run()
628
 
        total_failures = result.errors + result.failures
629
613
        if self._lock_check_thorough:
630
 
            self.assertEqual(1, len(total_failures))
 
614
            self.assertEqual(1, len(result.errors))
631
615
        else:
632
616
            # When _lock_check_thorough is disabled, then we don't trigger a
633
617
            # failure
634
 
            self.assertEqual(0, len(total_failures))
 
618
            self.assertEqual(0, len(result.errors))
635
619
 
636
620
 
637
621
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
638
622
    """Tests for the convenience functions TestCaseWithTransport introduces."""
639
623
 
640
624
    def test_get_readonly_url_none(self):
 
625
        from bzrlib.transport import get_transport
641
626
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
642
627
        self.vfs_transport_factory = memory.MemoryServer
643
628
        self.transport_readonly_server = None
645
630
        # for the server
646
631
        url = self.get_readonly_url()
647
632
        url2 = self.get_readonly_url('foo/bar')
648
 
        t = transport.get_transport(url)
649
 
        t2 = transport.get_transport(url2)
650
 
        self.assertIsInstance(t, ReadonlyTransportDecorator)
651
 
        self.assertIsInstance(t2, ReadonlyTransportDecorator)
 
633
        t = get_transport(url)
 
634
        t2 = get_transport(url2)
 
635
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
 
636
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
652
637
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
653
638
 
654
639
    def test_get_readonly_url_http(self):
655
640
        from bzrlib.tests.http_server import HttpServer
 
641
        from bzrlib.transport import get_transport
656
642
        from bzrlib.transport.http import HttpTransportBase
657
643
        self.transport_server = test_server.LocalURLServer
658
644
        self.transport_readonly_server = HttpServer
660
646
        url = self.get_readonly_url()
661
647
        url2 = self.get_readonly_url('foo/bar')
662
648
        # the transport returned may be any HttpTransportBase subclass
663
 
        t = transport.get_transport(url)
664
 
        t2 = transport.get_transport(url2)
665
 
        self.assertIsInstance(t, HttpTransportBase)
666
 
        self.assertIsInstance(t2, HttpTransportBase)
 
649
        t = get_transport(url)
 
650
        t2 = get_transport(url2)
 
651
        self.failUnless(isinstance(t, HttpTransportBase))
 
652
        self.failUnless(isinstance(t2, HttpTransportBase))
667
653
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
668
654
 
669
655
    def test_is_directory(self):
677
663
    def test_make_branch_builder(self):
678
664
        builder = self.make_branch_builder('dir')
679
665
        rev_id = builder.build_commit()
680
 
        self.assertPathExists('dir')
 
666
        self.failUnlessExists('dir')
681
667
        a_dir = bzrdir.BzrDir.open('dir')
682
668
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
683
669
        a_branch = a_dir.open_branch()
699
685
        self.assertIsInstance(result_bzrdir.transport,
700
686
                              memory.MemoryTransport)
701
687
        # should not be on disk, should only be in memory
702
 
        self.assertPathDoesNotExist('subdir')
 
688
        self.failIfExists('subdir')
703
689
 
704
690
 
705
691
class TestChrootedTest(tests.ChrootedTestCase):
706
692
 
707
693
    def test_root_is_root(self):
708
 
        t = transport.get_transport(self.get_readonly_url())
 
694
        from bzrlib.transport import get_transport
 
695
        t = get_transport(self.get_readonly_url())
709
696
        url = t.base
710
697
        self.assertEqual(url, t.clone('..').base)
711
698
 
713
700
class TestProfileResult(tests.TestCase):
714
701
 
715
702
    def test_profiles_tests(self):
716
 
        self.requireFeature(features.lsprof_feature)
717
 
        terminal = testtools.testresult.doubles.ExtendedTestResult()
 
703
        self.requireFeature(test_lsprof.LSProfFeature)
 
704
        terminal = testtools.tests.helpers.ExtendedTestResult()
718
705
        result = tests.ProfileResult(terminal)
719
706
        class Sample(tests.TestCase):
720
707
            def a(self):
737
724
                descriptions=0,
738
725
                verbosity=1,
739
726
                )
740
 
        capture = testtools.testresult.doubles.ExtendedTestResult()
 
727
        capture = testtools.tests.helpers.ExtendedTestResult()
741
728
        test_case.run(MultiTestResult(result, capture))
742
729
        run_case = capture._events[0][1]
743
730
        timed_string = result._testTimeString(run_case)
764
751
        self.check_timing(ShortDelayTestCase('test_short_delay'),
765
752
                          r"^ +[0-9]+ms$")
766
753
 
 
754
    def _patch_get_bzr_source_tree(self):
 
755
        # Reading from the actual source tree breaks isolation, but we don't
 
756
        # want to assume that thats *all* that would happen.
 
757
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', lambda: None)
 
758
 
 
759
    def test_assigned_benchmark_file_stores_date(self):
 
760
        self._patch_get_bzr_source_tree()
 
761
        output = StringIO()
 
762
        result = bzrlib.tests.TextTestResult(self._log_file,
 
763
                                        descriptions=0,
 
764
                                        verbosity=1,
 
765
                                        bench_history=output
 
766
                                        )
 
767
        output_string = output.getvalue()
 
768
        # if you are wondering about the regexp please read the comment in
 
769
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
770
        # XXX: what comment?  -- Andrew Bennetts
 
771
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
772
 
 
773
    def test_benchhistory_records_test_times(self):
 
774
        self._patch_get_bzr_source_tree()
 
775
        result_stream = StringIO()
 
776
        result = bzrlib.tests.TextTestResult(
 
777
            self._log_file,
 
778
            descriptions=0,
 
779
            verbosity=1,
 
780
            bench_history=result_stream
 
781
            )
 
782
 
 
783
        # we want profile a call and check that its test duration is recorded
 
784
        # make a new test instance that when run will generate a benchmark
 
785
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
786
        # execute the test, which should succeed and record times
 
787
        example_test_case.run(result)
 
788
        lines = result_stream.getvalue().splitlines()
 
789
        self.assertEqual(2, len(lines))
 
790
        self.assertContainsRe(lines[1],
 
791
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
792
            "._time_hello_world_encoding")
 
793
 
767
794
    def _time_hello_world_encoding(self):
768
795
        """Profile two sleep calls
769
796
 
774
801
 
775
802
    def test_lsprofiling(self):
776
803
        """Verbose test result prints lsprof statistics from test cases."""
777
 
        self.requireFeature(features.lsprof_feature)
 
804
        self.requireFeature(test_lsprof.LSProfFeature)
778
805
        result_stream = StringIO()
779
806
        result = bzrlib.tests.VerboseTestResult(
780
 
            result_stream,
 
807
            unittest._WritelnDecorator(result_stream),
781
808
            descriptions=0,
782
809
            verbosity=2,
783
810
            )
809
836
        self.assertContainsRe(output,
810
837
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
811
838
 
812
 
    def test_uses_time_from_testtools(self):
813
 
        """Test case timings in verbose results should use testtools times"""
814
 
        import datetime
815
 
        class TimeAddedVerboseTestResult(tests.VerboseTestResult):
816
 
            def startTest(self, test):
817
 
                self.time(datetime.datetime.utcfromtimestamp(1.145))
818
 
                super(TimeAddedVerboseTestResult, self).startTest(test)
819
 
            def addSuccess(self, test):
820
 
                self.time(datetime.datetime.utcfromtimestamp(51.147))
821
 
                super(TimeAddedVerboseTestResult, self).addSuccess(test)
822
 
            def report_tests_starting(self): pass
823
 
        sio = StringIO()
824
 
        self.get_passing_test().run(TimeAddedVerboseTestResult(sio, 0, 2))
825
 
        self.assertEndsWith(sio.getvalue(), "OK    50002ms\n")
826
 
 
827
839
    def test_known_failure(self):
828
 
        """Using knownFailure should trigger several result actions."""
 
840
        """A KnownFailure being raised should trigger several result actions."""
829
841
        class InstrumentedTestResult(tests.ExtendedTestResult):
830
842
            def stopTestRun(self): pass
831
 
            def report_tests_starting(self): pass
 
843
            def startTests(self): pass
 
844
            def report_test_start(self, test): pass
832
845
            def report_known_failure(self, test, err=None, details=None):
833
846
                self._call = test, 'known failure'
834
847
        result = InstrumentedTestResult(None, None, None, None)
835
848
        class Test(tests.TestCase):
836
849
            def test_function(self):
837
 
                self.knownFailure('failed!')
 
850
                raise tests.KnownFailure('failed!')
838
851
        test = Test("test_function")
839
852
        test.run(result)
840
853
        # it should invoke 'report_known_failure'.
852
865
        # verbose test output formatting
853
866
        result_stream = StringIO()
854
867
        result = bzrlib.tests.VerboseTestResult(
855
 
            result_stream,
 
868
            unittest._WritelnDecorator(result_stream),
856
869
            descriptions=0,
857
870
            verbosity=2,
858
871
            )
859
 
        _get_test("test_xfail").run(result)
860
 
        self.assertContainsRe(result_stream.getvalue(),
861
 
            "\n\\S+\\.test_xfail\\s+XFAIL\\s+\\d+ms\n"
862
 
            "\\s*(?:Text attachment: )?reason"
863
 
            "(?:\n-+\n|: {{{)"
864
 
            "this_fails"
865
 
            "(?:\n-+\n|}}}\n)")
 
872
        test = self.get_passing_test()
 
873
        result.startTest(test)
 
874
        prefix = len(result_stream.getvalue())
 
875
        # the err parameter has the shape:
 
876
        # (class, exception object, traceback)
 
877
        # KnownFailures dont get their tracebacks shown though, so we
 
878
        # can skip that.
 
879
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
880
        result.report_known_failure(test, err)
 
881
        output = result_stream.getvalue()[prefix:]
 
882
        lines = output.splitlines()
 
883
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
 
884
        self.assertEqual(lines[1], '    foo')
 
885
        self.assertEqual(2, len(lines))
866
886
 
867
887
    def get_passing_test(self):
868
888
        """Return a test object that can't be run usefully."""
874
894
        """Test the behaviour of invoking addNotSupported."""
875
895
        class InstrumentedTestResult(tests.ExtendedTestResult):
876
896
            def stopTestRun(self): pass
877
 
            def report_tests_starting(self): pass
 
897
            def startTests(self): pass
 
898
            def report_test_start(self, test): pass
878
899
            def report_unsupported(self, test, feature):
879
900
                self._call = test, feature
880
901
        result = InstrumentedTestResult(None, None, None, None)
881
902
        test = SampleTestCase('_test_pass')
882
 
        feature = features.Feature()
 
903
        feature = tests.Feature()
883
904
        result.startTest(test)
884
905
        result.addNotSupported(test, feature)
885
906
        # it should invoke 'report_unsupported'.
899
920
        # verbose test output formatting
900
921
        result_stream = StringIO()
901
922
        result = bzrlib.tests.VerboseTestResult(
902
 
            result_stream,
 
923
            unittest._WritelnDecorator(result_stream),
903
924
            descriptions=0,
904
925
            verbosity=2,
905
926
            )
906
927
        test = self.get_passing_test()
907
 
        feature = features.Feature()
 
928
        feature = tests.Feature()
908
929
        result.startTest(test)
909
930
        prefix = len(result_stream.getvalue())
910
931
        result.report_unsupported(test, feature)
919
940
        """An UnavailableFeature being raised should invoke addNotSupported."""
920
941
        class InstrumentedTestResult(tests.ExtendedTestResult):
921
942
            def stopTestRun(self): pass
922
 
            def report_tests_starting(self): pass
 
943
            def startTests(self): pass
 
944
            def report_test_start(self, test): pass
923
945
            def addNotSupported(self, test, feature):
924
946
                self._call = test, feature
925
947
        result = InstrumentedTestResult(None, None, None, None)
926
 
        feature = features.Feature()
 
948
        feature = tests.Feature()
927
949
        class Test(tests.TestCase):
928
950
            def test_function(self):
929
951
                raise tests.UnavailableFeature(feature)
948
970
    def test_strict_with_known_failure(self):
949
971
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
950
972
                                             verbosity=1)
951
 
        test = _get_test("test_xfail")
952
 
        test.run(result)
 
973
        test = self.get_passing_test()
 
974
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
975
        result.addExpectedFailure(test, err)
953
976
        self.assertFalse(result.wasStrictlySuccessful())
954
977
        self.assertEqual(None, result._extractBenchmarkTime(test))
955
978
 
966
989
        class InstrumentedTestResult(tests.ExtendedTestResult):
967
990
            calls = 0
968
991
            def startTests(self): self.calls += 1
 
992
            def report_test_start(self, test): pass
969
993
        result = InstrumentedTestResult(None, None, None, None)
970
994
        def test_function():
971
995
            pass
973
997
        test.run(result)
974
998
        self.assertEquals(1, result.calls)
975
999
 
976
 
    def test_startTests_only_once(self):
977
 
        """With multiple tests startTests should still only be called once"""
978
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
979
 
            calls = 0
980
 
            def startTests(self): self.calls += 1
981
 
        result = InstrumentedTestResult(None, None, None, None)
982
 
        suite = unittest.TestSuite([
983
 
            unittest.FunctionTestCase(lambda: None),
984
 
            unittest.FunctionTestCase(lambda: None)])
985
 
        suite.run(result)
986
 
        self.assertEquals(1, result.calls)
987
 
        self.assertEquals(2, result.count)
 
1000
 
 
1001
class TestUnicodeFilenameFeature(tests.TestCase):
 
1002
 
 
1003
    def test_probe_passes(self):
 
1004
        """UnicodeFilenameFeature._probe passes."""
 
1005
        # We can't test much more than that because the behaviour depends
 
1006
        # on the platform.
 
1007
        tests.UnicodeFilenameFeature._probe()
988
1008
 
989
1009
 
990
1010
class TestRunner(tests.TestCase):
1003
1023
        because of our use of global state.
1004
1024
        """
1005
1025
        old_root = tests.TestCaseInTempDir.TEST_ROOT
 
1026
        old_leak = tests.TestCase._first_thread_leaker_id
1006
1027
        try:
1007
1028
            tests.TestCaseInTempDir.TEST_ROOT = None
 
1029
            tests.TestCase._first_thread_leaker_id = None
1008
1030
            return testrunner.run(test)
1009
1031
        finally:
1010
1032
            tests.TestCaseInTempDir.TEST_ROOT = old_root
 
1033
            tests.TestCase._first_thread_leaker_id = old_leak
1011
1034
 
1012
1035
    def test_known_failure_failed_run(self):
1013
1036
        # run a test that generates a known failure which should be printed in
1018
1041
        test = unittest.TestSuite()
1019
1042
        test.addTest(Test("known_failure_test"))
1020
1043
        def failing_test():
1021
 
            raise AssertionError('foo')
 
1044
            self.fail('foo')
1022
1045
        test.addTest(unittest.FunctionTestCase(failing_test))
1023
1046
        stream = StringIO()
1024
1047
        runner = tests.TextTestRunner(stream=stream)
1032
1055
            '^----------------------------------------------------------------------\n'
1033
1056
            'Traceback \\(most recent call last\\):\n'
1034
1057
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1035
 
            '    raise AssertionError\\(\'foo\'\\)\n'
 
1058
            '    self.fail\\(\'foo\'\\)\n'
1036
1059
            '.*'
1037
1060
            '^----------------------------------------------------------------------\n'
1038
1061
            '.*'
1044
1067
        # the final output.
1045
1068
        class Test(tests.TestCase):
1046
1069
            def known_failure_test(self):
1047
 
                self.knownFailure("Never works...")
 
1070
                self.expectFailure('failed', self.assertTrue, False)
1048
1071
        test = Test("known_failure_test")
1049
1072
        stream = StringIO()
1050
1073
        runner = tests.TextTestRunner(stream=stream)
1056
1079
            '\n'
1057
1080
            'OK \\(known_failures=1\\)\n')
1058
1081
 
1059
 
    def test_unexpected_success_bad(self):
1060
 
        class Test(tests.TestCase):
1061
 
            def test_truth(self):
1062
 
                self.expectFailure("No absolute truth", self.assertTrue, True)
1063
 
        runner = tests.TextTestRunner(stream=StringIO())
1064
 
        result = self.run_test_runner(runner, Test("test_truth"))
1065
 
        if testtools_version[:3] <= (0, 9, 11):
1066
 
            self.assertContainsRe(runner.stream.getvalue(),
1067
 
                "=+\n"
1068
 
                "FAIL: \\S+\.test_truth\n"
1069
 
                "-+\n"
1070
 
                "(?:.*\n)*"
1071
 
                "No absolute truth\n"
1072
 
                "(?:.*\n)*"
1073
 
                "-+\n"
1074
 
                "Ran 1 test in .*\n"
1075
 
                "\n"
1076
 
                "FAILED \\(failures=1\\)\n\\Z")
1077
 
        else:
1078
 
            self.assertContainsRe(runner.stream.getvalue(),
1079
 
                "=+\n"
1080
 
                "FAIL: \\S+\.test_truth\n"
1081
 
                "-+\n"
1082
 
                "Empty attachments:\n"
1083
 
                "  log\n"
1084
 
                "\n"
1085
 
                "reason: {{{No absolute truth}}}\n"
1086
 
                "-+\n"
1087
 
                "Ran 1 test in .*\n"
1088
 
                "\n"
1089
 
                "FAILED \\(failures=1\\)\n\\Z")
1090
 
 
1091
1082
    def test_result_decorator(self):
1092
1083
        # decorate results
1093
1084
        calls = []
1094
 
        class LoggingDecorator(ExtendedToOriginalDecorator):
 
1085
        class LoggingDecorator(tests.ForwardingResult):
1095
1086
            def startTest(self, test):
1096
 
                ExtendedToOriginalDecorator.startTest(self, test)
 
1087
                tests.ForwardingResult.startTest(self, test)
1097
1088
                calls.append('start')
1098
1089
        test = unittest.FunctionTestCase(lambda:None)
1099
1090
        stream = StringIO()
1177
1168
 
1178
1169
    def test_unsupported_features_listed(self):
1179
1170
        """When unsupported features are encountered they are detailed."""
1180
 
        class Feature1(features.Feature):
 
1171
        class Feature1(tests.Feature):
1181
1172
            def _probe(self): return False
1182
 
        class Feature2(features.Feature):
 
1173
        class Feature2(tests.Feature):
1183
1174
            def _probe(self): return False
1184
1175
        # create sample tests
1185
1176
        test1 = SampleTestCase('_test_pass')
1200
1191
            ],
1201
1192
            lines[-3:])
1202
1193
 
1203
 
    def test_verbose_test_count(self):
1204
 
        """A verbose test run reports the right test count at the start"""
1205
 
        suite = TestUtil.TestSuite([
1206
 
            unittest.FunctionTestCase(lambda:None),
1207
 
            unittest.FunctionTestCase(lambda:None)])
1208
 
        self.assertEqual(suite.countTestCases(), 2)
1209
 
        stream = StringIO()
1210
 
        runner = tests.TextTestRunner(stream=stream, verbosity=2)
1211
 
        # Need to use the CountingDecorator as that's what sets num_tests
1212
 
        result = self.run_test_runner(runner, tests.CountingDecorator(suite))
1213
 
        self.assertStartsWith(stream.getvalue(), "running 2 tests")
 
1194
    def _patch_get_bzr_source_tree(self):
 
1195
        # Reading from the actual source tree breaks isolation, but we don't
 
1196
        # want to assume that thats *all* that would happen.
 
1197
        self._get_source_tree_calls = []
 
1198
        def new_get():
 
1199
            self._get_source_tree_calls.append("called")
 
1200
            return None
 
1201
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree',  new_get)
 
1202
 
 
1203
    def test_bench_history(self):
 
1204
        # tests that the running the benchmark passes bench_history into
 
1205
        # the test result object. We can tell that happens if
 
1206
        # _get_bzr_source_tree is called.
 
1207
        self._patch_get_bzr_source_tree()
 
1208
        test = TestRunner('dummy_test')
 
1209
        output = StringIO()
 
1210
        runner = tests.TextTestRunner(stream=self._log_file,
 
1211
                                      bench_history=output)
 
1212
        result = self.run_test_runner(runner, test)
 
1213
        output_string = output.getvalue()
 
1214
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
1215
        self.assertLength(1, self._get_source_tree_calls)
1214
1216
 
1215
1217
    def test_startTestRun(self):
1216
1218
        """run should call result.startTestRun()"""
1217
1219
        calls = []
1218
 
        class LoggingDecorator(ExtendedToOriginalDecorator):
 
1220
        class LoggingDecorator(tests.ForwardingResult):
1219
1221
            def startTestRun(self):
1220
 
                ExtendedToOriginalDecorator.startTestRun(self)
 
1222
                tests.ForwardingResult.startTestRun(self)
1221
1223
                calls.append('startTestRun')
1222
1224
        test = unittest.FunctionTestCase(lambda:None)
1223
1225
        stream = StringIO()
1229
1231
    def test_stopTestRun(self):
1230
1232
        """run should call result.stopTestRun()"""
1231
1233
        calls = []
1232
 
        class LoggingDecorator(ExtendedToOriginalDecorator):
 
1234
        class LoggingDecorator(tests.ForwardingResult):
1233
1235
            def stopTestRun(self):
1234
 
                ExtendedToOriginalDecorator.stopTestRun(self)
 
1236
                tests.ForwardingResult.stopTestRun(self)
1235
1237
                calls.append('stopTestRun')
1236
1238
        test = unittest.FunctionTestCase(lambda:None)
1237
1239
        stream = StringIO()
1240
1242
        result = self.run_test_runner(runner, test)
1241
1243
        self.assertLength(1, calls)
1242
1244
 
1243
 
    def test_unicode_test_output_on_ascii_stream(self):
1244
 
        """Showing results should always succeed even on an ascii console"""
1245
 
        class FailureWithUnicode(tests.TestCase):
1246
 
            def test_log_unicode(self):
1247
 
                self.log(u"\u2606")
1248
 
                self.fail("Now print that log!")
1249
 
        out = StringIO()
1250
 
        self.overrideAttr(osutils, "get_terminal_encoding",
1251
 
            lambda trace=False: "ascii")
1252
 
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
1253
 
            FailureWithUnicode("test_log_unicode"))
1254
 
        if testtools_version[:3] > (0, 9, 11):
1255
 
            self.assertContainsRe(out.getvalue(), "log: {{{\d+\.\d+  \\\\u2606}}}")
1256
 
        else:
1257
 
            self.assertContainsRe(out.getvalue(),
1258
 
                "Text attachment: log\n"
1259
 
                "-+\n"
1260
 
                "\d+\.\d+  \\\\u2606\n"
1261
 
                "-+\n")
1262
 
 
1263
1245
 
1264
1246
class SampleTestCase(tests.TestCase):
1265
1247
 
1440
1422
        sample_test = TestTestCase("method_that_times_a_bit_twice")
1441
1423
        output_stream = StringIO()
1442
1424
        result = bzrlib.tests.VerboseTestResult(
1443
 
            output_stream,
 
1425
            unittest._WritelnDecorator(output_stream),
1444
1426
            descriptions=0,
1445
1427
            verbosity=2)
1446
1428
        sample_test.run(result)
1453
1435
        # Note this test won't fail with hooks that the core library doesn't
1454
1436
        # use - but it trigger with a plugin that adds hooks, so its still a
1455
1437
        # useful warning in that case.
1456
 
        self.assertEqual(bzrlib.branch.BranchHooks(), bzrlib.branch.Branch.hooks)
1457
 
        self.assertEqual(
1458
 
            bzrlib.smart.server.SmartServerHooks(),
 
1438
        self.assertEqual(bzrlib.branch.BranchHooks(),
 
1439
            bzrlib.branch.Branch.hooks)
 
1440
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1459
1441
            bzrlib.smart.server.SmartTCPServer.hooks)
1460
 
        self.assertEqual(
1461
 
            bzrlib.commands.CommandHooks(), bzrlib.commands.Command.hooks)
 
1442
        self.assertEqual(bzrlib.commands.CommandHooks(),
 
1443
            bzrlib.commands.Command.hooks)
1462
1444
 
1463
1445
    def test__gather_lsprof_in_benchmarks(self):
1464
1446
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1465
1447
 
1466
1448
        Each self.time() call is individually and separately profiled.
1467
1449
        """
1468
 
        self.requireFeature(features.lsprof_feature)
 
1450
        self.requireFeature(test_lsprof.LSProfFeature)
1469
1451
        # overrides the class member with an instance member so no cleanup
1470
1452
        # needed.
1471
1453
        self._gather_lsprof_in_benchmarks = True
1501
1483
 
1502
1484
    def test_requireFeature_available(self):
1503
1485
        """self.requireFeature(available) is a no-op."""
1504
 
        class Available(features.Feature):
 
1486
        class Available(tests.Feature):
1505
1487
            def _probe(self):return True
1506
1488
        feature = Available()
1507
1489
        self.requireFeature(feature)
1508
1490
 
1509
1491
    def test_requireFeature_unavailable(self):
1510
1492
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1511
 
        class Unavailable(features.Feature):
 
1493
        class Unavailable(tests.Feature):
1512
1494
            def _probe(self):return False
1513
1495
        feature = Unavailable()
1514
1496
        self.assertRaises(tests.UnavailableFeature,
1673
1655
        test.run(unittest.TestResult())
1674
1656
        self.assertEqual('original', obj.test_attr)
1675
1657
 
1676
 
    def test_recordCalls(self):
1677
 
        from bzrlib.tests import test_selftest
1678
 
        calls = self.recordCalls(
1679
 
            test_selftest, '_add_numbers')
1680
 
        self.assertEqual(test_selftest._add_numbers(2, 10),
1681
 
            12)
1682
 
        self.assertEquals(calls, [((2, 10), {})])
1683
 
 
1684
 
 
1685
 
def _add_numbers(a, b):
1686
 
    return a + b
1687
 
 
1688
 
 
1689
 
class _MissingFeature(features.Feature):
1690
 
    def _probe(self):
1691
 
        return False
1692
 
missing_feature = _MissingFeature()
1693
 
 
1694
 
 
1695
 
def _get_test(name):
1696
 
    """Get an instance of a specific example test.
1697
 
 
1698
 
    We protect this in a function so that they don't auto-run in the test
1699
 
    suite.
1700
 
    """
1701
 
 
1702
 
    class ExampleTests(tests.TestCase):
1703
 
 
1704
 
        def test_fail(self):
1705
 
            mutter('this was a failing test')
1706
 
            self.fail('this test will fail')
1707
 
 
1708
 
        def test_error(self):
1709
 
            mutter('this test errored')
1710
 
            raise RuntimeError('gotcha')
1711
 
 
1712
 
        def test_missing_feature(self):
1713
 
            mutter('missing the feature')
1714
 
            self.requireFeature(missing_feature)
1715
 
 
1716
 
        def test_skip(self):
1717
 
            mutter('this test will be skipped')
1718
 
            raise tests.TestSkipped('reason')
1719
 
 
1720
 
        def test_success(self):
1721
 
            mutter('this test succeeds')
1722
 
 
1723
 
        def test_xfail(self):
1724
 
            mutter('test with expected failure')
1725
 
            self.knownFailure('this_fails')
1726
 
 
1727
 
        def test_unexpected_success(self):
1728
 
            mutter('test with unexpected success')
1729
 
            self.expectFailure('should_fail', lambda: None)
1730
 
 
1731
 
    return ExampleTests(name)
1732
 
 
1733
 
 
1734
 
class TestTestCaseLogDetails(tests.TestCase):
1735
 
 
1736
 
    def _run_test(self, test_name):
1737
 
        test = _get_test(test_name)
1738
 
        result = testtools.TestResult()
1739
 
        test.run(result)
1740
 
        return result
1741
 
 
1742
 
    def test_fail_has_log(self):
1743
 
        result = self._run_test('test_fail')
1744
 
        self.assertEqual(1, len(result.failures))
1745
 
        result_content = result.failures[0][1]
1746
 
        if testtools_version < (0, 9, 12):
1747
 
            self.assertContainsRe(result_content, 'Text attachment: log')
1748
 
        self.assertContainsRe(result_content, 'this was a failing test')
1749
 
 
1750
 
    def test_error_has_log(self):
1751
 
        result = self._run_test('test_error')
1752
 
        self.assertEqual(1, len(result.errors))
1753
 
        result_content = result.errors[0][1]
1754
 
        if testtools_version < (0, 9, 12):
1755
 
            self.assertContainsRe(result_content, 'Text attachment: log')
1756
 
        self.assertContainsRe(result_content, 'this test errored')
1757
 
 
1758
 
    def test_skip_has_no_log(self):
1759
 
        result = self._run_test('test_skip')
1760
 
        self.assertEqual(['reason'], result.skip_reasons.keys())
1761
 
        skips = result.skip_reasons['reason']
1762
 
        self.assertEqual(1, len(skips))
1763
 
        test = skips[0]
1764
 
        self.assertFalse('log' in test.getDetails())
1765
 
 
1766
 
    def test_missing_feature_has_no_log(self):
1767
 
        # testtools doesn't know about addNotSupported, so it just gets
1768
 
        # considered as a skip
1769
 
        result = self._run_test('test_missing_feature')
1770
 
        self.assertEqual([missing_feature], result.skip_reasons.keys())
1771
 
        skips = result.skip_reasons[missing_feature]
1772
 
        self.assertEqual(1, len(skips))
1773
 
        test = skips[0]
1774
 
        self.assertFalse('log' in test.getDetails())
1775
 
 
1776
 
    def test_xfail_has_no_log(self):
1777
 
        result = self._run_test('test_xfail')
1778
 
        self.assertEqual(1, len(result.expectedFailures))
1779
 
        result_content = result.expectedFailures[0][1]
1780
 
        self.assertNotContainsRe(result_content, 'Text attachment: log')
1781
 
        self.assertNotContainsRe(result_content, 'test with expected failure')
1782
 
 
1783
 
    def test_unexpected_success_has_log(self):
1784
 
        result = self._run_test('test_unexpected_success')
1785
 
        self.assertEqual(1, len(result.unexpectedSuccesses))
1786
 
        # Inconsistency, unexpectedSuccesses is a list of tests,
1787
 
        # expectedFailures is a list of reasons?
1788
 
        test = result.unexpectedSuccesses[0]
1789
 
        details = test.getDetails()
1790
 
        self.assertTrue('log' in details)
1791
 
 
1792
 
 
1793
 
class TestTestCloning(tests.TestCase):
1794
 
    """Tests that test cloning of TestCases (as used by multiply_tests)."""
1795
 
 
1796
 
    def test_cloned_testcase_does_not_share_details(self):
1797
 
        """A TestCase cloned with clone_test does not share mutable attributes
1798
 
        such as details or cleanups.
1799
 
        """
1800
 
        class Test(tests.TestCase):
1801
 
            def test_foo(self):
1802
 
                self.addDetail('foo', Content('text/plain', lambda: 'foo'))
1803
 
        orig_test = Test('test_foo')
1804
 
        cloned_test = tests.clone_test(orig_test, orig_test.id() + '(cloned)')
1805
 
        orig_test.run(unittest.TestResult())
1806
 
        self.assertEqual('foo', orig_test.getDetails()['foo'].iter_bytes())
1807
 
        self.assertEqual(None, cloned_test.getDetails().get('foo'))
1808
 
 
1809
 
    def test_double_apply_scenario_preserves_first_scenario(self):
1810
 
        """Applying two levels of scenarios to a test preserves the attributes
1811
 
        added by both scenarios.
1812
 
        """
1813
 
        class Test(tests.TestCase):
1814
 
            def test_foo(self):
1815
 
                pass
1816
 
        test = Test('test_foo')
1817
 
        scenarios_x = [('x=1', {'x': 1}), ('x=2', {'x': 2})]
1818
 
        scenarios_y = [('y=1', {'y': 1}), ('y=2', {'y': 2})]
1819
 
        suite = tests.multiply_tests(test, scenarios_x, unittest.TestSuite())
1820
 
        suite = tests.multiply_tests(suite, scenarios_y, unittest.TestSuite())
1821
 
        all_tests = list(tests.iter_suite_tests(suite))
1822
 
        self.assertLength(4, all_tests)
1823
 
        all_xys = sorted((t.x, t.y) for t in all_tests)
1824
 
        self.assertEqual([(1, 1), (1, 2), (2, 1), (2, 2)], all_xys)
1825
 
 
1826
1658
 
1827
1659
# NB: Don't delete this; it's not actually from 0.11!
1828
1660
@deprecated_function(deprecated_in((0, 11, 0)))
1956
1788
    def test_make_branch_and_tree_with_format(self):
1957
1789
        # we should be able to supply a format to make_branch_and_tree
1958
1790
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
 
1791
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1959
1792
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1960
1793
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
1794
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
 
1795
                              bzrlib.bzrdir.BzrDirFormat6)
1961
1796
 
1962
1797
    def test_make_branch_and_memory_tree(self):
1963
1798
        # we should be able to get a new branch and a mutable tree from
1980
1815
                tree.branch.repository.bzrdir.root_transport)
1981
1816
 
1982
1817
 
1983
 
class SelfTestHelper(object):
 
1818
class SelfTestHelper:
1984
1819
 
1985
1820
    def run_selftest(self, **kwargs):
1986
1821
        """Run selftest returning its output."""
2040
1875
        self.assertLength(2, output.readlines())
2041
1876
 
2042
1877
    def test_lsprof_tests(self):
2043
 
        self.requireFeature(features.lsprof_feature)
2044
 
        results = []
 
1878
        self.requireFeature(test_lsprof.LSProfFeature)
 
1879
        calls = []
2045
1880
        class Test(object):
2046
1881
            def __call__(test, result):
2047
1882
                test.run(result)
2048
1883
            def run(test, result):
2049
 
                results.append(result)
 
1884
                self.assertIsInstance(result, tests.ForwardingResult)
 
1885
                calls.append("called")
2050
1886
            def countTestCases(self):
2051
1887
                return 1
2052
1888
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
2053
 
        self.assertLength(1, results)
2054
 
        self.assertIsInstance(results.pop(), ExtendedToOriginalDecorator)
 
1889
        self.assertLength(1, calls)
2055
1890
 
2056
1891
    def test_random(self):
2057
1892
        # test randomising by listing a number of tests.
2112
1947
 
2113
1948
    def test_transport_sftp(self):
2114
1949
        self.requireFeature(features.paramiko)
2115
 
        from bzrlib.tests import stub_sftp
2116
1950
        self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
2117
1951
 
2118
1952
    def test_transport_memory(self):
2137
1971
            load_list='missing file name', list_only=True)
2138
1972
 
2139
1973
 
2140
 
class TestSubunitLogDetails(tests.TestCase, SelfTestHelper):
2141
 
 
2142
 
    _test_needs_features = [features.subunit]
2143
 
 
2144
 
    def run_subunit_stream(self, test_name):
2145
 
        from subunit import ProtocolTestCase
2146
 
        def factory():
2147
 
            return TestUtil.TestSuite([_get_test(test_name)])
2148
 
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
2149
 
            test_suite_factory=factory)
2150
 
        test = ProtocolTestCase(stream)
2151
 
        result = testtools.TestResult()
2152
 
        test.run(result)
2153
 
        content = stream.getvalue()
2154
 
        return content, result
2155
 
 
2156
 
    def test_fail_has_log(self):
2157
 
        content, result = self.run_subunit_stream('test_fail')
2158
 
        self.assertEqual(1, len(result.failures))
2159
 
        self.assertContainsRe(content, '(?m)^log$')
2160
 
        self.assertContainsRe(content, 'this test will fail')
2161
 
 
2162
 
    def test_error_has_log(self):
2163
 
        content, result = self.run_subunit_stream('test_error')
2164
 
        self.assertContainsRe(content, '(?m)^log$')
2165
 
        self.assertContainsRe(content, 'this test errored')
2166
 
 
2167
 
    def test_skip_has_no_log(self):
2168
 
        content, result = self.run_subunit_stream('test_skip')
2169
 
        self.assertNotContainsRe(content, '(?m)^log$')
2170
 
        self.assertNotContainsRe(content, 'this test will be skipped')
2171
 
        self.assertEqual(['reason'], result.skip_reasons.keys())
2172
 
        skips = result.skip_reasons['reason']
2173
 
        self.assertEqual(1, len(skips))
2174
 
        test = skips[0]
2175
 
        # RemotedTestCase doesn't preserve the "details"
2176
 
        ## self.assertFalse('log' in test.getDetails())
2177
 
 
2178
 
    def test_missing_feature_has_no_log(self):
2179
 
        content, result = self.run_subunit_stream('test_missing_feature')
2180
 
        self.assertNotContainsRe(content, '(?m)^log$')
2181
 
        self.assertNotContainsRe(content, 'missing the feature')
2182
 
        self.assertEqual(['_MissingFeature\n'], result.skip_reasons.keys())
2183
 
        skips = result.skip_reasons['_MissingFeature\n']
2184
 
        self.assertEqual(1, len(skips))
2185
 
        test = skips[0]
2186
 
        # RemotedTestCase doesn't preserve the "details"
2187
 
        ## self.assertFalse('log' in test.getDetails())
2188
 
 
2189
 
    def test_xfail_has_no_log(self):
2190
 
        content, result = self.run_subunit_stream('test_xfail')
2191
 
        self.assertNotContainsRe(content, '(?m)^log$')
2192
 
        self.assertNotContainsRe(content, 'test with expected failure')
2193
 
        self.assertEqual(1, len(result.expectedFailures))
2194
 
        result_content = result.expectedFailures[0][1]
2195
 
        self.assertNotContainsRe(result_content, 'Text attachment: log')
2196
 
        self.assertNotContainsRe(result_content, 'test with expected failure')
2197
 
 
2198
 
    def test_unexpected_success_has_log(self):
2199
 
        content, result = self.run_subunit_stream('test_unexpected_success')
2200
 
        self.assertContainsRe(content, '(?m)^log$')
2201
 
        self.assertContainsRe(content, 'test with unexpected success')
2202
 
        # GZ 2011-05-18: Old versions of subunit treat unexpected success as a
2203
 
        #                success, if a min version check is added remove this
2204
 
        from subunit import TestProtocolClient as _Client
2205
 
        if _Client.addUnexpectedSuccess.im_func is _Client.addSuccess.im_func:
2206
 
            self.expectFailure('subunit treats "unexpectedSuccess"'
2207
 
                               ' as a plain success',
2208
 
                self.assertEqual, 1, len(result.unexpectedSuccesses))
2209
 
        self.assertEqual(1, len(result.unexpectedSuccesses))
2210
 
        test = result.unexpectedSuccesses[0]
2211
 
        # RemotedTestCase doesn't preserve the "details"
2212
 
        ## self.assertTrue('log' in test.getDetails())
2213
 
 
2214
 
    def test_success_has_no_log(self):
2215
 
        content, result = self.run_subunit_stream('test_success')
2216
 
        self.assertEqual(1, result.testsRun)
2217
 
        self.assertNotContainsRe(content, '(?m)^log$')
2218
 
        self.assertNotContainsRe(content, 'this test succeeds')
2219
 
 
2220
 
 
2221
1974
class TestRunBzr(tests.TestCase):
2222
1975
 
2223
1976
    out = ''
2346
2099
        # stdout and stderr of the invoked run_bzr
2347
2100
        current_factory = bzrlib.ui.ui_factory
2348
2101
        self.run_bzr(['foo'])
2349
 
        self.assertFalse(current_factory is self.factory)
 
2102
        self.failIf(current_factory is self.factory)
2350
2103
        self.assertNotEqual(sys.stdout, self.factory.stdout)
2351
2104
        self.assertNotEqual(sys.stderr, self.factory.stderr)
2352
2105
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
2509
2262
 
2510
2263
 
2511
2264
class TestStartBzrSubProcess(tests.TestCase):
2512
 
    """Stub test start_bzr_subprocess."""
2513
2265
 
2514
 
    def _subprocess_log_cleanup(self):
2515
 
        """Inhibits the base version as we don't produce a log file."""
 
2266
    def check_popen_state(self):
 
2267
        """Replace to make assertions when popen is called."""
2516
2268
 
2517
2269
    def _popen(self, *args, **kwargs):
2518
 
        """Override the base version to record the command that is run.
2519
 
 
2520
 
        From there we can ensure it is correct without spawning a real process.
2521
 
        """
 
2270
        """Record the command that is run, so that we can ensure it is correct"""
2522
2271
        self.check_popen_state()
2523
2272
        self._popen_args = args
2524
2273
        self._popen_kwargs = kwargs
2525
2274
        raise _DontSpawnProcess()
2526
2275
 
2527
 
    def check_popen_state(self):
2528
 
        """Replace to make assertions when popen is called."""
2529
 
 
2530
2276
    def test_run_bzr_subprocess_no_plugins(self):
2531
2277
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2532
2278
        command = self._popen_args[0]
2536
2282
 
2537
2283
    def test_allow_plugins(self):
2538
2284
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2539
 
                          allow_plugins=True)
 
2285
            allow_plugins=True)
2540
2286
        command = self._popen_args[0]
2541
2287
        self.assertEqual([], command[2:])
2542
2288
 
2543
2289
    def test_set_env(self):
2544
 
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2290
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
2545
2291
        # set in the child
2546
2292
        def check_environment():
2547
2293
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2548
2294
        self.check_popen_state = check_environment
2549
2295
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2550
 
                          env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2296
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
2551
2297
        # not set in theparent
2552
2298
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2553
2299
 
2554
2300
    def test_run_bzr_subprocess_env_del(self):
2555
2301
        """run_bzr_subprocess can remove environment variables too."""
2556
 
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2302
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
2557
2303
        def check_environment():
2558
2304
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2559
2305
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2560
2306
        self.check_popen_state = check_environment
2561
2307
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2562
 
                          env_changes={'EXISTANT_ENV_VAR':None})
 
2308
            env_changes={'EXISTANT_ENV_VAR':None})
2563
2309
        # Still set in parent
2564
2310
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2565
2311
        del os.environ['EXISTANT_ENV_VAR']
2566
2312
 
2567
2313
    def test_env_del_missing(self):
2568
 
        self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
 
2314
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2569
2315
        def check_environment():
2570
2316
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2571
2317
        self.check_popen_state = check_environment
2572
2318
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2573
 
                          env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2319
            env_changes={'NON_EXISTANT_ENV_VAR':None})
2574
2320
 
2575
2321
    def test_working_dir(self):
2576
2322
        """Test that we can specify the working dir for the child"""
2579
2325
        chdirs = []
2580
2326
        def chdir(path):
2581
2327
            chdirs.append(path)
2582
 
        self.overrideAttr(os, 'chdir', chdir)
2583
 
        def getcwd():
2584
 
            return 'current'
2585
 
        self.overrideAttr(osutils, 'getcwd', getcwd)
2586
 
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2587
 
                          working_dir='foo')
 
2328
        os.chdir = chdir
 
2329
        try:
 
2330
            def getcwd():
 
2331
                return 'current'
 
2332
            osutils.getcwd = getcwd
 
2333
            try:
 
2334
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2335
                    working_dir='foo')
 
2336
            finally:
 
2337
                osutils.getcwd = orig_getcwd
 
2338
        finally:
 
2339
            os.chdir = orig_chdir
2588
2340
        self.assertEqual(['foo', 'current'], chdirs)
2589
2341
 
2590
 
    def test_get_bzr_path_with_cwd_bzrlib(self):
2591
 
        self.get_source_path = lambda: ""
2592
 
        self.overrideAttr(os.path, "isfile", lambda path: True)
2593
 
        self.assertEqual(self.get_bzr_path(), "bzr")
2594
 
 
2595
2342
 
2596
2343
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2597
2344
    """Tests that really need to do things with an external bzr."""
2610
2357
        self.assertEqual('bzr: interrupted\n', result[1])
2611
2358
 
2612
2359
 
 
2360
class TestFeature(tests.TestCase):
 
2361
 
 
2362
    def test_caching(self):
 
2363
        """Feature._probe is called by the feature at most once."""
 
2364
        class InstrumentedFeature(tests.Feature):
 
2365
            def __init__(self):
 
2366
                super(InstrumentedFeature, self).__init__()
 
2367
                self.calls = []
 
2368
            def _probe(self):
 
2369
                self.calls.append('_probe')
 
2370
                return False
 
2371
        feature = InstrumentedFeature()
 
2372
        feature.available()
 
2373
        self.assertEqual(['_probe'], feature.calls)
 
2374
        feature.available()
 
2375
        self.assertEqual(['_probe'], feature.calls)
 
2376
 
 
2377
    def test_named_str(self):
 
2378
        """Feature.__str__ should thunk to feature_name()."""
 
2379
        class NamedFeature(tests.Feature):
 
2380
            def feature_name(self):
 
2381
                return 'symlinks'
 
2382
        feature = NamedFeature()
 
2383
        self.assertEqual('symlinks', str(feature))
 
2384
 
 
2385
    def test_default_str(self):
 
2386
        """Feature.__str__ should default to __class__.__name__."""
 
2387
        class NamedFeature(tests.Feature):
 
2388
            pass
 
2389
        feature = NamedFeature()
 
2390
        self.assertEqual('NamedFeature', str(feature))
 
2391
 
 
2392
 
 
2393
class TestUnavailableFeature(tests.TestCase):
 
2394
 
 
2395
    def test_access_feature(self):
 
2396
        feature = tests.Feature()
 
2397
        exception = tests.UnavailableFeature(feature)
 
2398
        self.assertIs(feature, exception.args[0])
 
2399
 
 
2400
 
 
2401
simple_thunk_feature = tests._CompatabilityThunkFeature(
 
2402
    deprecated_in((2, 1, 0)),
 
2403
    'bzrlib.tests.test_selftest',
 
2404
    'simple_thunk_feature','UnicodeFilename',
 
2405
    replacement_module='bzrlib.tests'
 
2406
    )
 
2407
 
 
2408
class Test_CompatibilityFeature(tests.TestCase):
 
2409
 
 
2410
    def test_does_thunk(self):
 
2411
        res = self.callDeprecated(
 
2412
            ['bzrlib.tests.test_selftest.simple_thunk_feature was deprecated'
 
2413
             ' in version 2.1.0. Use bzrlib.tests.UnicodeFilename instead.'],
 
2414
            simple_thunk_feature.available)
 
2415
        self.assertEqual(tests.UnicodeFilename.available(), res)
 
2416
 
 
2417
 
 
2418
class TestModuleAvailableFeature(tests.TestCase):
 
2419
 
 
2420
    def test_available_module(self):
 
2421
        feature = tests.ModuleAvailableFeature('bzrlib.tests')
 
2422
        self.assertEqual('bzrlib.tests', feature.module_name)
 
2423
        self.assertEqual('bzrlib.tests', str(feature))
 
2424
        self.assertTrue(feature.available())
 
2425
        self.assertIs(tests, feature.module)
 
2426
 
 
2427
    def test_unavailable_module(self):
 
2428
        feature = tests.ModuleAvailableFeature('bzrlib.no_such_module_exists')
 
2429
        self.assertEqual('bzrlib.no_such_module_exists', str(feature))
 
2430
        self.assertFalse(feature.available())
 
2431
        self.assertIs(None, feature.module)
 
2432
 
 
2433
 
2613
2434
class TestSelftestFiltering(tests.TestCase):
2614
2435
 
2615
2436
    def setUp(self):
2766
2587
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2767
2588
 
2768
2589
 
2769
 
class TestCheckTreeShape(tests.TestCaseWithTransport):
 
2590
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2770
2591
 
2771
 
    def test_check_tree_shape(self):
 
2592
    def test_check_inventory_shape(self):
2772
2593
        files = ['a', 'b/', 'b/c']
2773
2594
        tree = self.make_branch_and_tree('.')
2774
2595
        self.build_tree(files)
2775
2596
        tree.add(files)
2776
2597
        tree.lock_read()
2777
2598
        try:
2778
 
            self.check_tree_shape(tree, files)
 
2599
            self.check_inventory_shape(tree.inventory, files)
2779
2600
        finally:
2780
2601
            tree.unlock()
2781
2602
 
2952
2773
        # Test that a plausible list of modules to doctest is returned
2953
2774
        # by _test_suite_modules_to_doctest.
2954
2775
        test_list = tests._test_suite_modules_to_doctest()
2955
 
        if __doc__ is None:
2956
 
            # When docstrings are stripped, there are no modules to doctest
2957
 
            self.assertEqual([], test_list)
2958
 
            return
2959
2776
        self.assertSubset([
2960
2777
            'bzrlib.timestamp',
2961
2778
            ],
2978
2795
        self.overrideAttr(tests, '_test_suite_testmod_names', testmod_names)
2979
2796
        def doctests():
2980
2797
            calls.append("modules_to_doctest")
2981
 
            if __doc__ is None:
2982
 
                return []
2983
2798
            return ['bzrlib.timestamp']
2984
2799
        self.overrideAttr(tests, '_test_suite_modules_to_doctest', doctests)
2985
2800
        expected_test_list = [
2988
2803
            ('bzrlib.tests.per_transport.TransportTests'
2989
2804
             '.test_abspath(LocalTransport,LocalURLServer)'),
2990
2805
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
 
2806
            # modules_to_doctest
 
2807
            'bzrlib.timestamp.format_highres_date',
2991
2808
            # plugins can't be tested that way since selftest may be run with
2992
2809
            # --no-plugins
2993
2810
            ]
2994
 
        if __doc__ is not None:
2995
 
            expected_test_list.extend([
2996
 
                # modules_to_doctest
2997
 
                'bzrlib.timestamp.format_highres_date',
2998
 
                ])
2999
2811
        suite = tests.test_suite()
3000
2812
        self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
3001
2813
            set(calls))
3113
2925
        tpr.register('bar', 'bBB.aAA.rRR')
3114
2926
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
3115
2927
        self.assertThat(self.get_log(),
3116
 
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR",
3117
 
                           doctest.ELLIPSIS))
 
2928
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR", ELLIPSIS))
3118
2929
 
3119
2930
    def test_get_unknown_prefix(self):
3120
2931
        tpr = self._get_registry()
3140
2951
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
3141
2952
 
3142
2953
 
3143
 
class TestThreadLeakDetection(tests.TestCase):
3144
 
    """Ensure when tests leak threads we detect and report it"""
3145
 
 
3146
 
    class LeakRecordingResult(tests.ExtendedTestResult):
3147
 
        def __init__(self):
3148
 
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
3149
 
            self.leaks = []
3150
 
        def _report_thread_leak(self, test, leaks, alive):
3151
 
            self.leaks.append((test, leaks))
3152
 
 
3153
 
    def test_testcase_without_addCleanups(self):
3154
 
        """Check old TestCase instances don't break with leak detection"""
3155
 
        class Test(unittest.TestCase):
3156
 
            def runTest(self):
3157
 
                pass
3158
 
        result = self.LeakRecordingResult()
3159
 
        test = Test()
3160
 
        result.startTestRun()
3161
 
        test.run(result)
3162
 
        result.stopTestRun()
3163
 
        self.assertEqual(result._tests_leaking_threads_count, 0)
3164
 
        self.assertEqual(result.leaks, [])
3165
 
        
3166
 
    def test_thread_leak(self):
3167
 
        """Ensure a thread that outlives the running of a test is reported
3168
 
 
3169
 
        Uses a thread that blocks on an event, and is started by the inner
3170
 
        test case. As the thread outlives the inner case's run, it should be
3171
 
        detected as a leak, but the event is then set so that the thread can
3172
 
        be safely joined in cleanup so it's not leaked for real.
3173
 
        """
3174
 
        event = threading.Event()
3175
 
        thread = threading.Thread(name="Leaker", target=event.wait)
3176
 
        class Test(tests.TestCase):
3177
 
            def test_leak(self):
3178
 
                thread.start()
3179
 
        result = self.LeakRecordingResult()
3180
 
        test = Test("test_leak")
3181
 
        self.addCleanup(thread.join)
3182
 
        self.addCleanup(event.set)
3183
 
        result.startTestRun()
3184
 
        test.run(result)
3185
 
        result.stopTestRun()
3186
 
        self.assertEqual(result._tests_leaking_threads_count, 1)
3187
 
        self.assertEqual(result._first_thread_leaker_id, test.id())
3188
 
        self.assertEqual(result.leaks, [(test, set([thread]))])
3189
 
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
3190
 
 
3191
 
    def test_multiple_leaks(self):
3192
 
        """Check multiple leaks are blamed on the test cases at fault
3193
 
 
3194
 
        Same concept as the previous test, but has one inner test method that
3195
 
        leaks two threads, and one that doesn't leak at all.
3196
 
        """
3197
 
        event = threading.Event()
3198
 
        thread_a = threading.Thread(name="LeakerA", target=event.wait)
3199
 
        thread_b = threading.Thread(name="LeakerB", target=event.wait)
3200
 
        thread_c = threading.Thread(name="LeakerC", target=event.wait)
3201
 
        class Test(tests.TestCase):
3202
 
            def test_first_leak(self):
3203
 
                thread_b.start()
3204
 
            def test_second_no_leak(self):
3205
 
                pass
3206
 
            def test_third_leak(self):
3207
 
                thread_c.start()
3208
 
                thread_a.start()
3209
 
        result = self.LeakRecordingResult()
3210
 
        first_test = Test("test_first_leak")
3211
 
        third_test = Test("test_third_leak")
3212
 
        self.addCleanup(thread_a.join)
3213
 
        self.addCleanup(thread_b.join)
3214
 
        self.addCleanup(thread_c.join)
3215
 
        self.addCleanup(event.set)
3216
 
        result.startTestRun()
3217
 
        unittest.TestSuite(
3218
 
            [first_test, Test("test_second_no_leak"), third_test]
3219
 
            ).run(result)
3220
 
        result.stopTestRun()
3221
 
        self.assertEqual(result._tests_leaking_threads_count, 2)
3222
 
        self.assertEqual(result._first_thread_leaker_id, first_test.id())
3223
 
        self.assertEqual(result.leaks, [
3224
 
            (first_test, set([thread_b])),
3225
 
            (third_test, set([thread_a, thread_c]))])
3226
 
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
3227
 
 
3228
 
 
3229
 
class TestPostMortemDebugging(tests.TestCase):
3230
 
    """Check post mortem debugging works when tests fail or error"""
3231
 
 
3232
 
    class TracebackRecordingResult(tests.ExtendedTestResult):
3233
 
        def __init__(self):
3234
 
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
3235
 
            self.postcode = None
3236
 
        def _post_mortem(self, tb=None):
3237
 
            """Record the code object at the end of the current traceback"""
3238
 
            tb = tb or sys.exc_info()[2]
3239
 
            if tb is not None:
3240
 
                next = tb.tb_next
3241
 
                while next is not None:
3242
 
                    tb = next
3243
 
                    next = next.tb_next
3244
 
                self.postcode = tb.tb_frame.f_code
3245
 
        def report_error(self, test, err):
3246
 
            pass
3247
 
        def report_failure(self, test, err):
3248
 
            pass
3249
 
 
3250
 
    def test_location_unittest_error(self):
3251
 
        """Needs right post mortem traceback with erroring unittest case"""
3252
 
        class Test(unittest.TestCase):
3253
 
            def runTest(self):
3254
 
                raise RuntimeError
3255
 
        result = self.TracebackRecordingResult()
3256
 
        Test().run(result)
3257
 
        self.assertEqual(result.postcode, Test.runTest.func_code)
3258
 
 
3259
 
    def test_location_unittest_failure(self):
3260
 
        """Needs right post mortem traceback with failing unittest case"""
3261
 
        class Test(unittest.TestCase):
3262
 
            def runTest(self):
3263
 
                raise self.failureException
3264
 
        result = self.TracebackRecordingResult()
3265
 
        Test().run(result)
3266
 
        self.assertEqual(result.postcode, Test.runTest.func_code)
3267
 
 
3268
 
    def test_location_bt_error(self):
3269
 
        """Needs right post mortem traceback with erroring bzrlib.tests case"""
3270
 
        class Test(tests.TestCase):
3271
 
            def test_error(self):
3272
 
                raise RuntimeError
3273
 
        result = self.TracebackRecordingResult()
3274
 
        Test("test_error").run(result)
3275
 
        self.assertEqual(result.postcode, Test.test_error.func_code)
3276
 
 
3277
 
    def test_location_bt_failure(self):
3278
 
        """Needs right post mortem traceback with failing bzrlib.tests case"""
3279
 
        class Test(tests.TestCase):
3280
 
            def test_failure(self):
3281
 
                raise self.failureException
3282
 
        result = self.TracebackRecordingResult()
3283
 
        Test("test_failure").run(result)
3284
 
        self.assertEqual(result.postcode, Test.test_failure.func_code)
3285
 
 
3286
 
    def test_env_var_triggers_post_mortem(self):
3287
 
        """Check pdb.post_mortem is called iff BZR_TEST_PDB is set"""
3288
 
        import pdb
3289
 
        result = tests.ExtendedTestResult(StringIO(), 0, 1)
3290
 
        post_mortem_calls = []
3291
 
        self.overrideAttr(pdb, "post_mortem", post_mortem_calls.append)
3292
 
        self.overrideEnv('BZR_TEST_PDB', None)
3293
 
        result._post_mortem(1)
3294
 
        self.overrideEnv('BZR_TEST_PDB', 'on')
3295
 
        result._post_mortem(2)
3296
 
        self.assertEqual([2], post_mortem_calls)
3297
 
 
3298
 
 
3299
2954
class TestRunSuite(tests.TestCase):
3300
2955
 
3301
2956
    def test_runner_class(self):
3312
2967
                                                self.verbosity)
3313
2968
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
3314
2969
        self.assertLength(1, calls)
3315
 
 
3316
 
 
3317
 
class TestEnvironHandling(tests.TestCase):
3318
 
 
3319
 
    def test_overrideEnv_None_called_twice_doesnt_leak(self):
3320
 
        self.assertFalse('MYVAR' in os.environ)
3321
 
        self.overrideEnv('MYVAR', '42')
3322
 
        # We use an embedded test to make sure we fix the _captureVar bug
3323
 
        class Test(tests.TestCase):
3324
 
            def test_me(self):
3325
 
                # The first call save the 42 value
3326
 
                self.overrideEnv('MYVAR', None)
3327
 
                self.assertEquals(None, os.environ.get('MYVAR'))
3328
 
                # Make sure we can call it twice
3329
 
                self.overrideEnv('MYVAR', None)
3330
 
                self.assertEquals(None, os.environ.get('MYVAR'))
3331
 
        output = StringIO()
3332
 
        result = tests.TextTestResult(output, 0, 1)
3333
 
        Test('test_me').run(result)
3334
 
        if not result.wasStrictlySuccessful():
3335
 
            self.fail(output.getvalue())
3336
 
        # We get our value back
3337
 
        self.assertEquals('42', os.environ.get('MYVAR'))
3338
 
 
3339
 
 
3340
 
class TestIsolatedEnv(tests.TestCase):
3341
 
    """Test isolating tests from os.environ.
3342
 
 
3343
 
    Since we use tests that are already isolated from os.environ a bit of care
3344
 
    should be taken when designing the tests to avoid bootstrap side-effects.
3345
 
    The tests start an already clean os.environ which allow doing valid
3346
 
    assertions about which variables are present or not and design tests around
3347
 
    these assertions.
3348
 
    """
3349
 
 
3350
 
    class ScratchMonkey(tests.TestCase):
3351
 
 
3352
 
        def test_me(self):
3353
 
            pass
3354
 
 
3355
 
    def test_basics(self):
3356
 
        # Make sure we know the definition of BZR_HOME: not part of os.environ
3357
 
        # for tests.TestCase.
3358
 
        self.assertTrue('BZR_HOME' in tests.isolated_environ)
3359
 
        self.assertEquals(None, tests.isolated_environ['BZR_HOME'])
3360
 
        # Being part of isolated_environ, BZR_HOME should not appear here
3361
 
        self.assertFalse('BZR_HOME' in os.environ)
3362
 
        # Make sure we know the definition of LINES: part of os.environ for
3363
 
        # tests.TestCase
3364
 
        self.assertTrue('LINES' in tests.isolated_environ)
3365
 
        self.assertEquals('25', tests.isolated_environ['LINES'])
3366
 
        self.assertEquals('25', os.environ['LINES'])
3367
 
 
3368
 
    def test_injecting_unknown_variable(self):
3369
 
        # BZR_HOME is known to be absent from os.environ
3370
 
        test = self.ScratchMonkey('test_me')
3371
 
        tests.override_os_environ(test, {'BZR_HOME': 'foo'})
3372
 
        self.assertEquals('foo', os.environ['BZR_HOME'])
3373
 
        tests.restore_os_environ(test)
3374
 
        self.assertFalse('BZR_HOME' in os.environ)
3375
 
 
3376
 
    def test_injecting_known_variable(self):
3377
 
        test = self.ScratchMonkey('test_me')
3378
 
        # LINES is known to be present in os.environ
3379
 
        tests.override_os_environ(test, {'LINES': '42'})
3380
 
        self.assertEquals('42', os.environ['LINES'])
3381
 
        tests.restore_os_environ(test)
3382
 
        self.assertEquals('25', os.environ['LINES'])
3383
 
 
3384
 
    def test_deleting_variable(self):
3385
 
        test = self.ScratchMonkey('test_me')
3386
 
        # LINES is known to be present in os.environ
3387
 
        tests.override_os_environ(test, {'LINES': None})
3388
 
        self.assertTrue('LINES' not in os.environ)
3389
 
        tests.restore_os_environ(test)
3390
 
        self.assertEquals('25', os.environ['LINES'])
3391
 
 
3392
 
 
3393
 
class TestDocTestSuiteIsolation(tests.TestCase):
3394
 
    """Test that `tests.DocTestSuite` isolates doc tests from os.environ.
3395
 
 
3396
 
    Since tests.TestCase alreay provides an isolation from os.environ, we use
3397
 
    the clean environment as a base for testing. To precisely capture the
3398
 
    isolation provided by tests.DocTestSuite, we use doctest.DocTestSuite to
3399
 
    compare against.
3400
 
 
3401
 
    We want to make sure `tests.DocTestSuite` respect `tests.isolated_environ`,
3402
 
    not `os.environ` so each test overrides it to suit its needs.
3403
 
 
3404
 
    """
3405
 
 
3406
 
    def get_doctest_suite_for_string(self, klass, string):
3407
 
        class Finder(doctest.DocTestFinder):
3408
 
 
3409
 
            def find(*args, **kwargs):
3410
 
                test = doctest.DocTestParser().get_doctest(
3411
 
                    string, {}, 'foo', 'foo.py', 0)
3412
 
                return [test]
3413
 
 
3414
 
        suite = klass(test_finder=Finder())
3415
 
        return suite
3416
 
 
3417
 
    def run_doctest_suite_for_string(self, klass, string):
3418
 
        suite = self.get_doctest_suite_for_string(klass, string)
3419
 
        output = StringIO()
3420
 
        result = tests.TextTestResult(output, 0, 1)
3421
 
        suite.run(result)
3422
 
        return result, output
3423
 
 
3424
 
    def assertDocTestStringSucceds(self, klass, string):
3425
 
        result, output = self.run_doctest_suite_for_string(klass, string)
3426
 
        if not result.wasStrictlySuccessful():
3427
 
            self.fail(output.getvalue())
3428
 
 
3429
 
    def assertDocTestStringFails(self, klass, string):
3430
 
        result, output = self.run_doctest_suite_for_string(klass, string)
3431
 
        if result.wasStrictlySuccessful():
3432
 
            self.fail(output.getvalue())
3433
 
 
3434
 
    def test_injected_variable(self):
3435
 
        self.overrideAttr(tests, 'isolated_environ', {'LINES': '42'})
3436
 
        test = """
3437
 
            >>> import os
3438
 
            >>> os.environ['LINES']
3439
 
            '42'
3440
 
            """
3441
 
        # doctest.DocTestSuite fails as it sees '25'
3442
 
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
3443
 
        # tests.DocTestSuite sees '42'
3444
 
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
3445
 
 
3446
 
    def test_deleted_variable(self):
3447
 
        self.overrideAttr(tests, 'isolated_environ', {'LINES': None})
3448
 
        test = """
3449
 
            >>> import os
3450
 
            >>> os.environ.get('LINES')
3451
 
            """
3452
 
        # doctest.DocTestSuite fails as it sees '25'
3453
 
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
3454
 
        # tests.DocTestSuite sees None
3455
 
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
3456
 
 
3457
 
 
3458
 
class TestSelftestExcludePatterns(tests.TestCase):
3459
 
 
3460
 
    def setUp(self):
3461
 
        super(TestSelftestExcludePatterns, self).setUp()
3462
 
        self.overrideAttr(tests, 'test_suite', self.suite_factory)
3463
 
 
3464
 
    def suite_factory(self, keep_only=None, starting_with=None):
3465
 
        """A test suite factory with only a few tests."""
3466
 
        class Test(tests.TestCase):
3467
 
            def id(self):
3468
 
                # We don't need the full class path
3469
 
                return self._testMethodName
3470
 
            def a(self):
3471
 
                pass
3472
 
            def b(self):
3473
 
                pass
3474
 
            def c(self):
3475
 
                pass
3476
 
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
3477
 
 
3478
 
    def assertTestList(self, expected, *selftest_args):
3479
 
        # We rely on setUp installing the right test suite factory so we can
3480
 
        # test at the command level without loading the whole test suite
3481
 
        out, err = self.run_bzr(('selftest', '--list') + selftest_args)
3482
 
        actual = out.splitlines()
3483
 
        self.assertEquals(expected, actual)
3484
 
 
3485
 
    def test_full_list(self):
3486
 
        self.assertTestList(['a', 'b', 'c'])
3487
 
 
3488
 
    def test_single_exclude(self):
3489
 
        self.assertTestList(['b', 'c'], '-x', 'a')
3490
 
 
3491
 
    def test_mutiple_excludes(self):
3492
 
        self.assertTestList(['c'], '-x', 'a', '-x', 'b')
3493
 
 
3494
 
 
3495
 
class TestCounterHooks(tests.TestCase, SelfTestHelper):
3496
 
 
3497
 
    _test_needs_features = [features.subunit]
3498
 
 
3499
 
    def setUp(self):
3500
 
        super(TestCounterHooks, self).setUp()
3501
 
        class Test(tests.TestCase):
3502
 
 
3503
 
            def setUp(self):
3504
 
                super(Test, self).setUp()
3505
 
                self.hooks = hooks.Hooks()
3506
 
                self.hooks.add_hook('myhook', 'Foo bar blah', (2,4))
3507
 
                self.install_counter_hook(self.hooks, 'myhook')
3508
 
 
3509
 
            def no_hook(self):
3510
 
                pass
3511
 
 
3512
 
            def run_hook_once(self):
3513
 
                for hook in self.hooks['myhook']:
3514
 
                    hook(self)
3515
 
 
3516
 
        self.test_class = Test
3517
 
 
3518
 
    def assertHookCalls(self, expected_calls, test_name):
3519
 
        test = self.test_class(test_name)
3520
 
        result = unittest.TestResult()
3521
 
        test.run(result)
3522
 
        self.assertTrue(hasattr(test, '_counters'))
3523
 
        self.assertTrue(test._counters.has_key('myhook'))
3524
 
        self.assertEquals(expected_calls, test._counters['myhook'])
3525
 
 
3526
 
    def test_no_hook(self):
3527
 
        self.assertHookCalls(0, 'no_hook')
3528
 
 
3529
 
    def test_run_hook_once(self):
3530
 
        tt = features.testtools
3531
 
        if tt.module.__version__ < (0, 9, 8):
3532
 
            raise tests.TestSkipped('testtools-0.9.8 required for addDetail')
3533
 
        self.assertHookCalls(1, 'run_hook_once')