/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Vincent Ladeuil
  • Date: 2011-06-16 10:45:17 UTC
  • mto: This revision was merged to the branch mainline in revision 5981.
  • Revision ID: v.ladeuil+lp@free.fr-20110616104517-4qzhmzkxgozji88y
Add copyright notice, some docs and some cleanups.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
 
from doctest import ELLIPSIS
 
20
import doctest
21
21
import os
22
22
import signal
23
23
import sys
 
24
import threading
24
25
import time
25
26
import unittest
26
27
import warnings
27
28
 
28
 
from testtools import MultiTestResult
 
29
from testtools import (
 
30
    ExtendedToOriginalDecorator,
 
31
    MultiTestResult,
 
32
    )
 
33
from testtools.content import Content
29
34
from testtools.content_type import ContentType
30
35
from testtools.matchers import (
31
36
    DocTestMatches,
32
37
    Equals,
33
38
    )
34
 
import testtools.tests.helpers
 
39
import testtools.testresult.doubles
35
40
 
36
41
import bzrlib
37
42
from bzrlib import (
38
43
    branchbuilder,
39
44
    bzrdir,
40
 
    debug,
41
45
    errors,
 
46
    hooks,
42
47
    lockdir,
43
48
    memorytree,
44
49
    osutils,
45
 
    progress,
46
50
    remote,
47
51
    repository,
48
52
    symbol_versioning,
49
53
    tests,
50
54
    transport,
51
55
    workingtree,
 
56
    workingtree_3,
 
57
    workingtree_4,
52
58
    )
53
59
from bzrlib.repofmt import (
54
60
    groupcompress_repo,
55
 
    pack_repo,
56
 
    weaverepo,
57
61
    )
58
62
from bzrlib.symbol_versioning import (
59
63
    deprecated_function,
64
68
    features,
65
69
    test_lsprof,
66
70
    test_server,
67
 
    test_sftp_transport,
68
71
    TestUtil,
69
72
    )
70
 
from bzrlib.trace import note
 
73
from bzrlib.trace import note, mutter
71
74
from bzrlib.transport import memory
72
 
from bzrlib.version import _get_bzr_source_tree
73
75
 
74
76
 
75
77
def _test_ids(test_suite):
77
79
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
78
80
 
79
81
 
80
 
class SelftestTests(tests.TestCase):
81
 
 
82
 
    def test_import_tests(self):
83
 
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
84
 
        self.assertEqual(mod.SelftestTests, SelftestTests)
85
 
 
86
 
    def test_import_test_failure(self):
87
 
        self.assertRaises(ImportError,
88
 
                          TestUtil._load_module_by_name,
89
 
                          'bzrlib.no-name-yet')
90
 
 
91
 
 
92
82
class MetaTestLog(tests.TestCase):
93
83
 
94
84
    def test_logging(self):
100
90
            "text", "plain", {"charset": "utf8"})))
101
91
        self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
102
92
        self.assertThat(self.get_log(),
103
 
            DocTestMatches(u"...a test message\n", ELLIPSIS))
 
93
            DocTestMatches(u"...a test message\n", doctest.ELLIPSIS))
104
94
 
105
95
 
106
96
class TestUnicodeFilename(tests.TestCase):
119
109
 
120
110
        filename = u'hell\u00d8'
121
111
        self.build_tree_contents([(filename, 'contents of hello')])
122
 
        self.failUnlessExists(filename)
 
112
        self.assertPathExists(filename)
 
113
 
 
114
 
 
115
class TestClassesAvailable(tests.TestCase):
 
116
    """As a convenience we expose Test* classes from bzrlib.tests"""
 
117
 
 
118
    def test_test_case(self):
 
119
        from bzrlib.tests import TestCase
 
120
 
 
121
    def test_test_loader(self):
 
122
        from bzrlib.tests import TestLoader
 
123
 
 
124
    def test_test_suite(self):
 
125
        from bzrlib.tests import TestSuite
123
126
 
124
127
 
125
128
class TestTransportScenarios(tests.TestCase):
208
211
    def test_scenarios(self):
209
212
        # check that constructor parameters are passed through to the adapted
210
213
        # test.
211
 
        from bzrlib.tests.per_bzrdir import make_scenarios
 
214
        from bzrlib.tests.per_controldir import make_scenarios
212
215
        vfs_factory = "v"
213
216
        server1 = "a"
214
217
        server2 = "b"
312
315
        from bzrlib.tests.per_interrepository import make_scenarios
313
316
        server1 = "a"
314
317
        server2 = "b"
315
 
        formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
 
318
        formats = [("C0", "C1", "C2", "C3"), ("D0", "D1", "D2", "D3")]
316
319
        scenarios = make_scenarios(server1, server2, formats)
317
320
        self.assertEqual([
318
321
            ('C0,str,str',
319
322
             {'repository_format': 'C1',
320
323
              'repository_format_to': 'C2',
321
324
              'transport_readonly_server': 'b',
322
 
              'transport_server': 'a'}),
 
325
              'transport_server': 'a',
 
326
              'extra_setup': 'C3'}),
323
327
            ('D0,str,str',
324
328
             {'repository_format': 'D1',
325
329
              'repository_format_to': 'D2',
326
330
              'transport_readonly_server': 'b',
327
 
              'transport_server': 'a'})],
 
331
              'transport_server': 'a',
 
332
              'extra_setup': 'D3'})],
328
333
            scenarios)
329
334
 
330
335
 
336
341
        from bzrlib.tests.per_workingtree import make_scenarios
337
342
        server1 = "a"
338
343
        server2 = "b"
339
 
        formats = [workingtree.WorkingTreeFormat2(),
340
 
                   workingtree.WorkingTreeFormat3(),]
 
344
        formats = [workingtree_4.WorkingTreeFormat4(),
 
345
                   workingtree_3.WorkingTreeFormat3(),]
341
346
        scenarios = make_scenarios(server1, server2, formats)
342
347
        self.assertEqual([
343
 
            ('WorkingTreeFormat2',
 
348
            ('WorkingTreeFormat4',
344
349
             {'bzrdir_format': formats[0]._matchingbzrdir,
345
350
              'transport_readonly_server': 'b',
346
351
              'transport_server': 'a',
373
378
            )
374
379
        server1 = "a"
375
380
        server2 = "b"
376
 
        formats = [workingtree.WorkingTreeFormat2(),
377
 
                   workingtree.WorkingTreeFormat3(),]
 
381
        formats = [workingtree_4.WorkingTreeFormat4(),
 
382
                   workingtree_3.WorkingTreeFormat3(),]
378
383
        scenarios = make_scenarios(server1, server2, formats)
379
384
        self.assertEqual(7, len(scenarios))
380
 
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
381
 
        wt4_format = workingtree.WorkingTreeFormat4()
382
 
        wt5_format = workingtree.WorkingTreeFormat5()
 
385
        default_wt_format = workingtree.format_registry.get_default()
 
386
        wt4_format = workingtree_4.WorkingTreeFormat4()
 
387
        wt5_format = workingtree_4.WorkingTreeFormat5()
383
388
        expected_scenarios = [
384
 
            ('WorkingTreeFormat2',
 
389
            ('WorkingTreeFormat4',
385
390
             {'bzrdir_format': formats[0]._matchingbzrdir,
386
391
              'transport_readonly_server': 'b',
387
392
              'transport_server': 'a',
447
452
        # ones to add.
448
453
        from bzrlib.tests.per_tree import (
449
454
            return_parameter,
450
 
            revision_tree_from_workingtree
451
455
            )
452
456
        from bzrlib.tests.per_intertree import (
453
457
            make_scenarios,
454
458
            )
455
 
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
 
459
        from bzrlib.workingtree_3 import WorkingTreeFormat3
 
460
        from bzrlib.workingtree_4 import WorkingTreeFormat4
456
461
        input_test = TestInterTreeScenarios(
457
462
            "test_scenarios")
458
463
        server1 = "a"
459
464
        server2 = "b"
460
 
        format1 = WorkingTreeFormat2()
 
465
        format1 = WorkingTreeFormat4()
461
466
        format2 = WorkingTreeFormat3()
462
467
        formats = [("1", str, format1, format2, "converter1"),
463
468
            ("2", int, format2, format1, "converter2")]
509
514
        self.assertRaises(AssertionError, self.assertEqualStat,
510
515
            os.lstat("foo"), os.lstat("longname"))
511
516
 
 
517
    def test_failUnlessExists(self):
 
518
        """Deprecated failUnlessExists and failIfExists"""
 
519
        self.applyDeprecated(
 
520
            deprecated_in((2, 4)),
 
521
            self.failUnlessExists, '.')
 
522
        self.build_tree(['foo/', 'foo/bar'])
 
523
        self.applyDeprecated(
 
524
            deprecated_in((2, 4)),
 
525
            self.failUnlessExists, 'foo/bar')
 
526
        self.applyDeprecated(
 
527
            deprecated_in((2, 4)),
 
528
            self.failIfExists, 'foo/foo')
 
529
 
 
530
    def test_assertPathExists(self):
 
531
        self.assertPathExists('.')
 
532
        self.build_tree(['foo/', 'foo/bar'])
 
533
        self.assertPathExists('foo/bar')
 
534
        self.assertPathDoesNotExist('foo/foo')
 
535
 
512
536
 
513
537
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
514
538
 
548
572
        tree = self.make_branch_and_memory_tree('dir')
549
573
        # Guard against regression into MemoryTransport leaking
550
574
        # files to disk instead of keeping them in memory.
551
 
        self.failIf(osutils.lexists('dir'))
 
575
        self.assertFalse(osutils.lexists('dir'))
552
576
        self.assertIsInstance(tree, memorytree.MemoryTree)
553
577
 
554
578
    def test_make_branch_and_memory_tree_with_format(self):
555
579
        """make_branch_and_memory_tree should accept a format option."""
556
580
        format = bzrdir.BzrDirMetaFormat1()
557
 
        format.repository_format = weaverepo.RepositoryFormat7()
 
581
        format.repository_format = repository.format_registry.get_default()
558
582
        tree = self.make_branch_and_memory_tree('dir', format=format)
559
583
        # Guard against regression into MemoryTransport leaking
560
584
        # files to disk instead of keeping them in memory.
561
 
        self.failIf(osutils.lexists('dir'))
 
585
        self.assertFalse(osutils.lexists('dir'))
562
586
        self.assertIsInstance(tree, memorytree.MemoryTree)
563
587
        self.assertEqual(format.repository_format.__class__,
564
588
            tree.branch.repository._format.__class__)
568
592
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
569
593
        # Guard against regression into MemoryTransport leaking
570
594
        # files to disk instead of keeping them in memory.
571
 
        self.failIf(osutils.lexists('dir'))
 
595
        self.assertFalse(osutils.lexists('dir'))
572
596
 
573
597
    def test_make_branch_builder_with_format(self):
574
598
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
575
599
        # that the format objects are used.
576
600
        format = bzrdir.BzrDirMetaFormat1()
577
 
        repo_format = weaverepo.RepositoryFormat7()
 
601
        repo_format = repository.format_registry.get_default()
578
602
        format.repository_format = repo_format
579
603
        builder = self.make_branch_builder('dir', format=format)
580
604
        the_branch = builder.get_branch()
581
605
        # Guard against regression into MemoryTransport leaking
582
606
        # files to disk instead of keeping them in memory.
583
 
        self.failIf(osutils.lexists('dir'))
 
607
        self.assertFalse(osutils.lexists('dir'))
584
608
        self.assertEqual(format.repository_format.__class__,
585
609
                         the_branch.repository._format.__class__)
586
610
        self.assertEqual(repo_format.get_format_string(),
592
616
        the_branch = builder.get_branch()
593
617
        # Guard against regression into MemoryTransport leaking
594
618
        # files to disk instead of keeping them in memory.
595
 
        self.failIf(osutils.lexists('dir'))
 
619
        self.assertFalse(osutils.lexists('dir'))
596
620
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
597
621
        self.assertEqual(dir_format.repository_format.__class__,
598
622
                         the_branch.repository._format.__class__)
609
633
                l.attempt_lock()
610
634
        test = TestDanglingLock('test_function')
611
635
        result = test.run()
 
636
        total_failures = result.errors + result.failures
612
637
        if self._lock_check_thorough:
613
 
            self.assertEqual(1, len(result.errors))
 
638
            self.assertEqual(1, len(total_failures))
614
639
        else:
615
640
            # When _lock_check_thorough is disabled, then we don't trigger a
616
641
            # failure
617
 
            self.assertEqual(0, len(result.errors))
 
642
            self.assertEqual(0, len(total_failures))
618
643
 
619
644
 
620
645
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
621
646
    """Tests for the convenience functions TestCaseWithTransport introduces."""
622
647
 
623
648
    def test_get_readonly_url_none(self):
624
 
        from bzrlib.transport import get_transport
625
649
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
626
650
        self.vfs_transport_factory = memory.MemoryServer
627
651
        self.transport_readonly_server = None
629
653
        # for the server
630
654
        url = self.get_readonly_url()
631
655
        url2 = self.get_readonly_url('foo/bar')
632
 
        t = get_transport(url)
633
 
        t2 = get_transport(url2)
634
 
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
635
 
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
 
656
        t = transport.get_transport(url)
 
657
        t2 = transport.get_transport(url2)
 
658
        self.assertIsInstance(t, ReadonlyTransportDecorator)
 
659
        self.assertIsInstance(t2, ReadonlyTransportDecorator)
636
660
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
637
661
 
638
662
    def test_get_readonly_url_http(self):
639
663
        from bzrlib.tests.http_server import HttpServer
640
 
        from bzrlib.transport import get_transport
641
664
        from bzrlib.transport.http import HttpTransportBase
642
665
        self.transport_server = test_server.LocalURLServer
643
666
        self.transport_readonly_server = HttpServer
645
668
        url = self.get_readonly_url()
646
669
        url2 = self.get_readonly_url('foo/bar')
647
670
        # the transport returned may be any HttpTransportBase subclass
648
 
        t = get_transport(url)
649
 
        t2 = get_transport(url2)
650
 
        self.failUnless(isinstance(t, HttpTransportBase))
651
 
        self.failUnless(isinstance(t2, HttpTransportBase))
 
671
        t = transport.get_transport(url)
 
672
        t2 = transport.get_transport(url2)
 
673
        self.assertIsInstance(t, HttpTransportBase)
 
674
        self.assertIsInstance(t2, HttpTransportBase)
652
675
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
653
676
 
654
677
    def test_is_directory(self):
662
685
    def test_make_branch_builder(self):
663
686
        builder = self.make_branch_builder('dir')
664
687
        rev_id = builder.build_commit()
665
 
        self.failUnlessExists('dir')
 
688
        self.assertPathExists('dir')
666
689
        a_dir = bzrdir.BzrDir.open('dir')
667
690
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
668
691
        a_branch = a_dir.open_branch()
684
707
        self.assertIsInstance(result_bzrdir.transport,
685
708
                              memory.MemoryTransport)
686
709
        # should not be on disk, should only be in memory
687
 
        self.failIfExists('subdir')
 
710
        self.assertPathDoesNotExist('subdir')
688
711
 
689
712
 
690
713
class TestChrootedTest(tests.ChrootedTestCase):
691
714
 
692
715
    def test_root_is_root(self):
693
 
        from bzrlib.transport import get_transport
694
 
        t = get_transport(self.get_readonly_url())
 
716
        t = transport.get_transport(self.get_readonly_url())
695
717
        url = t.base
696
718
        self.assertEqual(url, t.clone('..').base)
697
719
 
700
722
 
701
723
    def test_profiles_tests(self):
702
724
        self.requireFeature(test_lsprof.LSProfFeature)
703
 
        terminal = testtools.tests.helpers.ExtendedTestResult()
 
725
        terminal = testtools.testresult.doubles.ExtendedTestResult()
704
726
        result = tests.ProfileResult(terminal)
705
727
        class Sample(tests.TestCase):
706
728
            def a(self):
723
745
                descriptions=0,
724
746
                verbosity=1,
725
747
                )
726
 
        capture = testtools.tests.helpers.ExtendedTestResult()
 
748
        capture = testtools.testresult.doubles.ExtendedTestResult()
727
749
        test_case.run(MultiTestResult(result, capture))
728
750
        run_case = capture._events[0][1]
729
751
        timed_string = result._testTimeString(run_case)
750
772
        self.check_timing(ShortDelayTestCase('test_short_delay'),
751
773
                          r"^ +[0-9]+ms$")
752
774
 
753
 
    def _patch_get_bzr_source_tree(self):
754
 
        # Reading from the actual source tree breaks isolation, but we don't
755
 
        # want to assume that thats *all* that would happen.
756
 
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', lambda: None)
757
 
 
758
 
    def test_assigned_benchmark_file_stores_date(self):
759
 
        self._patch_get_bzr_source_tree()
760
 
        output = StringIO()
761
 
        result = bzrlib.tests.TextTestResult(self._log_file,
762
 
                                        descriptions=0,
763
 
                                        verbosity=1,
764
 
                                        bench_history=output
765
 
                                        )
766
 
        output_string = output.getvalue()
767
 
        # if you are wondering about the regexp please read the comment in
768
 
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
769
 
        # XXX: what comment?  -- Andrew Bennetts
770
 
        self.assertContainsRe(output_string, "--date [0-9.]+")
771
 
 
772
 
    def test_benchhistory_records_test_times(self):
773
 
        self._patch_get_bzr_source_tree()
774
 
        result_stream = StringIO()
775
 
        result = bzrlib.tests.TextTestResult(
776
 
            self._log_file,
777
 
            descriptions=0,
778
 
            verbosity=1,
779
 
            bench_history=result_stream
780
 
            )
781
 
 
782
 
        # we want profile a call and check that its test duration is recorded
783
 
        # make a new test instance that when run will generate a benchmark
784
 
        example_test_case = TestTestResult("_time_hello_world_encoding")
785
 
        # execute the test, which should succeed and record times
786
 
        example_test_case.run(result)
787
 
        lines = result_stream.getvalue().splitlines()
788
 
        self.assertEqual(2, len(lines))
789
 
        self.assertContainsRe(lines[1],
790
 
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
791
 
            "._time_hello_world_encoding")
792
 
 
793
775
    def _time_hello_world_encoding(self):
794
776
        """Profile two sleep calls
795
777
 
803
785
        self.requireFeature(test_lsprof.LSProfFeature)
804
786
        result_stream = StringIO()
805
787
        result = bzrlib.tests.VerboseTestResult(
806
 
            unittest._WritelnDecorator(result_stream),
 
788
            result_stream,
807
789
            descriptions=0,
808
790
            verbosity=2,
809
791
            )
835
817
        self.assertContainsRe(output,
836
818
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
837
819
 
 
820
    def test_uses_time_from_testtools(self):
 
821
        """Test case timings in verbose results should use testtools times"""
 
822
        import datetime
 
823
        class TimeAddedVerboseTestResult(tests.VerboseTestResult):
 
824
            def startTest(self, test):
 
825
                self.time(datetime.datetime.utcfromtimestamp(1.145))
 
826
                super(TimeAddedVerboseTestResult, self).startTest(test)
 
827
            def addSuccess(self, test):
 
828
                self.time(datetime.datetime.utcfromtimestamp(51.147))
 
829
                super(TimeAddedVerboseTestResult, self).addSuccess(test)
 
830
            def report_tests_starting(self): pass
 
831
        sio = StringIO()
 
832
        self.get_passing_test().run(TimeAddedVerboseTestResult(sio, 0, 2))
 
833
        self.assertEndsWith(sio.getvalue(), "OK    50002ms\n")
 
834
 
838
835
    def test_known_failure(self):
839
836
        """A KnownFailure being raised should trigger several result actions."""
840
837
        class InstrumentedTestResult(tests.ExtendedTestResult):
841
838
            def stopTestRun(self): pass
842
 
            def startTests(self): pass
843
 
            def report_test_start(self, test): pass
 
839
            def report_tests_starting(self): pass
844
840
            def report_known_failure(self, test, err=None, details=None):
845
841
                self._call = test, 'known failure'
846
842
        result = InstrumentedTestResult(None, None, None, None)
864
860
        # verbose test output formatting
865
861
        result_stream = StringIO()
866
862
        result = bzrlib.tests.VerboseTestResult(
867
 
            unittest._WritelnDecorator(result_stream),
 
863
            result_stream,
868
864
            descriptions=0,
869
865
            verbosity=2,
870
866
            )
880
876
        output = result_stream.getvalue()[prefix:]
881
877
        lines = output.splitlines()
882
878
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
 
879
        if sys.version_info > (2, 7):
 
880
            self.expectFailure("_ExpectedFailure on 2.7 loses the message",
 
881
                self.assertNotEqual, lines[1], '    ')
883
882
        self.assertEqual(lines[1], '    foo')
884
883
        self.assertEqual(2, len(lines))
885
884
 
893
892
        """Test the behaviour of invoking addNotSupported."""
894
893
        class InstrumentedTestResult(tests.ExtendedTestResult):
895
894
            def stopTestRun(self): pass
896
 
            def startTests(self): pass
897
 
            def report_test_start(self, test): pass
 
895
            def report_tests_starting(self): pass
898
896
            def report_unsupported(self, test, feature):
899
897
                self._call = test, feature
900
898
        result = InstrumentedTestResult(None, None, None, None)
919
917
        # verbose test output formatting
920
918
        result_stream = StringIO()
921
919
        result = bzrlib.tests.VerboseTestResult(
922
 
            unittest._WritelnDecorator(result_stream),
 
920
            result_stream,
923
921
            descriptions=0,
924
922
            verbosity=2,
925
923
            )
939
937
        """An UnavailableFeature being raised should invoke addNotSupported."""
940
938
        class InstrumentedTestResult(tests.ExtendedTestResult):
941
939
            def stopTestRun(self): pass
942
 
            def startTests(self): pass
943
 
            def report_test_start(self, test): pass
 
940
            def report_tests_starting(self): pass
944
941
            def addNotSupported(self, test, feature):
945
942
                self._call = test, feature
946
943
        result = InstrumentedTestResult(None, None, None, None)
988
985
        class InstrumentedTestResult(tests.ExtendedTestResult):
989
986
            calls = 0
990
987
            def startTests(self): self.calls += 1
991
 
            def report_test_start(self, test): pass
992
988
        result = InstrumentedTestResult(None, None, None, None)
993
989
        def test_function():
994
990
            pass
996
992
        test.run(result)
997
993
        self.assertEquals(1, result.calls)
998
994
 
 
995
    def test_startTests_only_once(self):
 
996
        """With multiple tests startTests should still only be called once"""
 
997
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
998
            calls = 0
 
999
            def startTests(self): self.calls += 1
 
1000
        result = InstrumentedTestResult(None, None, None, None)
 
1001
        suite = unittest.TestSuite([
 
1002
            unittest.FunctionTestCase(lambda: None),
 
1003
            unittest.FunctionTestCase(lambda: None)])
 
1004
        suite.run(result)
 
1005
        self.assertEquals(1, result.calls)
 
1006
        self.assertEquals(2, result.count)
 
1007
 
999
1008
 
1000
1009
class TestUnicodeFilenameFeature(tests.TestCase):
1001
1010
 
1022
1031
        because of our use of global state.
1023
1032
        """
1024
1033
        old_root = tests.TestCaseInTempDir.TEST_ROOT
1025
 
        old_leak = tests.TestCase._first_thread_leaker_id
1026
1034
        try:
1027
1035
            tests.TestCaseInTempDir.TEST_ROOT = None
1028
 
            tests.TestCase._first_thread_leaker_id = None
1029
1036
            return testrunner.run(test)
1030
1037
        finally:
1031
1038
            tests.TestCaseInTempDir.TEST_ROOT = old_root
1032
 
            tests.TestCase._first_thread_leaker_id = old_leak
1033
1039
 
1034
1040
    def test_known_failure_failed_run(self):
1035
1041
        # run a test that generates a known failure which should be printed in
1040
1046
        test = unittest.TestSuite()
1041
1047
        test.addTest(Test("known_failure_test"))
1042
1048
        def failing_test():
1043
 
            self.fail('foo')
 
1049
            raise AssertionError('foo')
1044
1050
        test.addTest(unittest.FunctionTestCase(failing_test))
1045
1051
        stream = StringIO()
1046
1052
        runner = tests.TextTestRunner(stream=stream)
1054
1060
            '^----------------------------------------------------------------------\n'
1055
1061
            'Traceback \\(most recent call last\\):\n'
1056
1062
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1057
 
            '    self.fail\\(\'foo\'\\)\n'
 
1063
            '    raise AssertionError\\(\'foo\'\\)\n'
1058
1064
            '.*'
1059
1065
            '^----------------------------------------------------------------------\n'
1060
1066
            '.*'
1066
1072
        # the final output.
1067
1073
        class Test(tests.TestCase):
1068
1074
            def known_failure_test(self):
1069
 
                self.expectFailure('failed', self.assertTrue, False)
 
1075
                self.knownFailure("Never works...")
1070
1076
        test = Test("known_failure_test")
1071
1077
        stream = StringIO()
1072
1078
        runner = tests.TextTestRunner(stream=stream)
1078
1084
            '\n'
1079
1085
            'OK \\(known_failures=1\\)\n')
1080
1086
 
 
1087
    def test_unexpected_success_bad(self):
 
1088
        class Test(tests.TestCase):
 
1089
            def test_truth(self):
 
1090
                self.expectFailure("No absolute truth", self.assertTrue, True)
 
1091
        runner = tests.TextTestRunner(stream=StringIO())
 
1092
        result = self.run_test_runner(runner, Test("test_truth"))
 
1093
        self.assertContainsRe(runner.stream.getvalue(),
 
1094
            "=+\n"
 
1095
            "FAIL: \\S+\.test_truth\n"
 
1096
            "-+\n"
 
1097
            "(?:.*\n)*"
 
1098
            "No absolute truth\n"
 
1099
            "(?:.*\n)*"
 
1100
            "-+\n"
 
1101
            "Ran 1 test in .*\n"
 
1102
            "\n"
 
1103
            "FAILED \\(failures=1\\)\n\\Z")
 
1104
 
1081
1105
    def test_result_decorator(self):
1082
1106
        # decorate results
1083
1107
        calls = []
1084
 
        class LoggingDecorator(tests.ForwardingResult):
 
1108
        class LoggingDecorator(ExtendedToOriginalDecorator):
1085
1109
            def startTest(self, test):
1086
 
                tests.ForwardingResult.startTest(self, test)
 
1110
                ExtendedToOriginalDecorator.startTest(self, test)
1087
1111
                calls.append('start')
1088
1112
        test = unittest.FunctionTestCase(lambda:None)
1089
1113
        stream = StringIO()
1190
1214
            ],
1191
1215
            lines[-3:])
1192
1216
 
1193
 
    def _patch_get_bzr_source_tree(self):
1194
 
        # Reading from the actual source tree breaks isolation, but we don't
1195
 
        # want to assume that thats *all* that would happen.
1196
 
        self._get_source_tree_calls = []
1197
 
        def new_get():
1198
 
            self._get_source_tree_calls.append("called")
1199
 
            return None
1200
 
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree',  new_get)
1201
 
 
1202
 
    def test_bench_history(self):
1203
 
        # tests that the running the benchmark passes bench_history into
1204
 
        # the test result object. We can tell that happens if
1205
 
        # _get_bzr_source_tree is called.
1206
 
        self._patch_get_bzr_source_tree()
1207
 
        test = TestRunner('dummy_test')
1208
 
        output = StringIO()
1209
 
        runner = tests.TextTestRunner(stream=self._log_file,
1210
 
                                      bench_history=output)
1211
 
        result = self.run_test_runner(runner, test)
1212
 
        output_string = output.getvalue()
1213
 
        self.assertContainsRe(output_string, "--date [0-9.]+")
1214
 
        self.assertLength(1, self._get_source_tree_calls)
 
1217
    def test_verbose_test_count(self):
 
1218
        """A verbose test run reports the right test count at the start"""
 
1219
        suite = TestUtil.TestSuite([
 
1220
            unittest.FunctionTestCase(lambda:None),
 
1221
            unittest.FunctionTestCase(lambda:None)])
 
1222
        self.assertEqual(suite.countTestCases(), 2)
 
1223
        stream = StringIO()
 
1224
        runner = tests.TextTestRunner(stream=stream, verbosity=2)
 
1225
        # Need to use the CountingDecorator as that's what sets num_tests
 
1226
        result = self.run_test_runner(runner, tests.CountingDecorator(suite))
 
1227
        self.assertStartsWith(stream.getvalue(), "running 2 tests")
1215
1228
 
1216
1229
    def test_startTestRun(self):
1217
1230
        """run should call result.startTestRun()"""
1218
1231
        calls = []
1219
 
        class LoggingDecorator(tests.ForwardingResult):
 
1232
        class LoggingDecorator(ExtendedToOriginalDecorator):
1220
1233
            def startTestRun(self):
1221
 
                tests.ForwardingResult.startTestRun(self)
 
1234
                ExtendedToOriginalDecorator.startTestRun(self)
1222
1235
                calls.append('startTestRun')
1223
1236
        test = unittest.FunctionTestCase(lambda:None)
1224
1237
        stream = StringIO()
1230
1243
    def test_stopTestRun(self):
1231
1244
        """run should call result.stopTestRun()"""
1232
1245
        calls = []
1233
 
        class LoggingDecorator(tests.ForwardingResult):
 
1246
        class LoggingDecorator(ExtendedToOriginalDecorator):
1234
1247
            def stopTestRun(self):
1235
 
                tests.ForwardingResult.stopTestRun(self)
 
1248
                ExtendedToOriginalDecorator.stopTestRun(self)
1236
1249
                calls.append('stopTestRun')
1237
1250
        test = unittest.FunctionTestCase(lambda:None)
1238
1251
        stream = StringIO()
1241
1254
        result = self.run_test_runner(runner, test)
1242
1255
        self.assertLength(1, calls)
1243
1256
 
 
1257
    def test_unicode_test_output_on_ascii_stream(self):
 
1258
        """Showing results should always succeed even on an ascii console"""
 
1259
        class FailureWithUnicode(tests.TestCase):
 
1260
            def test_log_unicode(self):
 
1261
                self.log(u"\u2606")
 
1262
                self.fail("Now print that log!")
 
1263
        out = StringIO()
 
1264
        self.overrideAttr(osutils, "get_terminal_encoding",
 
1265
            lambda trace=False: "ascii")
 
1266
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
 
1267
            FailureWithUnicode("test_log_unicode"))
 
1268
        self.assertContainsRe(out.getvalue(),
 
1269
            "Text attachment: log\n"
 
1270
            "-+\n"
 
1271
            "\d+\.\d+  \\\\u2606\n"
 
1272
            "-+\n")
 
1273
 
1244
1274
 
1245
1275
class SampleTestCase(tests.TestCase):
1246
1276
 
1421
1451
        sample_test = TestTestCase("method_that_times_a_bit_twice")
1422
1452
        output_stream = StringIO()
1423
1453
        result = bzrlib.tests.VerboseTestResult(
1424
 
            unittest._WritelnDecorator(output_stream),
 
1454
            output_stream,
1425
1455
            descriptions=0,
1426
1456
            verbosity=2)
1427
1457
        sample_test.run(result)
1434
1464
        # Note this test won't fail with hooks that the core library doesn't
1435
1465
        # use - but it trigger with a plugin that adds hooks, so its still a
1436
1466
        # useful warning in that case.
1437
 
        self.assertEqual(bzrlib.branch.BranchHooks(),
1438
 
            bzrlib.branch.Branch.hooks)
1439
 
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
 
1467
        self.assertEqual(bzrlib.branch.BranchHooks(), bzrlib.branch.Branch.hooks)
 
1468
        self.assertEqual(
 
1469
            bzrlib.smart.server.SmartServerHooks(),
1440
1470
            bzrlib.smart.server.SmartTCPServer.hooks)
1441
 
        self.assertEqual(bzrlib.commands.CommandHooks(),
1442
 
            bzrlib.commands.Command.hooks)
 
1471
        self.assertEqual(
 
1472
            bzrlib.commands.CommandHooks(), bzrlib.commands.Command.hooks)
1443
1473
 
1444
1474
    def test__gather_lsprof_in_benchmarks(self):
1445
1475
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1655
1685
        self.assertEqual('original', obj.test_attr)
1656
1686
 
1657
1687
 
 
1688
class _MissingFeature(tests.Feature):
 
1689
    def _probe(self):
 
1690
        return False
 
1691
missing_feature = _MissingFeature()
 
1692
 
 
1693
 
 
1694
def _get_test(name):
 
1695
    """Get an instance of a specific example test.
 
1696
 
 
1697
    We protect this in a function so that they don't auto-run in the test
 
1698
    suite.
 
1699
    """
 
1700
 
 
1701
    class ExampleTests(tests.TestCase):
 
1702
 
 
1703
        def test_fail(self):
 
1704
            mutter('this was a failing test')
 
1705
            self.fail('this test will fail')
 
1706
 
 
1707
        def test_error(self):
 
1708
            mutter('this test errored')
 
1709
            raise RuntimeError('gotcha')
 
1710
 
 
1711
        def test_missing_feature(self):
 
1712
            mutter('missing the feature')
 
1713
            self.requireFeature(missing_feature)
 
1714
 
 
1715
        def test_skip(self):
 
1716
            mutter('this test will be skipped')
 
1717
            raise tests.TestSkipped('reason')
 
1718
 
 
1719
        def test_success(self):
 
1720
            mutter('this test succeeds')
 
1721
 
 
1722
        def test_xfail(self):
 
1723
            mutter('test with expected failure')
 
1724
            self.knownFailure('this_fails')
 
1725
 
 
1726
        def test_unexpected_success(self):
 
1727
            mutter('test with unexpected success')
 
1728
            self.expectFailure('should_fail', lambda: None)
 
1729
 
 
1730
    return ExampleTests(name)
 
1731
 
 
1732
 
 
1733
class TestTestCaseLogDetails(tests.TestCase):
 
1734
 
 
1735
    def _run_test(self, test_name):
 
1736
        test = _get_test(test_name)
 
1737
        result = testtools.TestResult()
 
1738
        test.run(result)
 
1739
        return result
 
1740
 
 
1741
    def test_fail_has_log(self):
 
1742
        result = self._run_test('test_fail')
 
1743
        self.assertEqual(1, len(result.failures))
 
1744
        result_content = result.failures[0][1]
 
1745
        self.assertContainsRe(result_content, 'Text attachment: log')
 
1746
        self.assertContainsRe(result_content, 'this was a failing test')
 
1747
 
 
1748
    def test_error_has_log(self):
 
1749
        result = self._run_test('test_error')
 
1750
        self.assertEqual(1, len(result.errors))
 
1751
        result_content = result.errors[0][1]
 
1752
        self.assertContainsRe(result_content, 'Text attachment: log')
 
1753
        self.assertContainsRe(result_content, 'this test errored')
 
1754
 
 
1755
    def test_skip_has_no_log(self):
 
1756
        result = self._run_test('test_skip')
 
1757
        self.assertEqual(['reason'], result.skip_reasons.keys())
 
1758
        skips = result.skip_reasons['reason']
 
1759
        self.assertEqual(1, len(skips))
 
1760
        test = skips[0]
 
1761
        self.assertFalse('log' in test.getDetails())
 
1762
 
 
1763
    def test_missing_feature_has_no_log(self):
 
1764
        # testtools doesn't know about addNotSupported, so it just gets
 
1765
        # considered as a skip
 
1766
        result = self._run_test('test_missing_feature')
 
1767
        self.assertEqual([missing_feature], result.skip_reasons.keys())
 
1768
        skips = result.skip_reasons[missing_feature]
 
1769
        self.assertEqual(1, len(skips))
 
1770
        test = skips[0]
 
1771
        self.assertFalse('log' in test.getDetails())
 
1772
 
 
1773
    def test_xfail_has_no_log(self):
 
1774
        result = self._run_test('test_xfail')
 
1775
        self.assertEqual(1, len(result.expectedFailures))
 
1776
        result_content = result.expectedFailures[0][1]
 
1777
        self.assertNotContainsRe(result_content, 'Text attachment: log')
 
1778
        self.assertNotContainsRe(result_content, 'test with expected failure')
 
1779
 
 
1780
    def test_unexpected_success_has_log(self):
 
1781
        result = self._run_test('test_unexpected_success')
 
1782
        self.assertEqual(1, len(result.unexpectedSuccesses))
 
1783
        # Inconsistency, unexpectedSuccesses is a list of tests,
 
1784
        # expectedFailures is a list of reasons?
 
1785
        test = result.unexpectedSuccesses[0]
 
1786
        details = test.getDetails()
 
1787
        self.assertTrue('log' in details)
 
1788
 
 
1789
 
 
1790
class TestTestCloning(tests.TestCase):
 
1791
    """Tests that test cloning of TestCases (as used by multiply_tests)."""
 
1792
 
 
1793
    def test_cloned_testcase_does_not_share_details(self):
 
1794
        """A TestCase cloned with clone_test does not share mutable attributes
 
1795
        such as details or cleanups.
 
1796
        """
 
1797
        class Test(tests.TestCase):
 
1798
            def test_foo(self):
 
1799
                self.addDetail('foo', Content('text/plain', lambda: 'foo'))
 
1800
        orig_test = Test('test_foo')
 
1801
        cloned_test = tests.clone_test(orig_test, orig_test.id() + '(cloned)')
 
1802
        orig_test.run(unittest.TestResult())
 
1803
        self.assertEqual('foo', orig_test.getDetails()['foo'].iter_bytes())
 
1804
        self.assertEqual(None, cloned_test.getDetails().get('foo'))
 
1805
 
 
1806
    def test_double_apply_scenario_preserves_first_scenario(self):
 
1807
        """Applying two levels of scenarios to a test preserves the attributes
 
1808
        added by both scenarios.
 
1809
        """
 
1810
        class Test(tests.TestCase):
 
1811
            def test_foo(self):
 
1812
                pass
 
1813
        test = Test('test_foo')
 
1814
        scenarios_x = [('x=1', {'x': 1}), ('x=2', {'x': 2})]
 
1815
        scenarios_y = [('y=1', {'y': 1}), ('y=2', {'y': 2})]
 
1816
        suite = tests.multiply_tests(test, scenarios_x, unittest.TestSuite())
 
1817
        suite = tests.multiply_tests(suite, scenarios_y, unittest.TestSuite())
 
1818
        all_tests = list(tests.iter_suite_tests(suite))
 
1819
        self.assertLength(4, all_tests)
 
1820
        all_xys = sorted((t.x, t.y) for t in all_tests)
 
1821
        self.assertEqual([(1, 1), (1, 2), (2, 1), (2, 2)], all_xys)
 
1822
 
 
1823
 
1658
1824
# NB: Don't delete this; it's not actually from 0.11!
1659
1825
@deprecated_function(deprecated_in((0, 11, 0)))
1660
1826
def sample_deprecated_function():
1787
1953
    def test_make_branch_and_tree_with_format(self):
1788
1954
        # we should be able to supply a format to make_branch_and_tree
1789
1955
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1790
 
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1791
1956
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1792
1957
                              bzrlib.bzrdir.BzrDirMetaFormat1)
1793
 
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1794
 
                              bzrlib.bzrdir.BzrDirFormat6)
1795
1958
 
1796
1959
    def test_make_branch_and_memory_tree(self):
1797
1960
        # we should be able to get a new branch and a mutable tree from
1814
1977
                tree.branch.repository.bzrdir.root_transport)
1815
1978
 
1816
1979
 
1817
 
class SelfTestHelper:
 
1980
class SelfTestHelper(object):
1818
1981
 
1819
1982
    def run_selftest(self, **kwargs):
1820
1983
        """Run selftest returning its output."""
1875
2038
 
1876
2039
    def test_lsprof_tests(self):
1877
2040
        self.requireFeature(test_lsprof.LSProfFeature)
1878
 
        calls = []
 
2041
        results = []
1879
2042
        class Test(object):
1880
2043
            def __call__(test, result):
1881
2044
                test.run(result)
1882
2045
            def run(test, result):
1883
 
                self.assertIsInstance(result, tests.ForwardingResult)
1884
 
                calls.append("called")
 
2046
                results.append(result)
1885
2047
            def countTestCases(self):
1886
2048
                return 1
1887
2049
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1888
 
        self.assertLength(1, calls)
 
2050
        self.assertLength(1, results)
 
2051
        self.assertIsInstance(results.pop(), ExtendedToOriginalDecorator)
1889
2052
 
1890
2053
    def test_random(self):
1891
2054
        # test randomising by listing a number of tests.
1971
2134
            load_list='missing file name', list_only=True)
1972
2135
 
1973
2136
 
 
2137
class TestSubunitLogDetails(tests.TestCase, SelfTestHelper):
 
2138
 
 
2139
    _test_needs_features = [features.subunit]
 
2140
 
 
2141
    def run_subunit_stream(self, test_name):
 
2142
        from subunit import ProtocolTestCase
 
2143
        def factory():
 
2144
            return TestUtil.TestSuite([_get_test(test_name)])
 
2145
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
 
2146
            test_suite_factory=factory)
 
2147
        test = ProtocolTestCase(stream)
 
2148
        result = testtools.TestResult()
 
2149
        test.run(result)
 
2150
        content = stream.getvalue()
 
2151
        return content, result
 
2152
 
 
2153
    def test_fail_has_log(self):
 
2154
        content, result = self.run_subunit_stream('test_fail')
 
2155
        self.assertEqual(1, len(result.failures))
 
2156
        self.assertContainsRe(content, '(?m)^log$')
 
2157
        self.assertContainsRe(content, 'this test will fail')
 
2158
 
 
2159
    def test_error_has_log(self):
 
2160
        content, result = self.run_subunit_stream('test_error')
 
2161
        self.assertContainsRe(content, '(?m)^log$')
 
2162
        self.assertContainsRe(content, 'this test errored')
 
2163
 
 
2164
    def test_skip_has_no_log(self):
 
2165
        content, result = self.run_subunit_stream('test_skip')
 
2166
        self.assertNotContainsRe(content, '(?m)^log$')
 
2167
        self.assertNotContainsRe(content, 'this test will be skipped')
 
2168
        self.assertEqual(['reason'], result.skip_reasons.keys())
 
2169
        skips = result.skip_reasons['reason']
 
2170
        self.assertEqual(1, len(skips))
 
2171
        test = skips[0]
 
2172
        # RemotedTestCase doesn't preserve the "details"
 
2173
        ## self.assertFalse('log' in test.getDetails())
 
2174
 
 
2175
    def test_missing_feature_has_no_log(self):
 
2176
        content, result = self.run_subunit_stream('test_missing_feature')
 
2177
        self.assertNotContainsRe(content, '(?m)^log$')
 
2178
        self.assertNotContainsRe(content, 'missing the feature')
 
2179
        self.assertEqual(['_MissingFeature\n'], result.skip_reasons.keys())
 
2180
        skips = result.skip_reasons['_MissingFeature\n']
 
2181
        self.assertEqual(1, len(skips))
 
2182
        test = skips[0]
 
2183
        # RemotedTestCase doesn't preserve the "details"
 
2184
        ## self.assertFalse('log' in test.getDetails())
 
2185
 
 
2186
    def test_xfail_has_no_log(self):
 
2187
        content, result = self.run_subunit_stream('test_xfail')
 
2188
        self.assertNotContainsRe(content, '(?m)^log$')
 
2189
        self.assertNotContainsRe(content, 'test with expected failure')
 
2190
        self.assertEqual(1, len(result.expectedFailures))
 
2191
        result_content = result.expectedFailures[0][1]
 
2192
        self.assertNotContainsRe(result_content, 'Text attachment: log')
 
2193
        self.assertNotContainsRe(result_content, 'test with expected failure')
 
2194
 
 
2195
    def test_unexpected_success_has_log(self):
 
2196
        content, result = self.run_subunit_stream('test_unexpected_success')
 
2197
        self.assertContainsRe(content, '(?m)^log$')
 
2198
        self.assertContainsRe(content, 'test with unexpected success')
 
2199
        # GZ 2011-05-18: Old versions of subunit treat unexpected success as a
 
2200
        #                success, if a min version check is added remove this
 
2201
        from subunit import TestProtocolClient as _Client
 
2202
        if _Client.addUnexpectedSuccess.im_func is _Client.addSuccess.im_func:
 
2203
            self.expectFailure('subunit treats "unexpectedSuccess"'
 
2204
                               ' as a plain success',
 
2205
                self.assertEqual, 1, len(result.unexpectedSuccesses))
 
2206
        self.assertEqual(1, len(result.unexpectedSuccesses))
 
2207
        test = result.unexpectedSuccesses[0]
 
2208
        # RemotedTestCase doesn't preserve the "details"
 
2209
        ## self.assertTrue('log' in test.getDetails())
 
2210
 
 
2211
    def test_success_has_no_log(self):
 
2212
        content, result = self.run_subunit_stream('test_success')
 
2213
        self.assertEqual(1, result.testsRun)
 
2214
        self.assertNotContainsRe(content, '(?m)^log$')
 
2215
        self.assertNotContainsRe(content, 'this test succeeds')
 
2216
 
 
2217
 
1974
2218
class TestRunBzr(tests.TestCase):
1975
2219
 
1976
2220
    out = ''
2099
2343
        # stdout and stderr of the invoked run_bzr
2100
2344
        current_factory = bzrlib.ui.ui_factory
2101
2345
        self.run_bzr(['foo'])
2102
 
        self.failIf(current_factory is self.factory)
 
2346
        self.assertFalse(current_factory is self.factory)
2103
2347
        self.assertNotEqual(sys.stdout, self.factory.stdout)
2104
2348
        self.assertNotEqual(sys.stderr, self.factory.stderr)
2105
2349
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
2287
2531
        self.assertEqual([], command[2:])
2288
2532
 
2289
2533
    def test_set_env(self):
2290
 
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2534
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2291
2535
        # set in the child
2292
2536
        def check_environment():
2293
2537
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2299
2543
 
2300
2544
    def test_run_bzr_subprocess_env_del(self):
2301
2545
        """run_bzr_subprocess can remove environment variables too."""
2302
 
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2546
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2303
2547
        def check_environment():
2304
2548
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2305
2549
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2311
2555
        del os.environ['EXISTANT_ENV_VAR']
2312
2556
 
2313
2557
    def test_env_del_missing(self):
2314
 
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
 
2558
        self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2315
2559
        def check_environment():
2316
2560
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2317
2561
        self.check_popen_state = check_environment
2339
2583
            os.chdir = orig_chdir
2340
2584
        self.assertEqual(['foo', 'current'], chdirs)
2341
2585
 
 
2586
    def test_get_bzr_path_with_cwd_bzrlib(self):
 
2587
        self.get_source_path = lambda: ""
 
2588
        self.overrideAttr(os.path, "isfile", lambda path: True)
 
2589
        self.assertEqual(self.get_bzr_path(), "bzr")
 
2590
 
2342
2591
 
2343
2592
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2344
2593
    """Tests that really need to do things with an external bzr."""
2587
2836
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2588
2837
 
2589
2838
 
2590
 
class TestCheckInventoryShape(tests.TestCaseWithTransport):
 
2839
class TestCheckTreeShape(tests.TestCaseWithTransport):
2591
2840
 
2592
 
    def test_check_inventory_shape(self):
 
2841
    def test_check_tree_shape(self):
2593
2842
        files = ['a', 'b/', 'b/c']
2594
2843
        tree = self.make_branch_and_tree('.')
2595
2844
        self.build_tree(files)
2596
2845
        tree.add(files)
2597
2846
        tree.lock_read()
2598
2847
        try:
2599
 
            self.check_inventory_shape(tree.inventory, files)
 
2848
            self.check_tree_shape(tree, files)
2600
2849
        finally:
2601
2850
            tree.unlock()
2602
2851
 
2934
3183
        tpr.register('bar', 'bBB.aAA.rRR')
2935
3184
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2936
3185
        self.assertThat(self.get_log(),
2937
 
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR", ELLIPSIS))
 
3186
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR",
 
3187
                           doctest.ELLIPSIS))
2938
3188
 
2939
3189
    def test_get_unknown_prefix(self):
2940
3190
        tpr = self._get_registry()
2960
3210
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2961
3211
 
2962
3212
 
 
3213
class TestThreadLeakDetection(tests.TestCase):
 
3214
    """Ensure when tests leak threads we detect and report it"""
 
3215
 
 
3216
    class LeakRecordingResult(tests.ExtendedTestResult):
 
3217
        def __init__(self):
 
3218
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
 
3219
            self.leaks = []
 
3220
        def _report_thread_leak(self, test, leaks, alive):
 
3221
            self.leaks.append((test, leaks))
 
3222
 
 
3223
    def test_testcase_without_addCleanups(self):
 
3224
        """Check old TestCase instances don't break with leak detection"""
 
3225
        class Test(unittest.TestCase):
 
3226
            def runTest(self):
 
3227
                pass
 
3228
        result = self.LeakRecordingResult()
 
3229
        test = Test()
 
3230
        result.startTestRun()
 
3231
        test.run(result)
 
3232
        result.stopTestRun()
 
3233
        self.assertEqual(result._tests_leaking_threads_count, 0)
 
3234
        self.assertEqual(result.leaks, [])
 
3235
        
 
3236
    def test_thread_leak(self):
 
3237
        """Ensure a thread that outlives the running of a test is reported
 
3238
 
 
3239
        Uses a thread that blocks on an event, and is started by the inner
 
3240
        test case. As the thread outlives the inner case's run, it should be
 
3241
        detected as a leak, but the event is then set so that the thread can
 
3242
        be safely joined in cleanup so it's not leaked for real.
 
3243
        """
 
3244
        event = threading.Event()
 
3245
        thread = threading.Thread(name="Leaker", target=event.wait)
 
3246
        class Test(tests.TestCase):
 
3247
            def test_leak(self):
 
3248
                thread.start()
 
3249
        result = self.LeakRecordingResult()
 
3250
        test = Test("test_leak")
 
3251
        self.addCleanup(thread.join)
 
3252
        self.addCleanup(event.set)
 
3253
        result.startTestRun()
 
3254
        test.run(result)
 
3255
        result.stopTestRun()
 
3256
        self.assertEqual(result._tests_leaking_threads_count, 1)
 
3257
        self.assertEqual(result._first_thread_leaker_id, test.id())
 
3258
        self.assertEqual(result.leaks, [(test, set([thread]))])
 
3259
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
 
3260
 
 
3261
    def test_multiple_leaks(self):
 
3262
        """Check multiple leaks are blamed on the test cases at fault
 
3263
 
 
3264
        Same concept as the previous test, but has one inner test method that
 
3265
        leaks two threads, and one that doesn't leak at all.
 
3266
        """
 
3267
        event = threading.Event()
 
3268
        thread_a = threading.Thread(name="LeakerA", target=event.wait)
 
3269
        thread_b = threading.Thread(name="LeakerB", target=event.wait)
 
3270
        thread_c = threading.Thread(name="LeakerC", target=event.wait)
 
3271
        class Test(tests.TestCase):
 
3272
            def test_first_leak(self):
 
3273
                thread_b.start()
 
3274
            def test_second_no_leak(self):
 
3275
                pass
 
3276
            def test_third_leak(self):
 
3277
                thread_c.start()
 
3278
                thread_a.start()
 
3279
        result = self.LeakRecordingResult()
 
3280
        first_test = Test("test_first_leak")
 
3281
        third_test = Test("test_third_leak")
 
3282
        self.addCleanup(thread_a.join)
 
3283
        self.addCleanup(thread_b.join)
 
3284
        self.addCleanup(thread_c.join)
 
3285
        self.addCleanup(event.set)
 
3286
        result.startTestRun()
 
3287
        unittest.TestSuite(
 
3288
            [first_test, Test("test_second_no_leak"), third_test]
 
3289
            ).run(result)
 
3290
        result.stopTestRun()
 
3291
        self.assertEqual(result._tests_leaking_threads_count, 2)
 
3292
        self.assertEqual(result._first_thread_leaker_id, first_test.id())
 
3293
        self.assertEqual(result.leaks, [
 
3294
            (first_test, set([thread_b])),
 
3295
            (third_test, set([thread_a, thread_c]))])
 
3296
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
 
3297
 
 
3298
 
 
3299
class TestPostMortemDebugging(tests.TestCase):
 
3300
    """Check post mortem debugging works when tests fail or error"""
 
3301
 
 
3302
    class TracebackRecordingResult(tests.ExtendedTestResult):
 
3303
        def __init__(self):
 
3304
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
 
3305
            self.postcode = None
 
3306
        def _post_mortem(self, tb=None):
 
3307
            """Record the code object at the end of the current traceback"""
 
3308
            tb = tb or sys.exc_info()[2]
 
3309
            if tb is not None:
 
3310
                next = tb.tb_next
 
3311
                while next is not None:
 
3312
                    tb = next
 
3313
                    next = next.tb_next
 
3314
                self.postcode = tb.tb_frame.f_code
 
3315
        def report_error(self, test, err):
 
3316
            pass
 
3317
        def report_failure(self, test, err):
 
3318
            pass
 
3319
 
 
3320
    def test_location_unittest_error(self):
 
3321
        """Needs right post mortem traceback with erroring unittest case"""
 
3322
        class Test(unittest.TestCase):
 
3323
            def runTest(self):
 
3324
                raise RuntimeError
 
3325
        result = self.TracebackRecordingResult()
 
3326
        Test().run(result)
 
3327
        self.assertEqual(result.postcode, Test.runTest.func_code)
 
3328
 
 
3329
    def test_location_unittest_failure(self):
 
3330
        """Needs right post mortem traceback with failing unittest case"""
 
3331
        class Test(unittest.TestCase):
 
3332
            def runTest(self):
 
3333
                raise self.failureException
 
3334
        result = self.TracebackRecordingResult()
 
3335
        Test().run(result)
 
3336
        self.assertEqual(result.postcode, Test.runTest.func_code)
 
3337
 
 
3338
    def test_location_bt_error(self):
 
3339
        """Needs right post mortem traceback with erroring bzrlib.tests case"""
 
3340
        class Test(tests.TestCase):
 
3341
            def test_error(self):
 
3342
                raise RuntimeError
 
3343
        result = self.TracebackRecordingResult()
 
3344
        Test("test_error").run(result)
 
3345
        self.assertEqual(result.postcode, Test.test_error.func_code)
 
3346
 
 
3347
    def test_location_bt_failure(self):
 
3348
        """Needs right post mortem traceback with failing bzrlib.tests case"""
 
3349
        class Test(tests.TestCase):
 
3350
            def test_failure(self):
 
3351
                raise self.failureException
 
3352
        result = self.TracebackRecordingResult()
 
3353
        Test("test_failure").run(result)
 
3354
        self.assertEqual(result.postcode, Test.test_failure.func_code)
 
3355
 
 
3356
    def test_env_var_triggers_post_mortem(self):
 
3357
        """Check pdb.post_mortem is called iff BZR_TEST_PDB is set"""
 
3358
        import pdb
 
3359
        result = tests.ExtendedTestResult(StringIO(), 0, 1)
 
3360
        post_mortem_calls = []
 
3361
        self.overrideAttr(pdb, "post_mortem", post_mortem_calls.append)
 
3362
        self.overrideEnv('BZR_TEST_PDB', None)
 
3363
        result._post_mortem(1)
 
3364
        self.overrideEnv('BZR_TEST_PDB', 'on')
 
3365
        result._post_mortem(2)
 
3366
        self.assertEqual([2], post_mortem_calls)
 
3367
 
 
3368
 
2963
3369
class TestRunSuite(tests.TestCase):
2964
3370
 
2965
3371
    def test_runner_class(self):
2976
3382
                                                self.verbosity)
2977
3383
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2978
3384
        self.assertLength(1, calls)
 
3385
 
 
3386
 
 
3387
class TestEnvironHandling(tests.TestCase):
 
3388
 
 
3389
    def test_overrideEnv_None_called_twice_doesnt_leak(self):
 
3390
        self.assertFalse('MYVAR' in os.environ)
 
3391
        self.overrideEnv('MYVAR', '42')
 
3392
        # We use an embedded test to make sure we fix the _captureVar bug
 
3393
        class Test(tests.TestCase):
 
3394
            def test_me(self):
 
3395
                # The first call save the 42 value
 
3396
                self.overrideEnv('MYVAR', None)
 
3397
                self.assertEquals(None, os.environ.get('MYVAR'))
 
3398
                # Make sure we can call it twice
 
3399
                self.overrideEnv('MYVAR', None)
 
3400
                self.assertEquals(None, os.environ.get('MYVAR'))
 
3401
        output = StringIO()
 
3402
        result = tests.TextTestResult(output, 0, 1)
 
3403
        Test('test_me').run(result)
 
3404
        if not result.wasStrictlySuccessful():
 
3405
            self.fail(output.getvalue())
 
3406
        # We get our value back
 
3407
        self.assertEquals('42', os.environ.get('MYVAR'))
 
3408
 
 
3409
 
 
3410
class TestIsolatedEnv(tests.TestCase):
 
3411
    """Test isolating tests from os.environ.
 
3412
 
 
3413
    Since we use tests that are already isolated from os.environ a bit of care
 
3414
    should be taken when designing the tests to avoid bootstrap side-effects.
 
3415
    The tests start an already clean os.environ which allow doing valid
 
3416
    assertions about which variables are present or not and design tests around
 
3417
    these assertions.
 
3418
    """
 
3419
 
 
3420
    class ScratchMonkey(tests.TestCase):
 
3421
 
 
3422
        def test_me(self):
 
3423
            pass
 
3424
 
 
3425
    def test_basics(self):
 
3426
        # Make sure we know the definition of BZR_HOME: not part of os.environ
 
3427
        # for tests.TestCase.
 
3428
        self.assertTrue('BZR_HOME' in tests.isolated_environ)
 
3429
        self.assertEquals(None, tests.isolated_environ['BZR_HOME'])
 
3430
        # Being part of isolated_environ, BZR_HOME should not appear here
 
3431
        self.assertFalse('BZR_HOME' in os.environ)
 
3432
        # Make sure we know the definition of LINES: part of os.environ for
 
3433
        # tests.TestCase
 
3434
        self.assertTrue('LINES' in tests.isolated_environ)
 
3435
        self.assertEquals('25', tests.isolated_environ['LINES'])
 
3436
        self.assertEquals('25', os.environ['LINES'])
 
3437
 
 
3438
    def test_injecting_unknown_variable(self):
 
3439
        # BZR_HOME is known to be absent from os.environ
 
3440
        test = self.ScratchMonkey('test_me')
 
3441
        tests.override_os_environ(test, {'BZR_HOME': 'foo'})
 
3442
        self.assertEquals('foo', os.environ['BZR_HOME'])
 
3443
        tests.restore_os_environ(test)
 
3444
        self.assertFalse('BZR_HOME' in os.environ)
 
3445
 
 
3446
    def test_injecting_known_variable(self):
 
3447
        test = self.ScratchMonkey('test_me')
 
3448
        # LINES is known to be present in os.environ
 
3449
        tests.override_os_environ(test, {'LINES': '42'})
 
3450
        self.assertEquals('42', os.environ['LINES'])
 
3451
        tests.restore_os_environ(test)
 
3452
        self.assertEquals('25', os.environ['LINES'])
 
3453
 
 
3454
    def test_deleting_variable(self):
 
3455
        test = self.ScratchMonkey('test_me')
 
3456
        # LINES is known to be present in os.environ
 
3457
        tests.override_os_environ(test, {'LINES': None})
 
3458
        self.assertTrue('LINES' not in os.environ)
 
3459
        tests.restore_os_environ(test)
 
3460
        self.assertEquals('25', os.environ['LINES'])
 
3461
 
 
3462
 
 
3463
class TestDocTestSuiteIsolation(tests.TestCase):
 
3464
    """Test that `tests.DocTestSuite` isolates doc tests from os.environ.
 
3465
 
 
3466
    Since tests.TestCase alreay provides an isolation from os.environ, we use
 
3467
    the clean environment as a base for testing. To precisely capture the
 
3468
    isolation provided by tests.DocTestSuite, we use doctest.DocTestSuite to
 
3469
    compare against.
 
3470
 
 
3471
    We want to make sure `tests.DocTestSuite` respect `tests.isolated_environ`,
 
3472
    not `os.environ` so each test overrides it to suit its needs.
 
3473
 
 
3474
    """
 
3475
 
 
3476
    def get_doctest_suite_for_string(self, klass, string):
 
3477
        class Finder(doctest.DocTestFinder):
 
3478
 
 
3479
            def find(*args, **kwargs):
 
3480
                test = doctest.DocTestParser().get_doctest(
 
3481
                    string, {}, 'foo', 'foo.py', 0)
 
3482
                return [test]
 
3483
 
 
3484
        suite = klass(test_finder=Finder())
 
3485
        return suite
 
3486
 
 
3487
    def run_doctest_suite_for_string(self, klass, string):
 
3488
        suite = self.get_doctest_suite_for_string(klass, string)
 
3489
        output = StringIO()
 
3490
        result = tests.TextTestResult(output, 0, 1)
 
3491
        suite.run(result)
 
3492
        return result, output
 
3493
 
 
3494
    def assertDocTestStringSucceds(self, klass, string):
 
3495
        result, output = self.run_doctest_suite_for_string(klass, string)
 
3496
        if not result.wasStrictlySuccessful():
 
3497
            self.fail(output.getvalue())
 
3498
 
 
3499
    def assertDocTestStringFails(self, klass, string):
 
3500
        result, output = self.run_doctest_suite_for_string(klass, string)
 
3501
        if result.wasStrictlySuccessful():
 
3502
            self.fail(output.getvalue())
 
3503
 
 
3504
    def test_injected_variable(self):
 
3505
        self.overrideAttr(tests, 'isolated_environ', {'LINES': '42'})
 
3506
        test = """
 
3507
            >>> import os
 
3508
            >>> os.environ['LINES']
 
3509
            '42'
 
3510
            """
 
3511
        # doctest.DocTestSuite fails as it sees '25'
 
3512
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
 
3513
        # tests.DocTestSuite sees '42'
 
3514
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
 
3515
 
 
3516
    def test_deleted_variable(self):
 
3517
        self.overrideAttr(tests, 'isolated_environ', {'LINES': None})
 
3518
        test = """
 
3519
            >>> import os
 
3520
            >>> os.environ.get('LINES')
 
3521
            """
 
3522
        # doctest.DocTestSuite fails as it sees '25'
 
3523
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
 
3524
        # tests.DocTestSuite sees None
 
3525
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
 
3526
 
 
3527
 
 
3528
class TestSelftestExcludePatterns(tests.TestCase):
 
3529
 
 
3530
    def setUp(self):
 
3531
        super(TestSelftestExcludePatterns, self).setUp()
 
3532
        self.overrideAttr(tests, 'test_suite', self.suite_factory)
 
3533
 
 
3534
    def suite_factory(self, keep_only=None, starting_with=None):
 
3535
        """A test suite factory with only a few tests."""
 
3536
        class Test(tests.TestCase):
 
3537
            def id(self):
 
3538
                # We don't need the full class path
 
3539
                return self._testMethodName
 
3540
            def a(self):
 
3541
                pass
 
3542
            def b(self):
 
3543
                pass
 
3544
            def c(self):
 
3545
                pass
 
3546
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
 
3547
 
 
3548
    def assertTestList(self, expected, *selftest_args):
 
3549
        # We rely on setUp installing the right test suite factory so we can
 
3550
        # test at the command level without loading the whole test suite
 
3551
        out, err = self.run_bzr(('selftest', '--list') + selftest_args)
 
3552
        actual = out.splitlines()
 
3553
        self.assertEquals(expected, actual)
 
3554
 
 
3555
    def test_full_list(self):
 
3556
        self.assertTestList(['a', 'b', 'c'])
 
3557
 
 
3558
    def test_single_exclude(self):
 
3559
        self.assertTestList(['b', 'c'], '-x', 'a')
 
3560
 
 
3561
    def test_mutiple_excludes(self):
 
3562
        self.assertTestList(['c'], '-x', 'a', '-x', 'b')
 
3563
 
 
3564
 
 
3565
class TestCounterHooks(tests.TestCase, SelfTestHelper):
 
3566
 
 
3567
    _test_needs_features = [features.subunit]
 
3568
 
 
3569
    def setUp(self):
 
3570
        super(TestCounterHooks, self).setUp()
 
3571
        class Test(tests.TestCase):
 
3572
 
 
3573
            def setUp(self):
 
3574
                super(Test, self).setUp()
 
3575
                self.hooks = hooks.Hooks()
 
3576
                self.hooks.add_hook('myhook', 'Foo bar blah', (2,4))
 
3577
                self.install_counter_hook(self.hooks, 'myhook')
 
3578
 
 
3579
            def no_hook(self):
 
3580
                pass
 
3581
 
 
3582
            def run_hook_once(self):
 
3583
                for hook in self.hooks['myhook']:
 
3584
                    hook(self)
 
3585
        self.test_class = Test
 
3586
 
 
3587
    def assertHookCalls(self, expected_calls, test_name):
 
3588
        test = self.test_class(test_name)
 
3589
        result = unittest.TestResult()
 
3590
        test.run(result)
 
3591
        self.assertTrue(hasattr(test, '_counters'))
 
3592
        self.assertTrue(test._counters.has_key('myhook'))
 
3593
        self.assertEquals(expected_calls, test._counters['myhook'])
 
3594
 
 
3595
    def test_no_hook(self):
 
3596
        self.assertHookCalls(0, 'no_hook')
 
3597
 
 
3598
    def test_run_hook_once(self):
 
3599
        self.assertHookCalls(1, 'run_hook_once')