~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Patch Queue Manager
  • Date: 2016-01-31 13:36:59 UTC
  • mfrom: (6613.1.5 1538480-match-hostname)
  • Revision ID: pqm@pqm.ubuntu.com-20160131133659-ouy92ee2wlv9xz8m
(vila) Use ssl.match_hostname instead of our own. (Vincent Ladeuil)

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 gc
 
21
import doctest
21
22
import os
22
23
import signal
23
24
import sys
 
25
import threading
24
26
import time
25
27
import unittest
26
28
import warnings
27
29
 
28
 
from testtools import MultiTestResult
 
30
from testtools import (
 
31
    ExtendedToOriginalDecorator,
 
32
    MultiTestResult,
 
33
    )
 
34
from testtools.content import Content
29
35
from testtools.content_type import ContentType
30
36
from testtools.matchers import (
31
37
    DocTestMatches,
32
38
    Equals,
33
39
    )
34
 
import testtools.tests.helpers
 
40
import testtools.testresult.doubles
35
41
 
36
42
import bzrlib
37
43
from bzrlib import (
38
44
    branchbuilder,
39
45
    bzrdir,
40
 
    debug,
 
46
    controldir,
41
47
    errors,
 
48
    hooks,
42
49
    lockdir,
43
50
    memorytree,
44
51
    osutils,
45
 
    progress,
46
52
    remote,
47
53
    repository,
48
54
    symbol_versioning,
49
55
    tests,
50
56
    transport,
51
57
    workingtree,
 
58
    workingtree_3,
 
59
    workingtree_4,
52
60
    )
53
61
from bzrlib.repofmt import (
54
62
    groupcompress_repo,
55
 
    pack_repo,
56
 
    weaverepo,
57
63
    )
58
64
from bzrlib.symbol_versioning import (
59
65
    deprecated_function,
64
70
    features,
65
71
    test_lsprof,
66
72
    test_server,
67
 
    test_sftp_transport,
68
73
    TestUtil,
69
74
    )
70
 
from bzrlib.trace import note
 
75
from bzrlib.trace import note, mutter
71
76
from bzrlib.transport import memory
72
 
from bzrlib.version import _get_bzr_source_tree
73
77
 
74
78
 
75
79
def _test_ids(test_suite):
77
81
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
78
82
 
79
83
 
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
84
class MetaTestLog(tests.TestCase):
93
85
 
94
86
    def test_logging(self):
100
92
            "text", "plain", {"charset": "utf8"})))
101
93
        self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
102
94
        self.assertThat(self.get_log(),
103
 
            DocTestMatches(u"...a test message\n", ELLIPSIS))
104
 
 
105
 
 
106
 
class TestUnicodeFilename(tests.TestCase):
107
 
 
108
 
    def test_probe_passes(self):
109
 
        """UnicodeFilename._probe passes."""
110
 
        # We can't test much more than that because the behaviour depends
111
 
        # on the platform.
112
 
        tests.UnicodeFilename._probe()
 
95
            DocTestMatches(u"...a test message\n", doctest.ELLIPSIS))
113
96
 
114
97
 
115
98
class TestTreeShape(tests.TestCaseInTempDir):
116
99
 
117
100
    def test_unicode_paths(self):
118
 
        self.requireFeature(tests.UnicodeFilename)
 
101
        self.requireFeature(features.UnicodeFilenameFeature)
119
102
 
120
103
        filename = u'hell\u00d8'
121
104
        self.build_tree_contents([(filename, 'contents of hello')])
122
 
        self.failUnlessExists(filename)
 
105
        self.assertPathExists(filename)
123
106
 
124
107
 
125
108
class TestClassesAvailable(tests.TestCase):
325
308
        from bzrlib.tests.per_interrepository import make_scenarios
326
309
        server1 = "a"
327
310
        server2 = "b"
328
 
        formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
 
311
        formats = [("C0", "C1", "C2", "C3"), ("D0", "D1", "D2", "D3")]
329
312
        scenarios = make_scenarios(server1, server2, formats)
330
313
        self.assertEqual([
331
314
            ('C0,str,str',
332
315
             {'repository_format': 'C1',
333
316
              'repository_format_to': 'C2',
334
317
              'transport_readonly_server': 'b',
335
 
              'transport_server': 'a'}),
 
318
              'transport_server': 'a',
 
319
              'extra_setup': 'C3'}),
336
320
            ('D0,str,str',
337
321
             {'repository_format': 'D1',
338
322
              'repository_format_to': 'D2',
339
323
              'transport_readonly_server': 'b',
340
 
              'transport_server': 'a'})],
 
324
              'transport_server': 'a',
 
325
              'extra_setup': 'D3'})],
341
326
            scenarios)
342
327
 
343
328
 
349
334
        from bzrlib.tests.per_workingtree import make_scenarios
350
335
        server1 = "a"
351
336
        server2 = "b"
352
 
        formats = [workingtree.WorkingTreeFormat2(),
353
 
                   workingtree.WorkingTreeFormat3(),]
354
 
        scenarios = make_scenarios(server1, server2, formats)
 
337
        formats = [workingtree_4.WorkingTreeFormat4(),
 
338
                   workingtree_3.WorkingTreeFormat3(),
 
339
                   workingtree_4.WorkingTreeFormat6()]
 
340
        scenarios = make_scenarios(server1, server2, formats,
 
341
            remote_server='c', remote_readonly_server='d',
 
342
            remote_backing_server='e')
355
343
        self.assertEqual([
356
 
            ('WorkingTreeFormat2',
 
344
            ('WorkingTreeFormat4',
357
345
             {'bzrdir_format': formats[0]._matchingbzrdir,
358
346
              'transport_readonly_server': 'b',
359
347
              'transport_server': 'a',
362
350
             {'bzrdir_format': formats[1]._matchingbzrdir,
363
351
              'transport_readonly_server': 'b',
364
352
              'transport_server': 'a',
365
 
              'workingtree_format': formats[1]})],
366
 
            scenarios)
 
353
              'workingtree_format': formats[1]}),
 
354
            ('WorkingTreeFormat6',
 
355
             {'bzrdir_format': formats[2]._matchingbzrdir,
 
356
              'transport_readonly_server': 'b',
 
357
              'transport_server': 'a',
 
358
              'workingtree_format': formats[2]}),
 
359
            ('WorkingTreeFormat6,remote',
 
360
             {'bzrdir_format': formats[2]._matchingbzrdir,
 
361
              'repo_is_remote': True,
 
362
              'transport_readonly_server': 'd',
 
363
              'transport_server': 'c',
 
364
              'vfs_transport_factory': 'e',
 
365
              'workingtree_format': formats[2]}),
 
366
            ], scenarios)
367
367
 
368
368
 
369
369
class TestTreeScenarios(tests.TestCase):
370
370
 
371
371
    def test_scenarios(self):
372
372
        # the tree implementation scenario generator is meant to setup one
373
 
        # instance for each working tree format, and one additional instance
 
373
        # instance for each working tree format, one additional instance
374
374
        # that will use the default wt format, but create a revision tree for
375
 
        # the tests.  this means that the wt ones should have the
376
 
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
377
 
        # revision one set to revision_tree_from_workingtree.
 
375
        # the tests, and one more that uses the default wt format as a
 
376
        # lightweight checkout of a remote repository.  This means that the wt
 
377
        # ones should have the workingtree_to_test_tree attribute set to
 
378
        # 'return_parameter' and the revision one set to
 
379
        # revision_tree_from_workingtree.
378
380
 
379
381
        from bzrlib.tests.per_tree import (
380
382
            _dirstate_tree_from_workingtree,
386
388
            )
387
389
        server1 = "a"
388
390
        server2 = "b"
389
 
        formats = [workingtree.WorkingTreeFormat2(),
390
 
                   workingtree.WorkingTreeFormat3(),]
 
391
        smart_server = test_server.SmartTCPServer_for_testing
 
392
        smart_readonly_server = test_server.ReadonlySmartTCPServer_for_testing
 
393
        mem_server = memory.MemoryServer
 
394
        formats = [workingtree_4.WorkingTreeFormat4(),
 
395
                   workingtree_3.WorkingTreeFormat3(),]
391
396
        scenarios = make_scenarios(server1, server2, formats)
392
 
        self.assertEqual(7, len(scenarios))
393
 
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
394
 
        wt4_format = workingtree.WorkingTreeFormat4()
395
 
        wt5_format = workingtree.WorkingTreeFormat5()
 
397
        self.assertEqual(8, len(scenarios))
 
398
        default_wt_format = workingtree.format_registry.get_default()
 
399
        wt4_format = workingtree_4.WorkingTreeFormat4()
 
400
        wt5_format = workingtree_4.WorkingTreeFormat5()
 
401
        wt6_format = workingtree_4.WorkingTreeFormat6()
396
402
        expected_scenarios = [
397
 
            ('WorkingTreeFormat2',
 
403
            ('WorkingTreeFormat4',
398
404
             {'bzrdir_format': formats[0]._matchingbzrdir,
399
405
              'transport_readonly_server': 'b',
400
406
              'transport_server': 'a',
408
414
              'workingtree_format': formats[1],
409
415
              '_workingtree_to_test_tree': return_parameter,
410
416
             }),
 
417
            ('WorkingTreeFormat6,remote',
 
418
             {'bzrdir_format': wt6_format._matchingbzrdir,
 
419
              'repo_is_remote': True,
 
420
              'transport_readonly_server': smart_readonly_server,
 
421
              'transport_server': smart_server,
 
422
              'vfs_transport_factory': mem_server,
 
423
              'workingtree_format': wt6_format,
 
424
              '_workingtree_to_test_tree': return_parameter,
 
425
             }),
411
426
            ('RevisionTree',
412
427
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
413
428
              'bzrdir_format': default_wt_format._matchingbzrdir,
460
475
        # ones to add.
461
476
        from bzrlib.tests.per_tree import (
462
477
            return_parameter,
463
 
            revision_tree_from_workingtree
464
478
            )
465
479
        from bzrlib.tests.per_intertree import (
466
480
            make_scenarios,
467
481
            )
468
 
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
 
482
        from bzrlib.workingtree_3 import WorkingTreeFormat3
 
483
        from bzrlib.workingtree_4 import WorkingTreeFormat4
469
484
        input_test = TestInterTreeScenarios(
470
485
            "test_scenarios")
471
486
        server1 = "a"
472
487
        server2 = "b"
473
 
        format1 = WorkingTreeFormat2()
 
488
        format1 = WorkingTreeFormat4()
474
489
        format2 = WorkingTreeFormat3()
475
490
        formats = [("1", str, format1, format2, "converter1"),
476
491
            ("2", int, format2, format1, "converter2")]
522
537
        self.assertRaises(AssertionError, self.assertEqualStat,
523
538
            os.lstat("foo"), os.lstat("longname"))
524
539
 
 
540
    def test_failUnlessExists(self):
 
541
        """Deprecated failUnlessExists and failIfExists"""
 
542
        self.applyDeprecated(
 
543
            deprecated_in((2, 4)),
 
544
            self.failUnlessExists, '.')
 
545
        self.build_tree(['foo/', 'foo/bar'])
 
546
        self.applyDeprecated(
 
547
            deprecated_in((2, 4)),
 
548
            self.failUnlessExists, 'foo/bar')
 
549
        self.applyDeprecated(
 
550
            deprecated_in((2, 4)),
 
551
            self.failIfExists, 'foo/foo')
 
552
 
 
553
    def test_assertPathExists(self):
 
554
        self.assertPathExists('.')
 
555
        self.build_tree(['foo/', 'foo/bar'])
 
556
        self.assertPathExists('foo/bar')
 
557
        self.assertPathDoesNotExist('foo/foo')
 
558
 
525
559
 
526
560
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
527
561
 
561
595
        tree = self.make_branch_and_memory_tree('dir')
562
596
        # Guard against regression into MemoryTransport leaking
563
597
        # files to disk instead of keeping them in memory.
564
 
        self.failIf(osutils.lexists('dir'))
 
598
        self.assertFalse(osutils.lexists('dir'))
565
599
        self.assertIsInstance(tree, memorytree.MemoryTree)
566
600
 
567
601
    def test_make_branch_and_memory_tree_with_format(self):
568
602
        """make_branch_and_memory_tree should accept a format option."""
569
603
        format = bzrdir.BzrDirMetaFormat1()
570
 
        format.repository_format = weaverepo.RepositoryFormat7()
 
604
        format.repository_format = repository.format_registry.get_default()
571
605
        tree = self.make_branch_and_memory_tree('dir', format=format)
572
606
        # Guard against regression into MemoryTransport leaking
573
607
        # files to disk instead of keeping them in memory.
574
 
        self.failIf(osutils.lexists('dir'))
 
608
        self.assertFalse(osutils.lexists('dir'))
575
609
        self.assertIsInstance(tree, memorytree.MemoryTree)
576
610
        self.assertEqual(format.repository_format.__class__,
577
611
            tree.branch.repository._format.__class__)
581
615
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
582
616
        # Guard against regression into MemoryTransport leaking
583
617
        # files to disk instead of keeping them in memory.
584
 
        self.failIf(osutils.lexists('dir'))
 
618
        self.assertFalse(osutils.lexists('dir'))
585
619
 
586
620
    def test_make_branch_builder_with_format(self):
587
621
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
588
622
        # that the format objects are used.
589
623
        format = bzrdir.BzrDirMetaFormat1()
590
 
        repo_format = weaverepo.RepositoryFormat7()
 
624
        repo_format = repository.format_registry.get_default()
591
625
        format.repository_format = repo_format
592
626
        builder = self.make_branch_builder('dir', format=format)
593
627
        the_branch = builder.get_branch()
594
628
        # Guard against regression into MemoryTransport leaking
595
629
        # files to disk instead of keeping them in memory.
596
 
        self.failIf(osutils.lexists('dir'))
 
630
        self.assertFalse(osutils.lexists('dir'))
597
631
        self.assertEqual(format.repository_format.__class__,
598
632
                         the_branch.repository._format.__class__)
599
633
        self.assertEqual(repo_format.get_format_string(),
605
639
        the_branch = builder.get_branch()
606
640
        # Guard against regression into MemoryTransport leaking
607
641
        # files to disk instead of keeping them in memory.
608
 
        self.failIf(osutils.lexists('dir'))
609
 
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
 
642
        self.assertFalse(osutils.lexists('dir'))
 
643
        dir_format = controldir.format_registry.make_bzrdir('knit')
610
644
        self.assertEqual(dir_format.repository_format.__class__,
611
645
                         the_branch.repository._format.__class__)
612
646
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
616
650
    def test_dangling_locks_cause_failures(self):
617
651
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
618
652
            def test_function(self):
619
 
                t = self.get_transport('.')
 
653
                t = self.get_transport_from_path('.')
620
654
                l = lockdir.LockDir(t, 'lock')
621
655
                l.create()
622
656
                l.attempt_lock()
624
658
        result = test.run()
625
659
        total_failures = result.errors + result.failures
626
660
        if self._lock_check_thorough:
627
 
            self.assertLength(1, total_failures)
 
661
            self.assertEqual(1, len(total_failures))
628
662
        else:
629
663
            # When _lock_check_thorough is disabled, then we don't trigger a
630
664
            # failure
631
 
            self.assertLength(0, total_failures)
 
665
            self.assertEqual(0, len(total_failures))
632
666
 
633
667
 
634
668
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
642
676
        # for the server
643
677
        url = self.get_readonly_url()
644
678
        url2 = self.get_readonly_url('foo/bar')
645
 
        t = transport.get_transport(url)
646
 
        t2 = transport.get_transport(url2)
647
 
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
648
 
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
 
679
        t = transport.get_transport_from_url(url)
 
680
        t2 = transport.get_transport_from_url(url2)
 
681
        self.assertIsInstance(t, ReadonlyTransportDecorator)
 
682
        self.assertIsInstance(t2, ReadonlyTransportDecorator)
649
683
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
650
684
 
651
685
    def test_get_readonly_url_http(self):
657
691
        url = self.get_readonly_url()
658
692
        url2 = self.get_readonly_url('foo/bar')
659
693
        # the transport returned may be any HttpTransportBase subclass
660
 
        t = transport.get_transport(url)
661
 
        t2 = transport.get_transport(url2)
662
 
        self.failUnless(isinstance(t, HttpTransportBase))
663
 
        self.failUnless(isinstance(t2, HttpTransportBase))
 
694
        t = transport.get_transport_from_url(url)
 
695
        t2 = transport.get_transport_from_url(url2)
 
696
        self.assertIsInstance(t, HttpTransportBase)
 
697
        self.assertIsInstance(t2, HttpTransportBase)
664
698
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
665
699
 
666
700
    def test_is_directory(self):
674
708
    def test_make_branch_builder(self):
675
709
        builder = self.make_branch_builder('dir')
676
710
        rev_id = builder.build_commit()
677
 
        self.failUnlessExists('dir')
678
 
        a_dir = bzrdir.BzrDir.open('dir')
 
711
        self.assertPathExists('dir')
 
712
        a_dir = controldir.ControlDir.open('dir')
679
713
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
680
714
        a_branch = a_dir.open_branch()
681
715
        builder_branch = builder.get_branch()
696
730
        self.assertIsInstance(result_bzrdir.transport,
697
731
                              memory.MemoryTransport)
698
732
        # should not be on disk, should only be in memory
699
 
        self.failIfExists('subdir')
 
733
        self.assertPathDoesNotExist('subdir')
700
734
 
701
735
 
702
736
class TestChrootedTest(tests.ChrootedTestCase):
703
737
 
704
738
    def test_root_is_root(self):
705
 
        t = transport.get_transport(self.get_readonly_url())
 
739
        t = transport.get_transport_from_url(self.get_readonly_url())
706
740
        url = t.base
707
741
        self.assertEqual(url, t.clone('..').base)
708
742
 
710
744
class TestProfileResult(tests.TestCase):
711
745
 
712
746
    def test_profiles_tests(self):
713
 
        self.requireFeature(test_lsprof.LSProfFeature)
714
 
        terminal = testtools.tests.helpers.ExtendedTestResult()
 
747
        self.requireFeature(features.lsprof_feature)
 
748
        terminal = testtools.testresult.doubles.ExtendedTestResult()
715
749
        result = tests.ProfileResult(terminal)
716
750
        class Sample(tests.TestCase):
717
751
            def a(self):
734
768
                descriptions=0,
735
769
                verbosity=1,
736
770
                )
737
 
        capture = testtools.tests.helpers.ExtendedTestResult()
 
771
        capture = testtools.testresult.doubles.ExtendedTestResult()
738
772
        test_case.run(MultiTestResult(result, capture))
739
773
        run_case = capture._events[0][1]
740
774
        timed_string = result._testTimeString(run_case)
761
795
        self.check_timing(ShortDelayTestCase('test_short_delay'),
762
796
                          r"^ +[0-9]+ms$")
763
797
 
764
 
    def _patch_get_bzr_source_tree(self):
765
 
        # Reading from the actual source tree breaks isolation, but we don't
766
 
        # want to assume that thats *all* that would happen.
767
 
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', lambda: None)
768
 
 
769
 
    def test_assigned_benchmark_file_stores_date(self):
770
 
        self._patch_get_bzr_source_tree()
771
 
        output = StringIO()
772
 
        result = bzrlib.tests.TextTestResult(self._log_file,
773
 
                                        descriptions=0,
774
 
                                        verbosity=1,
775
 
                                        bench_history=output
776
 
                                        )
777
 
        output_string = output.getvalue()
778
 
        # if you are wondering about the regexp please read the comment in
779
 
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
780
 
        # XXX: what comment?  -- Andrew Bennetts
781
 
        self.assertContainsRe(output_string, "--date [0-9.]+")
782
 
 
783
 
    def test_benchhistory_records_test_times(self):
784
 
        self._patch_get_bzr_source_tree()
785
 
        result_stream = StringIO()
786
 
        result = bzrlib.tests.TextTestResult(
787
 
            self._log_file,
788
 
            descriptions=0,
789
 
            verbosity=1,
790
 
            bench_history=result_stream
791
 
            )
792
 
 
793
 
        # we want profile a call and check that its test duration is recorded
794
 
        # make a new test instance that when run will generate a benchmark
795
 
        example_test_case = TestTestResult("_time_hello_world_encoding")
796
 
        # execute the test, which should succeed and record times
797
 
        example_test_case.run(result)
798
 
        lines = result_stream.getvalue().splitlines()
799
 
        self.assertEqual(2, len(lines))
800
 
        self.assertContainsRe(lines[1],
801
 
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
802
 
            "._time_hello_world_encoding")
803
 
 
804
798
    def _time_hello_world_encoding(self):
805
799
        """Profile two sleep calls
806
800
 
811
805
 
812
806
    def test_lsprofiling(self):
813
807
        """Verbose test result prints lsprof statistics from test cases."""
814
 
        self.requireFeature(test_lsprof.LSProfFeature)
 
808
        self.requireFeature(features.lsprof_feature)
815
809
        result_stream = StringIO()
816
810
        result = bzrlib.tests.VerboseTestResult(
817
811
            result_stream,
846
840
        self.assertContainsRe(output,
847
841
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
848
842
 
 
843
    def test_uses_time_from_testtools(self):
 
844
        """Test case timings in verbose results should use testtools times"""
 
845
        import datetime
 
846
        class TimeAddedVerboseTestResult(tests.VerboseTestResult):
 
847
            def startTest(self, test):
 
848
                self.time(datetime.datetime.utcfromtimestamp(1.145))
 
849
                super(TimeAddedVerboseTestResult, self).startTest(test)
 
850
            def addSuccess(self, test):
 
851
                self.time(datetime.datetime.utcfromtimestamp(51.147))
 
852
                super(TimeAddedVerboseTestResult, self).addSuccess(test)
 
853
            def report_tests_starting(self): pass
 
854
        sio = StringIO()
 
855
        self.get_passing_test().run(TimeAddedVerboseTestResult(sio, 0, 2))
 
856
        self.assertEndsWith(sio.getvalue(), "OK    50002ms\n")
 
857
 
849
858
    def test_known_failure(self):
850
 
        """A KnownFailure being raised should trigger several result actions."""
 
859
        """Using knownFailure should trigger several result actions."""
851
860
        class InstrumentedTestResult(tests.ExtendedTestResult):
852
861
            def stopTestRun(self): pass
853
 
            def startTests(self): pass
854
 
            def report_test_start(self, test): pass
 
862
            def report_tests_starting(self): pass
855
863
            def report_known_failure(self, test, err=None, details=None):
856
864
                self._call = test, 'known failure'
857
865
        result = InstrumentedTestResult(None, None, None, None)
858
866
        class Test(tests.TestCase):
859
867
            def test_function(self):
860
 
                raise tests.KnownFailure('failed!')
 
868
                self.knownFailure('failed!')
861
869
        test = Test("test_function")
862
870
        test.run(result)
863
871
        # it should invoke 'report_known_failure'.
879
887
            descriptions=0,
880
888
            verbosity=2,
881
889
            )
882
 
        test = self.get_passing_test()
883
 
        result.startTest(test)
884
 
        prefix = len(result_stream.getvalue())
885
 
        # the err parameter has the shape:
886
 
        # (class, exception object, traceback)
887
 
        # KnownFailures dont get their tracebacks shown though, so we
888
 
        # can skip that.
889
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
890
 
        result.report_known_failure(test, err)
891
 
        output = result_stream.getvalue()[prefix:]
892
 
        lines = output.splitlines()
893
 
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
894
 
        if sys.version_info > (2, 7):
895
 
            self.expectFailure("_ExpectedFailure on 2.7 loses the message",
896
 
                self.assertNotEqual, lines[1], '    ')
897
 
        self.assertEqual(lines[1], '    foo')
898
 
        self.assertEqual(2, len(lines))
 
890
        _get_test("test_xfail").run(result)
 
891
        self.assertContainsRe(result_stream.getvalue(),
 
892
            "\n\\S+\\.test_xfail\\s+XFAIL\\s+\\d+ms\n"
 
893
            "\\s*(?:Text attachment: )?reason"
 
894
            "(?:\n-+\n|: {{{)"
 
895
            "this_fails"
 
896
            "(?:\n-+\n|}}}\n)")
899
897
 
900
898
    def get_passing_test(self):
901
899
        """Return a test object that can't be run usefully."""
907
905
        """Test the behaviour of invoking addNotSupported."""
908
906
        class InstrumentedTestResult(tests.ExtendedTestResult):
909
907
            def stopTestRun(self): pass
910
 
            def startTests(self): pass
911
 
            def report_test_start(self, test): pass
 
908
            def report_tests_starting(self): pass
912
909
            def report_unsupported(self, test, feature):
913
910
                self._call = test, feature
914
911
        result = InstrumentedTestResult(None, None, None, None)
915
912
        test = SampleTestCase('_test_pass')
916
 
        feature = tests.Feature()
 
913
        feature = features.Feature()
917
914
        result.startTest(test)
918
915
        result.addNotSupported(test, feature)
919
916
        # it should invoke 'report_unsupported'.
938
935
            verbosity=2,
939
936
            )
940
937
        test = self.get_passing_test()
941
 
        feature = tests.Feature()
 
938
        feature = features.Feature()
942
939
        result.startTest(test)
943
940
        prefix = len(result_stream.getvalue())
944
941
        result.report_unsupported(test, feature)
953
950
        """An UnavailableFeature being raised should invoke addNotSupported."""
954
951
        class InstrumentedTestResult(tests.ExtendedTestResult):
955
952
            def stopTestRun(self): pass
956
 
            def startTests(self): pass
957
 
            def report_test_start(self, test): pass
 
953
            def report_tests_starting(self): pass
958
954
            def addNotSupported(self, test, feature):
959
955
                self._call = test, feature
960
956
        result = InstrumentedTestResult(None, None, None, None)
961
 
        feature = tests.Feature()
 
957
        feature = features.Feature()
962
958
        class Test(tests.TestCase):
963
959
            def test_function(self):
964
960
                raise tests.UnavailableFeature(feature)
983
979
    def test_strict_with_known_failure(self):
984
980
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
985
981
                                             verbosity=1)
986
 
        test = self.get_passing_test()
987
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
988
 
        result.addExpectedFailure(test, err)
 
982
        test = _get_test("test_xfail")
 
983
        test.run(result)
989
984
        self.assertFalse(result.wasStrictlySuccessful())
990
985
        self.assertEqual(None, result._extractBenchmarkTime(test))
991
986
 
1002
997
        class InstrumentedTestResult(tests.ExtendedTestResult):
1003
998
            calls = 0
1004
999
            def startTests(self): self.calls += 1
1005
 
            def report_test_start(self, test): pass
1006
1000
        result = InstrumentedTestResult(None, None, None, None)
1007
1001
        def test_function():
1008
1002
            pass
1010
1004
        test.run(result)
1011
1005
        self.assertEquals(1, result.calls)
1012
1006
 
1013
 
 
1014
 
class TestUnicodeFilenameFeature(tests.TestCase):
1015
 
 
1016
 
    def test_probe_passes(self):
1017
 
        """UnicodeFilenameFeature._probe passes."""
1018
 
        # We can't test much more than that because the behaviour depends
1019
 
        # on the platform.
1020
 
        tests.UnicodeFilenameFeature._probe()
 
1007
    def test_startTests_only_once(self):
 
1008
        """With multiple tests startTests should still only be called once"""
 
1009
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
1010
            calls = 0
 
1011
            def startTests(self): self.calls += 1
 
1012
        result = InstrumentedTestResult(None, None, None, None)
 
1013
        suite = unittest.TestSuite([
 
1014
            unittest.FunctionTestCase(lambda: None),
 
1015
            unittest.FunctionTestCase(lambda: None)])
 
1016
        suite.run(result)
 
1017
        self.assertEquals(1, result.calls)
 
1018
        self.assertEquals(2, result.count)
1021
1019
 
1022
1020
 
1023
1021
class TestRunner(tests.TestCase):
1036
1034
        because of our use of global state.
1037
1035
        """
1038
1036
        old_root = tests.TestCaseInTempDir.TEST_ROOT
1039
 
        old_leak = tests.TestCase._first_thread_leaker_id
1040
1037
        try:
1041
1038
            tests.TestCaseInTempDir.TEST_ROOT = None
1042
 
            tests.TestCase._first_thread_leaker_id = None
1043
1039
            return testrunner.run(test)
1044
1040
        finally:
1045
1041
            tests.TestCaseInTempDir.TEST_ROOT = old_root
1046
 
            tests.TestCase._first_thread_leaker_id = old_leak
1047
1042
 
1048
1043
    def test_known_failure_failed_run(self):
1049
1044
        # run a test that generates a known failure which should be printed in
1054
1049
        test = unittest.TestSuite()
1055
1050
        test.addTest(Test("known_failure_test"))
1056
1051
        def failing_test():
1057
 
            self.fail('foo')
 
1052
            raise AssertionError('foo')
1058
1053
        test.addTest(unittest.FunctionTestCase(failing_test))
1059
1054
        stream = StringIO()
1060
1055
        runner = tests.TextTestRunner(stream=stream)
1068
1063
            '^----------------------------------------------------------------------\n'
1069
1064
            'Traceback \\(most recent call last\\):\n'
1070
1065
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1071
 
            '    self.fail\\(\'foo\'\\)\n'
 
1066
            '    raise AssertionError\\(\'foo\'\\)\n'
1072
1067
            '.*'
1073
1068
            '^----------------------------------------------------------------------\n'
1074
1069
            '.*'
1080
1075
        # the final output.
1081
1076
        class Test(tests.TestCase):
1082
1077
            def known_failure_test(self):
1083
 
                self.expectFailure('failed', self.assertTrue, False)
 
1078
                self.knownFailure("Never works...")
1084
1079
        test = Test("known_failure_test")
1085
1080
        stream = StringIO()
1086
1081
        runner = tests.TextTestRunner(stream=stream)
1092
1087
            '\n'
1093
1088
            'OK \\(known_failures=1\\)\n')
1094
1089
 
 
1090
    def test_unexpected_success_bad(self):
 
1091
        class Test(tests.TestCase):
 
1092
            def test_truth(self):
 
1093
                self.expectFailure("No absolute truth", self.assertTrue, True)
 
1094
        runner = tests.TextTestRunner(stream=StringIO())
 
1095
        result = self.run_test_runner(runner, Test("test_truth"))
 
1096
        self.assertContainsRe(runner.stream.getvalue(),
 
1097
            "=+\n"
 
1098
            "FAIL: \\S+\.test_truth\n"
 
1099
            "-+\n"
 
1100
            "(?:.*\n)*"
 
1101
            "\\s*(?:Text attachment: )?reason"
 
1102
            "(?:\n-+\n|: {{{)"
 
1103
            "No absolute truth"
 
1104
            "(?:\n-+\n|}}}\n)"
 
1105
            "(?:.*\n)*"
 
1106
            "-+\n"
 
1107
            "Ran 1 test in .*\n"
 
1108
            "\n"
 
1109
            "FAILED \\(failures=1\\)\n\\Z")
 
1110
 
1095
1111
    def test_result_decorator(self):
1096
1112
        # decorate results
1097
1113
        calls = []
1098
 
        class LoggingDecorator(tests.ForwardingResult):
 
1114
        class LoggingDecorator(ExtendedToOriginalDecorator):
1099
1115
            def startTest(self, test):
1100
 
                tests.ForwardingResult.startTest(self, test)
 
1116
                ExtendedToOriginalDecorator.startTest(self, test)
1101
1117
                calls.append('start')
1102
1118
        test = unittest.FunctionTestCase(lambda:None)
1103
1119
        stream = StringIO()
1145
1161
        class SkippedTest(tests.TestCase):
1146
1162
 
1147
1163
            def setUp(self):
1148
 
                tests.TestCase.setUp(self)
 
1164
                super(SkippedTest, self).setUp()
1149
1165
                calls.append('setUp')
1150
1166
                self.addCleanup(self.cleanup)
1151
1167
 
1181
1197
 
1182
1198
    def test_unsupported_features_listed(self):
1183
1199
        """When unsupported features are encountered they are detailed."""
1184
 
        class Feature1(tests.Feature):
 
1200
        class Feature1(features.Feature):
1185
1201
            def _probe(self): return False
1186
 
        class Feature2(tests.Feature):
 
1202
        class Feature2(features.Feature):
1187
1203
            def _probe(self): return False
1188
1204
        # create sample tests
1189
1205
        test1 = SampleTestCase('_test_pass')
1204
1220
            ],
1205
1221
            lines[-3:])
1206
1222
 
1207
 
    def _patch_get_bzr_source_tree(self):
1208
 
        # Reading from the actual source tree breaks isolation, but we don't
1209
 
        # want to assume that thats *all* that would happen.
1210
 
        self._get_source_tree_calls = []
1211
 
        def new_get():
1212
 
            self._get_source_tree_calls.append("called")
1213
 
            return None
1214
 
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree',  new_get)
1215
 
 
1216
 
    def test_bench_history(self):
1217
 
        # tests that the running the benchmark passes bench_history into
1218
 
        # the test result object. We can tell that happens if
1219
 
        # _get_bzr_source_tree is called.
1220
 
        self._patch_get_bzr_source_tree()
1221
 
        test = TestRunner('dummy_test')
1222
 
        output = StringIO()
1223
 
        runner = tests.TextTestRunner(stream=self._log_file,
1224
 
                                      bench_history=output)
1225
 
        result = self.run_test_runner(runner, test)
1226
 
        output_string = output.getvalue()
1227
 
        self.assertContainsRe(output_string, "--date [0-9.]+")
1228
 
        self.assertLength(1, self._get_source_tree_calls)
 
1223
    def test_verbose_test_count(self):
 
1224
        """A verbose test run reports the right test count at the start"""
 
1225
        suite = TestUtil.TestSuite([
 
1226
            unittest.FunctionTestCase(lambda:None),
 
1227
            unittest.FunctionTestCase(lambda:None)])
 
1228
        self.assertEqual(suite.countTestCases(), 2)
 
1229
        stream = StringIO()
 
1230
        runner = tests.TextTestRunner(stream=stream, verbosity=2)
 
1231
        # Need to use the CountingDecorator as that's what sets num_tests
 
1232
        result = self.run_test_runner(runner, tests.CountingDecorator(suite))
 
1233
        self.assertStartsWith(stream.getvalue(), "running 2 tests")
1229
1234
 
1230
1235
    def test_startTestRun(self):
1231
1236
        """run should call result.startTestRun()"""
1232
1237
        calls = []
1233
 
        class LoggingDecorator(tests.ForwardingResult):
 
1238
        class LoggingDecorator(ExtendedToOriginalDecorator):
1234
1239
            def startTestRun(self):
1235
 
                tests.ForwardingResult.startTestRun(self)
 
1240
                ExtendedToOriginalDecorator.startTestRun(self)
1236
1241
                calls.append('startTestRun')
1237
1242
        test = unittest.FunctionTestCase(lambda:None)
1238
1243
        stream = StringIO()
1244
1249
    def test_stopTestRun(self):
1245
1250
        """run should call result.stopTestRun()"""
1246
1251
        calls = []
1247
 
        class LoggingDecorator(tests.ForwardingResult):
 
1252
        class LoggingDecorator(ExtendedToOriginalDecorator):
1248
1253
            def stopTestRun(self):
1249
 
                tests.ForwardingResult.stopTestRun(self)
 
1254
                ExtendedToOriginalDecorator.stopTestRun(self)
1250
1255
                calls.append('stopTestRun')
1251
1256
        test = unittest.FunctionTestCase(lambda:None)
1252
1257
        stream = StringIO()
1255
1260
        result = self.run_test_runner(runner, test)
1256
1261
        self.assertLength(1, calls)
1257
1262
 
 
1263
    def test_unicode_test_output_on_ascii_stream(self):
 
1264
        """Showing results should always succeed even on an ascii console"""
 
1265
        class FailureWithUnicode(tests.TestCase):
 
1266
            def test_log_unicode(self):
 
1267
                self.log(u"\u2606")
 
1268
                self.fail("Now print that log!")
 
1269
        out = StringIO()
 
1270
        self.overrideAttr(osutils, "get_terminal_encoding",
 
1271
            lambda trace=False: "ascii")
 
1272
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
 
1273
            FailureWithUnicode("test_log_unicode"))
 
1274
        self.assertContainsRe(out.getvalue(),
 
1275
            "(?:Text attachment: )?log"
 
1276
            "(?:\n-+\n|: {{{)"
 
1277
            "\d+\.\d+  \\\\u2606"
 
1278
            "(?:\n-+\n|}}}\n)")
 
1279
 
1258
1280
 
1259
1281
class SampleTestCase(tests.TestCase):
1260
1282
 
1448
1470
        # Note this test won't fail with hooks that the core library doesn't
1449
1471
        # use - but it trigger with a plugin that adds hooks, so its still a
1450
1472
        # useful warning in that case.
1451
 
        self.assertEqual(bzrlib.branch.BranchHooks(),
1452
 
            bzrlib.branch.Branch.hooks)
1453
 
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
 
1473
        self.assertEqual(bzrlib.branch.BranchHooks(), bzrlib.branch.Branch.hooks)
 
1474
        self.assertEqual(
 
1475
            bzrlib.smart.server.SmartServerHooks(),
1454
1476
            bzrlib.smart.server.SmartTCPServer.hooks)
1455
 
        self.assertEqual(bzrlib.commands.CommandHooks(),
1456
 
            bzrlib.commands.Command.hooks)
 
1477
        self.assertEqual(
 
1478
            bzrlib.commands.CommandHooks(), bzrlib.commands.Command.hooks)
1457
1479
 
1458
1480
    def test__gather_lsprof_in_benchmarks(self):
1459
1481
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1460
1482
 
1461
1483
        Each self.time() call is individually and separately profiled.
1462
1484
        """
1463
 
        self.requireFeature(test_lsprof.LSProfFeature)
 
1485
        self.requireFeature(features.lsprof_feature)
1464
1486
        # overrides the class member with an instance member so no cleanup
1465
1487
        # needed.
1466
1488
        self._gather_lsprof_in_benchmarks = True
1485
1507
        transport_server = memory.MemoryServer()
1486
1508
        transport_server.start_server()
1487
1509
        self.addCleanup(transport_server.stop_server)
1488
 
        t = transport.get_transport(transport_server.get_url())
1489
 
        bzrdir.BzrDir.create(t.base)
 
1510
        t = transport.get_transport_from_url(transport_server.get_url())
 
1511
        controldir.ControlDir.create(t.base)
1490
1512
        self.assertRaises(errors.BzrError,
1491
 
            bzrdir.BzrDir.open_from_transport, t)
 
1513
            controldir.ControlDir.open_from_transport, t)
1492
1514
        # But if we declare this as safe, we can open the bzrdir.
1493
1515
        self.permit_url(t.base)
1494
1516
        self._bzr_selftest_roots.append(t.base)
1495
 
        bzrdir.BzrDir.open_from_transport(t)
 
1517
        controldir.ControlDir.open_from_transport(t)
1496
1518
 
1497
1519
    def test_requireFeature_available(self):
1498
1520
        """self.requireFeature(available) is a no-op."""
1499
 
        class Available(tests.Feature):
 
1521
        class Available(features.Feature):
1500
1522
            def _probe(self):return True
1501
1523
        feature = Available()
1502
1524
        self.requireFeature(feature)
1503
1525
 
1504
1526
    def test_requireFeature_unavailable(self):
1505
1527
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1506
 
        class Unavailable(tests.Feature):
 
1528
        class Unavailable(features.Feature):
1507
1529
            def _probe(self):return False
1508
1530
        feature = Unavailable()
1509
1531
        self.assertRaises(tests.UnavailableFeature,
1632
1654
        self.assertRaises(AssertionError,
1633
1655
            self.assertListRaises, _TestException, success_generator)
1634
1656
 
 
1657
    def _run_successful_test(self, test):
 
1658
        result = testtools.TestResult()
 
1659
        test.run(result)
 
1660
        self.assertTrue(result.wasSuccessful())
 
1661
        return result
 
1662
 
1635
1663
    def test_overrideAttr_without_value(self):
1636
1664
        self.test_attr = 'original' # Define a test attribute
1637
1665
        obj = self # Make 'obj' visible to the embedded test
1638
1666
        class Test(tests.TestCase):
1639
1667
 
1640
1668
            def setUp(self):
1641
 
                tests.TestCase.setUp(self)
 
1669
                super(Test, self).setUp()
1642
1670
                self.orig = self.overrideAttr(obj, 'test_attr')
1643
1671
 
1644
1672
            def test_value(self):
1647
1675
                obj.test_attr = 'modified'
1648
1676
                self.assertEqual('modified', obj.test_attr)
1649
1677
 
1650
 
        test = Test('test_value')
1651
 
        test.run(unittest.TestResult())
 
1678
        self._run_successful_test(Test('test_value'))
1652
1679
        self.assertEqual('original', obj.test_attr)
1653
1680
 
1654
1681
    def test_overrideAttr_with_value(self):
1657
1684
        class Test(tests.TestCase):
1658
1685
 
1659
1686
            def setUp(self):
1660
 
                tests.TestCase.setUp(self)
 
1687
                super(Test, self).setUp()
1661
1688
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
1662
1689
 
1663
1690
            def test_value(self):
1664
1691
                self.assertEqual('original', self.orig)
1665
1692
                self.assertEqual('modified', obj.test_attr)
1666
1693
 
1667
 
        test = Test('test_value')
1668
 
        test.run(unittest.TestResult())
 
1694
        self._run_successful_test(Test('test_value'))
1669
1695
        self.assertEqual('original', obj.test_attr)
1670
1696
 
 
1697
    def test_overrideAttr_with_no_existing_value_and_value(self):
 
1698
        # Do not define the test_attribute
 
1699
        obj = self # Make 'obj' visible to the embedded test
 
1700
        class Test(tests.TestCase):
 
1701
 
 
1702
            def setUp(self):
 
1703
                tests.TestCase.setUp(self)
 
1704
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
 
1705
 
 
1706
            def test_value(self):
 
1707
                self.assertEqual(tests._unitialized_attr, self.orig)
 
1708
                self.assertEqual('modified', obj.test_attr)
 
1709
 
 
1710
        self._run_successful_test(Test('test_value'))
 
1711
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
 
1712
 
 
1713
    def test_overrideAttr_with_no_existing_value_and_no_value(self):
 
1714
        # Do not define the test_attribute
 
1715
        obj = self # Make 'obj' visible to the embedded test
 
1716
        class Test(tests.TestCase):
 
1717
 
 
1718
            def setUp(self):
 
1719
                tests.TestCase.setUp(self)
 
1720
                self.orig = self.overrideAttr(obj, 'test_attr')
 
1721
 
 
1722
            def test_value(self):
 
1723
                self.assertEqual(tests._unitialized_attr, self.orig)
 
1724
                self.assertRaises(AttributeError, getattr, obj, 'test_attr')
 
1725
 
 
1726
        self._run_successful_test(Test('test_value'))
 
1727
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
 
1728
 
 
1729
    def test_recordCalls(self):
 
1730
        from bzrlib.tests import test_selftest
 
1731
        calls = self.recordCalls(
 
1732
            test_selftest, '_add_numbers')
 
1733
        self.assertEqual(test_selftest._add_numbers(2, 10),
 
1734
            12)
 
1735
        self.assertEquals(calls, [((2, 10), {})])
 
1736
 
 
1737
 
 
1738
def _add_numbers(a, b):
 
1739
    return a + b
 
1740
 
 
1741
 
 
1742
class _MissingFeature(features.Feature):
 
1743
    def _probe(self):
 
1744
        return False
 
1745
missing_feature = _MissingFeature()
 
1746
 
 
1747
 
 
1748
def _get_test(name):
 
1749
    """Get an instance of a specific example test.
 
1750
 
 
1751
    We protect this in a function so that they don't auto-run in the test
 
1752
    suite.
 
1753
    """
 
1754
 
 
1755
    class ExampleTests(tests.TestCase):
 
1756
 
 
1757
        def test_fail(self):
 
1758
            mutter('this was a failing test')
 
1759
            self.fail('this test will fail')
 
1760
 
 
1761
        def test_error(self):
 
1762
            mutter('this test errored')
 
1763
            raise RuntimeError('gotcha')
 
1764
 
 
1765
        def test_missing_feature(self):
 
1766
            mutter('missing the feature')
 
1767
            self.requireFeature(missing_feature)
 
1768
 
 
1769
        def test_skip(self):
 
1770
            mutter('this test will be skipped')
 
1771
            raise tests.TestSkipped('reason')
 
1772
 
 
1773
        def test_success(self):
 
1774
            mutter('this test succeeds')
 
1775
 
 
1776
        def test_xfail(self):
 
1777
            mutter('test with expected failure')
 
1778
            self.knownFailure('this_fails')
 
1779
 
 
1780
        def test_unexpected_success(self):
 
1781
            mutter('test with unexpected success')
 
1782
            self.expectFailure('should_fail', lambda: None)
 
1783
 
 
1784
    return ExampleTests(name)
 
1785
 
 
1786
 
 
1787
class TestTestCaseLogDetails(tests.TestCase):
 
1788
 
 
1789
    def _run_test(self, test_name):
 
1790
        test = _get_test(test_name)
 
1791
        result = testtools.TestResult()
 
1792
        test.run(result)
 
1793
        return result
 
1794
 
 
1795
    def test_fail_has_log(self):
 
1796
        result = self._run_test('test_fail')
 
1797
        self.assertEqual(1, len(result.failures))
 
1798
        result_content = result.failures[0][1]
 
1799
        self.assertContainsRe(result_content,
 
1800
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1801
        self.assertContainsRe(result_content, 'this was a failing test')
 
1802
 
 
1803
    def test_error_has_log(self):
 
1804
        result = self._run_test('test_error')
 
1805
        self.assertEqual(1, len(result.errors))
 
1806
        result_content = result.errors[0][1]
 
1807
        self.assertContainsRe(result_content,
 
1808
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1809
        self.assertContainsRe(result_content, 'this test errored')
 
1810
 
 
1811
    def test_skip_has_no_log(self):
 
1812
        result = self._run_test('test_skip')
 
1813
        self.assertEqual(['reason'], result.skip_reasons.keys())
 
1814
        skips = result.skip_reasons['reason']
 
1815
        self.assertEqual(1, len(skips))
 
1816
        test = skips[0]
 
1817
        self.assertFalse('log' in test.getDetails())
 
1818
 
 
1819
    def test_missing_feature_has_no_log(self):
 
1820
        # testtools doesn't know about addNotSupported, so it just gets
 
1821
        # considered as a skip
 
1822
        result = self._run_test('test_missing_feature')
 
1823
        self.assertEqual([missing_feature], result.skip_reasons.keys())
 
1824
        skips = result.skip_reasons[missing_feature]
 
1825
        self.assertEqual(1, len(skips))
 
1826
        test = skips[0]
 
1827
        self.assertFalse('log' in test.getDetails())
 
1828
 
 
1829
    def test_xfail_has_no_log(self):
 
1830
        result = self._run_test('test_xfail')
 
1831
        self.assertEqual(1, len(result.expectedFailures))
 
1832
        result_content = result.expectedFailures[0][1]
 
1833
        self.assertNotContainsRe(result_content,
 
1834
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1835
        self.assertNotContainsRe(result_content, 'test with expected failure')
 
1836
 
 
1837
    def test_unexpected_success_has_log(self):
 
1838
        result = self._run_test('test_unexpected_success')
 
1839
        self.assertEqual(1, len(result.unexpectedSuccesses))
 
1840
        # Inconsistency, unexpectedSuccesses is a list of tests,
 
1841
        # expectedFailures is a list of reasons?
 
1842
        test = result.unexpectedSuccesses[0]
 
1843
        details = test.getDetails()
 
1844
        self.assertTrue('log' in details)
 
1845
 
 
1846
 
 
1847
class TestTestCloning(tests.TestCase):
 
1848
    """Tests that test cloning of TestCases (as used by multiply_tests)."""
 
1849
 
 
1850
    def test_cloned_testcase_does_not_share_details(self):
 
1851
        """A TestCase cloned with clone_test does not share mutable attributes
 
1852
        such as details or cleanups.
 
1853
        """
 
1854
        class Test(tests.TestCase):
 
1855
            def test_foo(self):
 
1856
                self.addDetail('foo', Content('text/plain', lambda: 'foo'))
 
1857
        orig_test = Test('test_foo')
 
1858
        cloned_test = tests.clone_test(orig_test, orig_test.id() + '(cloned)')
 
1859
        orig_test.run(unittest.TestResult())
 
1860
        self.assertEqual('foo', orig_test.getDetails()['foo'].iter_bytes())
 
1861
        self.assertEqual(None, cloned_test.getDetails().get('foo'))
 
1862
 
 
1863
    def test_double_apply_scenario_preserves_first_scenario(self):
 
1864
        """Applying two levels of scenarios to a test preserves the attributes
 
1865
        added by both scenarios.
 
1866
        """
 
1867
        class Test(tests.TestCase):
 
1868
            def test_foo(self):
 
1869
                pass
 
1870
        test = Test('test_foo')
 
1871
        scenarios_x = [('x=1', {'x': 1}), ('x=2', {'x': 2})]
 
1872
        scenarios_y = [('y=1', {'y': 1}), ('y=2', {'y': 2})]
 
1873
        suite = tests.multiply_tests(test, scenarios_x, unittest.TestSuite())
 
1874
        suite = tests.multiply_tests(suite, scenarios_y, unittest.TestSuite())
 
1875
        all_tests = list(tests.iter_suite_tests(suite))
 
1876
        self.assertLength(4, all_tests)
 
1877
        all_xys = sorted((t.x, t.y) for t in all_tests)
 
1878
        self.assertEqual([(1, 1), (1, 2), (2, 1), (2, 2)], all_xys)
 
1879
 
1671
1880
 
1672
1881
# NB: Don't delete this; it's not actually from 0.11!
1673
1882
@deprecated_function(deprecated_in((0, 11, 0)))
1801
2010
    def test_make_branch_and_tree_with_format(self):
1802
2011
        # we should be able to supply a format to make_branch_and_tree
1803
2012
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1804
 
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1805
 
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
 
2013
        self.assertIsInstance(bzrlib.controldir.ControlDir.open('a')._format,
1806
2014
                              bzrlib.bzrdir.BzrDirMetaFormat1)
1807
 
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1808
 
                              bzrlib.bzrdir.BzrDirFormat6)
1809
2015
 
1810
2016
    def test_make_branch_and_memory_tree(self):
1811
2017
        # we should be able to get a new branch and a mutable tree from
1828
2034
                tree.branch.repository.bzrdir.root_transport)
1829
2035
 
1830
2036
 
1831
 
class SelfTestHelper:
 
2037
class SelfTestHelper(object):
1832
2038
 
1833
2039
    def run_selftest(self, **kwargs):
1834
2040
        """Run selftest returning its output."""
1888
2094
        self.assertLength(2, output.readlines())
1889
2095
 
1890
2096
    def test_lsprof_tests(self):
1891
 
        self.requireFeature(test_lsprof.LSProfFeature)
1892
 
        calls = []
 
2097
        self.requireFeature(features.lsprof_feature)
 
2098
        results = []
1893
2099
        class Test(object):
1894
2100
            def __call__(test, result):
1895
2101
                test.run(result)
1896
2102
            def run(test, result):
1897
 
                self.assertIsInstance(result, tests.ForwardingResult)
1898
 
                calls.append("called")
 
2103
                results.append(result)
1899
2104
            def countTestCases(self):
1900
2105
                return 1
1901
2106
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1902
 
        self.assertLength(1, calls)
 
2107
        self.assertLength(1, results)
 
2108
        self.assertIsInstance(results.pop(), ExtendedToOriginalDecorator)
1903
2109
 
1904
2110
    def test_random(self):
1905
2111
        # test randomising by listing a number of tests.
1985
2191
            load_list='missing file name', list_only=True)
1986
2192
 
1987
2193
 
 
2194
class TestSubunitLogDetails(tests.TestCase, SelfTestHelper):
 
2195
 
 
2196
    _test_needs_features = [features.subunit]
 
2197
 
 
2198
    def run_subunit_stream(self, test_name):
 
2199
        from subunit import ProtocolTestCase
 
2200
        def factory():
 
2201
            return TestUtil.TestSuite([_get_test(test_name)])
 
2202
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
 
2203
            test_suite_factory=factory)
 
2204
        test = ProtocolTestCase(stream)
 
2205
        result = testtools.TestResult()
 
2206
        test.run(result)
 
2207
        content = stream.getvalue()
 
2208
        return content, result
 
2209
 
 
2210
    def test_fail_has_log(self):
 
2211
        content, result = self.run_subunit_stream('test_fail')
 
2212
        self.assertEqual(1, len(result.failures))
 
2213
        self.assertContainsRe(content, '(?m)^log$')
 
2214
        self.assertContainsRe(content, 'this test will fail')
 
2215
 
 
2216
    def test_error_has_log(self):
 
2217
        content, result = self.run_subunit_stream('test_error')
 
2218
        self.assertContainsRe(content, '(?m)^log$')
 
2219
        self.assertContainsRe(content, 'this test errored')
 
2220
 
 
2221
    def test_skip_has_no_log(self):
 
2222
        content, result = self.run_subunit_stream('test_skip')
 
2223
        self.assertNotContainsRe(content, '(?m)^log$')
 
2224
        self.assertNotContainsRe(content, 'this test will be skipped')
 
2225
        self.assertEqual(['reason'], result.skip_reasons.keys())
 
2226
        skips = result.skip_reasons['reason']
 
2227
        self.assertEqual(1, len(skips))
 
2228
        test = skips[0]
 
2229
        # RemotedTestCase doesn't preserve the "details"
 
2230
        ## self.assertFalse('log' in test.getDetails())
 
2231
 
 
2232
    def test_missing_feature_has_no_log(self):
 
2233
        content, result = self.run_subunit_stream('test_missing_feature')
 
2234
        self.assertNotContainsRe(content, '(?m)^log$')
 
2235
        self.assertNotContainsRe(content, 'missing the feature')
 
2236
        self.assertEqual(['_MissingFeature\n'], result.skip_reasons.keys())
 
2237
        skips = result.skip_reasons['_MissingFeature\n']
 
2238
        self.assertEqual(1, len(skips))
 
2239
        test = skips[0]
 
2240
        # RemotedTestCase doesn't preserve the "details"
 
2241
        ## self.assertFalse('log' in test.getDetails())
 
2242
 
 
2243
    def test_xfail_has_no_log(self):
 
2244
        content, result = self.run_subunit_stream('test_xfail')
 
2245
        self.assertNotContainsRe(content, '(?m)^log$')
 
2246
        self.assertNotContainsRe(content, 'test with expected failure')
 
2247
        self.assertEqual(1, len(result.expectedFailures))
 
2248
        result_content = result.expectedFailures[0][1]
 
2249
        self.assertNotContainsRe(result_content,
 
2250
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
2251
        self.assertNotContainsRe(result_content, 'test with expected failure')
 
2252
 
 
2253
    def test_unexpected_success_has_log(self):
 
2254
        content, result = self.run_subunit_stream('test_unexpected_success')
 
2255
        self.assertContainsRe(content, '(?m)^log$')
 
2256
        self.assertContainsRe(content, 'test with unexpected success')
 
2257
        # GZ 2011-05-18: Old versions of subunit treat unexpected success as a
 
2258
        #                success, if a min version check is added remove this
 
2259
        from subunit import TestProtocolClient as _Client
 
2260
        if _Client.addUnexpectedSuccess.im_func is _Client.addSuccess.im_func:
 
2261
            self.expectFailure('subunit treats "unexpectedSuccess"'
 
2262
                               ' as a plain success',
 
2263
                self.assertEqual, 1, len(result.unexpectedSuccesses))
 
2264
        self.assertEqual(1, len(result.unexpectedSuccesses))
 
2265
        test = result.unexpectedSuccesses[0]
 
2266
        # RemotedTestCase doesn't preserve the "details"
 
2267
        ## self.assertTrue('log' in test.getDetails())
 
2268
 
 
2269
    def test_success_has_no_log(self):
 
2270
        content, result = self.run_subunit_stream('test_success')
 
2271
        self.assertEqual(1, result.testsRun)
 
2272
        self.assertNotContainsRe(content, '(?m)^log$')
 
2273
        self.assertNotContainsRe(content, 'this test succeeds')
 
2274
 
 
2275
 
1988
2276
class TestRunBzr(tests.TestCase):
1989
2277
 
1990
2278
    out = ''
2113
2401
        # stdout and stderr of the invoked run_bzr
2114
2402
        current_factory = bzrlib.ui.ui_factory
2115
2403
        self.run_bzr(['foo'])
2116
 
        self.failIf(current_factory is self.factory)
 
2404
        self.assertFalse(current_factory is self.factory)
2117
2405
        self.assertNotEqual(sys.stdout, self.factory.stdout)
2118
2406
        self.assertNotEqual(sys.stderr, self.factory.stderr)
2119
2407
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
2160
2448
    """Base class for tests testing how we might run bzr."""
2161
2449
 
2162
2450
    def setUp(self):
2163
 
        tests.TestCaseWithTransport.setUp(self)
 
2451
        super(TestWithFakedStartBzrSubprocess, self).setUp()
2164
2452
        self.subprocess_calls = []
2165
2453
 
2166
2454
    def start_bzr_subprocess(self, process_args, env_changes=None,
2276
2564
 
2277
2565
 
2278
2566
class TestStartBzrSubProcess(tests.TestCase):
 
2567
    """Stub test start_bzr_subprocess."""
2279
2568
 
2280
 
    def check_popen_state(self):
2281
 
        """Replace to make assertions when popen is called."""
 
2569
    def _subprocess_log_cleanup(self):
 
2570
        """Inhibits the base version as we don't produce a log file."""
2282
2571
 
2283
2572
    def _popen(self, *args, **kwargs):
2284
 
        """Record the command that is run, so that we can ensure it is correct"""
 
2573
        """Override the base version to record the command that is run.
 
2574
 
 
2575
        From there we can ensure it is correct without spawning a real process.
 
2576
        """
2285
2577
        self.check_popen_state()
2286
2578
        self._popen_args = args
2287
2579
        self._popen_kwargs = kwargs
2288
2580
        raise _DontSpawnProcess()
2289
2581
 
 
2582
    def check_popen_state(self):
 
2583
        """Replace to make assertions when popen is called."""
 
2584
 
2290
2585
    def test_run_bzr_subprocess_no_plugins(self):
2291
2586
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2292
2587
        command = self._popen_args[0]
2296
2591
 
2297
2592
    def test_allow_plugins(self):
2298
2593
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2299
 
            allow_plugins=True)
 
2594
                          allow_plugins=True)
2300
2595
        command = self._popen_args[0]
2301
2596
        self.assertEqual([], command[2:])
2302
2597
 
2303
2598
    def test_set_env(self):
2304
 
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2599
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2305
2600
        # set in the child
2306
2601
        def check_environment():
2307
2602
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2308
2603
        self.check_popen_state = check_environment
2309
2604
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2310
 
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2605
                          env_changes={'EXISTANT_ENV_VAR':'set variable'})
2311
2606
        # not set in theparent
2312
2607
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2313
2608
 
2314
2609
    def test_run_bzr_subprocess_env_del(self):
2315
2610
        """run_bzr_subprocess can remove environment variables too."""
2316
 
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2611
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2317
2612
        def check_environment():
2318
2613
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2319
2614
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2320
2615
        self.check_popen_state = check_environment
2321
2616
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2322
 
            env_changes={'EXISTANT_ENV_VAR':None})
 
2617
                          env_changes={'EXISTANT_ENV_VAR':None})
2323
2618
        # Still set in parent
2324
2619
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2325
2620
        del os.environ['EXISTANT_ENV_VAR']
2326
2621
 
2327
2622
    def test_env_del_missing(self):
2328
 
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
 
2623
        self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2329
2624
        def check_environment():
2330
2625
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2331
2626
        self.check_popen_state = check_environment
2332
2627
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2333
 
            env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2628
                          env_changes={'NON_EXISTANT_ENV_VAR':None})
2334
2629
 
2335
2630
    def test_working_dir(self):
2336
2631
        """Test that we can specify the working dir for the child"""
2339
2634
        chdirs = []
2340
2635
        def chdir(path):
2341
2636
            chdirs.append(path)
2342
 
        os.chdir = chdir
2343
 
        try:
2344
 
            def getcwd():
2345
 
                return 'current'
2346
 
            osutils.getcwd = getcwd
2347
 
            try:
2348
 
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2349
 
                    working_dir='foo')
2350
 
            finally:
2351
 
                osutils.getcwd = orig_getcwd
2352
 
        finally:
2353
 
            os.chdir = orig_chdir
 
2637
        self.overrideAttr(os, 'chdir', chdir)
 
2638
        def getcwd():
 
2639
            return 'current'
 
2640
        self.overrideAttr(osutils, 'getcwd', getcwd)
 
2641
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2642
                          working_dir='foo')
2354
2643
        self.assertEqual(['foo', 'current'], chdirs)
2355
2644
 
2356
2645
    def test_get_bzr_path_with_cwd_bzrlib(self):
2376
2665
        self.assertEqual('bzr: interrupted\n', result[1])
2377
2666
 
2378
2667
 
2379
 
class TestFeature(tests.TestCase):
2380
 
 
2381
 
    def test_caching(self):
2382
 
        """Feature._probe is called by the feature at most once."""
2383
 
        class InstrumentedFeature(tests.Feature):
2384
 
            def __init__(self):
2385
 
                super(InstrumentedFeature, self).__init__()
2386
 
                self.calls = []
2387
 
            def _probe(self):
2388
 
                self.calls.append('_probe')
2389
 
                return False
2390
 
        feature = InstrumentedFeature()
2391
 
        feature.available()
2392
 
        self.assertEqual(['_probe'], feature.calls)
2393
 
        feature.available()
2394
 
        self.assertEqual(['_probe'], feature.calls)
2395
 
 
2396
 
    def test_named_str(self):
2397
 
        """Feature.__str__ should thunk to feature_name()."""
2398
 
        class NamedFeature(tests.Feature):
2399
 
            def feature_name(self):
2400
 
                return 'symlinks'
2401
 
        feature = NamedFeature()
2402
 
        self.assertEqual('symlinks', str(feature))
2403
 
 
2404
 
    def test_default_str(self):
2405
 
        """Feature.__str__ should default to __class__.__name__."""
2406
 
        class NamedFeature(tests.Feature):
2407
 
            pass
2408
 
        feature = NamedFeature()
2409
 
        self.assertEqual('NamedFeature', str(feature))
2410
 
 
2411
 
 
2412
 
class TestUnavailableFeature(tests.TestCase):
2413
 
 
2414
 
    def test_access_feature(self):
2415
 
        feature = tests.Feature()
2416
 
        exception = tests.UnavailableFeature(feature)
2417
 
        self.assertIs(feature, exception.args[0])
2418
 
 
2419
 
 
2420
 
simple_thunk_feature = tests._CompatabilityThunkFeature(
2421
 
    deprecated_in((2, 1, 0)),
2422
 
    'bzrlib.tests.test_selftest',
2423
 
    'simple_thunk_feature','UnicodeFilename',
2424
 
    replacement_module='bzrlib.tests'
2425
 
    )
2426
 
 
2427
 
class Test_CompatibilityFeature(tests.TestCase):
2428
 
 
2429
 
    def test_does_thunk(self):
2430
 
        res = self.callDeprecated(
2431
 
            ['bzrlib.tests.test_selftest.simple_thunk_feature was deprecated'
2432
 
             ' in version 2.1.0. Use bzrlib.tests.UnicodeFilename instead.'],
2433
 
            simple_thunk_feature.available)
2434
 
        self.assertEqual(tests.UnicodeFilename.available(), res)
2435
 
 
2436
 
 
2437
 
class TestModuleAvailableFeature(tests.TestCase):
2438
 
 
2439
 
    def test_available_module(self):
2440
 
        feature = tests.ModuleAvailableFeature('bzrlib.tests')
2441
 
        self.assertEqual('bzrlib.tests', feature.module_name)
2442
 
        self.assertEqual('bzrlib.tests', str(feature))
2443
 
        self.assertTrue(feature.available())
2444
 
        self.assertIs(tests, feature.module)
2445
 
 
2446
 
    def test_unavailable_module(self):
2447
 
        feature = tests.ModuleAvailableFeature('bzrlib.no_such_module_exists')
2448
 
        self.assertEqual('bzrlib.no_such_module_exists', str(feature))
2449
 
        self.assertFalse(feature.available())
2450
 
        self.assertIs(None, feature.module)
2451
 
 
2452
 
 
2453
2668
class TestSelftestFiltering(tests.TestCase):
2454
2669
 
2455
2670
    def setUp(self):
2456
 
        tests.TestCase.setUp(self)
 
2671
        super(TestSelftestFiltering, self).setUp()
2457
2672
        self.suite = TestUtil.TestSuite()
2458
2673
        self.loader = TestUtil.TestLoader()
2459
2674
        self.suite.addTest(self.loader.loadTestsFromModule(
2606
2821
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2607
2822
 
2608
2823
 
2609
 
class TestCheckInventoryShape(tests.TestCaseWithTransport):
 
2824
class TestCheckTreeShape(tests.TestCaseWithTransport):
2610
2825
 
2611
 
    def test_check_inventory_shape(self):
 
2826
    def test_check_tree_shape(self):
2612
2827
        files = ['a', 'b/', 'b/c']
2613
2828
        tree = self.make_branch_and_tree('.')
2614
2829
        self.build_tree(files)
2615
2830
        tree.add(files)
2616
2831
        tree.lock_read()
2617
2832
        try:
2618
 
            self.check_inventory_shape(tree.inventory, files)
 
2833
            self.check_tree_shape(tree, files)
2619
2834
        finally:
2620
2835
            tree.unlock()
2621
2836
 
2953
3168
        tpr.register('bar', 'bBB.aAA.rRR')
2954
3169
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2955
3170
        self.assertThat(self.get_log(),
2956
 
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR", ELLIPSIS))
 
3171
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR",
 
3172
                           doctest.ELLIPSIS))
2957
3173
 
2958
3174
    def test_get_unknown_prefix(self):
2959
3175
        tpr = self._get_registry()
2979
3195
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2980
3196
 
2981
3197
 
 
3198
class TestThreadLeakDetection(tests.TestCase):
 
3199
    """Ensure when tests leak threads we detect and report it"""
 
3200
 
 
3201
    class LeakRecordingResult(tests.ExtendedTestResult):
 
3202
        def __init__(self):
 
3203
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
 
3204
            self.leaks = []
 
3205
        def _report_thread_leak(self, test, leaks, alive):
 
3206
            self.leaks.append((test, leaks))
 
3207
 
 
3208
    def test_testcase_without_addCleanups(self):
 
3209
        """Check old TestCase instances don't break with leak detection"""
 
3210
        class Test(unittest.TestCase):
 
3211
            def runTest(self):
 
3212
                pass
 
3213
        result = self.LeakRecordingResult()
 
3214
        test = Test()
 
3215
        result.startTestRun()
 
3216
        test.run(result)
 
3217
        result.stopTestRun()
 
3218
        self.assertEqual(result._tests_leaking_threads_count, 0)
 
3219
        self.assertEqual(result.leaks, [])
 
3220
        
 
3221
    def test_thread_leak(self):
 
3222
        """Ensure a thread that outlives the running of a test is reported
 
3223
 
 
3224
        Uses a thread that blocks on an event, and is started by the inner
 
3225
        test case. As the thread outlives the inner case's run, it should be
 
3226
        detected as a leak, but the event is then set so that the thread can
 
3227
        be safely joined in cleanup so it's not leaked for real.
 
3228
        """
 
3229
        event = threading.Event()
 
3230
        thread = threading.Thread(name="Leaker", target=event.wait)
 
3231
        class Test(tests.TestCase):
 
3232
            def test_leak(self):
 
3233
                thread.start()
 
3234
        result = self.LeakRecordingResult()
 
3235
        test = Test("test_leak")
 
3236
        self.addCleanup(thread.join)
 
3237
        self.addCleanup(event.set)
 
3238
        result.startTestRun()
 
3239
        test.run(result)
 
3240
        result.stopTestRun()
 
3241
        self.assertEqual(result._tests_leaking_threads_count, 1)
 
3242
        self.assertEqual(result._first_thread_leaker_id, test.id())
 
3243
        self.assertEqual(result.leaks, [(test, set([thread]))])
 
3244
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
 
3245
 
 
3246
    def test_multiple_leaks(self):
 
3247
        """Check multiple leaks are blamed on the test cases at fault
 
3248
 
 
3249
        Same concept as the previous test, but has one inner test method that
 
3250
        leaks two threads, and one that doesn't leak at all.
 
3251
        """
 
3252
        event = threading.Event()
 
3253
        thread_a = threading.Thread(name="LeakerA", target=event.wait)
 
3254
        thread_b = threading.Thread(name="LeakerB", target=event.wait)
 
3255
        thread_c = threading.Thread(name="LeakerC", target=event.wait)
 
3256
        class Test(tests.TestCase):
 
3257
            def test_first_leak(self):
 
3258
                thread_b.start()
 
3259
            def test_second_no_leak(self):
 
3260
                pass
 
3261
            def test_third_leak(self):
 
3262
                thread_c.start()
 
3263
                thread_a.start()
 
3264
        result = self.LeakRecordingResult()
 
3265
        first_test = Test("test_first_leak")
 
3266
        third_test = Test("test_third_leak")
 
3267
        self.addCleanup(thread_a.join)
 
3268
        self.addCleanup(thread_b.join)
 
3269
        self.addCleanup(thread_c.join)
 
3270
        self.addCleanup(event.set)
 
3271
        result.startTestRun()
 
3272
        unittest.TestSuite(
 
3273
            [first_test, Test("test_second_no_leak"), third_test]
 
3274
            ).run(result)
 
3275
        result.stopTestRun()
 
3276
        self.assertEqual(result._tests_leaking_threads_count, 2)
 
3277
        self.assertEqual(result._first_thread_leaker_id, first_test.id())
 
3278
        self.assertEqual(result.leaks, [
 
3279
            (first_test, set([thread_b])),
 
3280
            (third_test, set([thread_a, thread_c]))])
 
3281
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
 
3282
 
 
3283
 
 
3284
class TestPostMortemDebugging(tests.TestCase):
 
3285
    """Check post mortem debugging works when tests fail or error"""
 
3286
 
 
3287
    class TracebackRecordingResult(tests.ExtendedTestResult):
 
3288
        def __init__(self):
 
3289
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
 
3290
            self.postcode = None
 
3291
        def _post_mortem(self, tb=None):
 
3292
            """Record the code object at the end of the current traceback"""
 
3293
            tb = tb or sys.exc_info()[2]
 
3294
            if tb is not None:
 
3295
                next = tb.tb_next
 
3296
                while next is not None:
 
3297
                    tb = next
 
3298
                    next = next.tb_next
 
3299
                self.postcode = tb.tb_frame.f_code
 
3300
        def report_error(self, test, err):
 
3301
            pass
 
3302
        def report_failure(self, test, err):
 
3303
            pass
 
3304
 
 
3305
    def test_location_unittest_error(self):
 
3306
        """Needs right post mortem traceback with erroring unittest case"""
 
3307
        class Test(unittest.TestCase):
 
3308
            def runTest(self):
 
3309
                raise RuntimeError
 
3310
        result = self.TracebackRecordingResult()
 
3311
        Test().run(result)
 
3312
        self.assertEqual(result.postcode, Test.runTest.func_code)
 
3313
 
 
3314
    def test_location_unittest_failure(self):
 
3315
        """Needs right post mortem traceback with failing unittest case"""
 
3316
        class Test(unittest.TestCase):
 
3317
            def runTest(self):
 
3318
                raise self.failureException
 
3319
        result = self.TracebackRecordingResult()
 
3320
        Test().run(result)
 
3321
        self.assertEqual(result.postcode, Test.runTest.func_code)
 
3322
 
 
3323
    def test_location_bt_error(self):
 
3324
        """Needs right post mortem traceback with erroring bzrlib.tests case"""
 
3325
        class Test(tests.TestCase):
 
3326
            def test_error(self):
 
3327
                raise RuntimeError
 
3328
        result = self.TracebackRecordingResult()
 
3329
        Test("test_error").run(result)
 
3330
        self.assertEqual(result.postcode, Test.test_error.func_code)
 
3331
 
 
3332
    def test_location_bt_failure(self):
 
3333
        """Needs right post mortem traceback with failing bzrlib.tests case"""
 
3334
        class Test(tests.TestCase):
 
3335
            def test_failure(self):
 
3336
                raise self.failureException
 
3337
        result = self.TracebackRecordingResult()
 
3338
        Test("test_failure").run(result)
 
3339
        self.assertEqual(result.postcode, Test.test_failure.func_code)
 
3340
 
 
3341
    def test_env_var_triggers_post_mortem(self):
 
3342
        """Check pdb.post_mortem is called iff BZR_TEST_PDB is set"""
 
3343
        import pdb
 
3344
        result = tests.ExtendedTestResult(StringIO(), 0, 1)
 
3345
        post_mortem_calls = []
 
3346
        self.overrideAttr(pdb, "post_mortem", post_mortem_calls.append)
 
3347
        self.overrideEnv('BZR_TEST_PDB', None)
 
3348
        result._post_mortem(1)
 
3349
        self.overrideEnv('BZR_TEST_PDB', 'on')
 
3350
        result._post_mortem(2)
 
3351
        self.assertEqual([2], post_mortem_calls)
 
3352
 
 
3353
 
2982
3354
class TestRunSuite(tests.TestCase):
2983
3355
 
2984
3356
    def test_runner_class(self):
2995
3367
                                                self.verbosity)
2996
3368
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2997
3369
        self.assertLength(1, calls)
 
3370
 
 
3371
 
 
3372
class _Selftest(object):
 
3373
    """Mixin for tests needing full selftest output"""
 
3374
 
 
3375
    def _inject_stream_into_subunit(self, stream):
 
3376
        """To be overridden by subclasses that run tests out of process"""
 
3377
 
 
3378
    def _run_selftest(self, **kwargs):
 
3379
        sio = StringIO()
 
3380
        self._inject_stream_into_subunit(sio)
 
3381
        tests.selftest(stream=sio, stop_on_failure=False, **kwargs)
 
3382
        return sio.getvalue()
 
3383
 
 
3384
 
 
3385
class _ForkedSelftest(_Selftest):
 
3386
    """Mixin for tests needing full selftest output with forked children"""
 
3387
 
 
3388
    _test_needs_features = [features.subunit]
 
3389
 
 
3390
    def _inject_stream_into_subunit(self, stream):
 
3391
        """Monkey-patch subunit so the extra output goes to stream not stdout
 
3392
 
 
3393
        Some APIs need rewriting so this kind of bogus hackery can be replaced
 
3394
        by passing the stream param from run_tests down into ProtocolTestCase.
 
3395
        """
 
3396
        from subunit import ProtocolTestCase
 
3397
        _original_init = ProtocolTestCase.__init__
 
3398
        def _init_with_passthrough(self, *args, **kwargs):
 
3399
            _original_init(self, *args, **kwargs)
 
3400
            self._passthrough = stream
 
3401
        self.overrideAttr(ProtocolTestCase, "__init__", _init_with_passthrough)
 
3402
 
 
3403
    def _run_selftest(self, **kwargs):
 
3404
        # GZ 2011-05-26: Add a PosixSystem feature so this check can go away
 
3405
        if getattr(os, "fork", None) is None:
 
3406
            raise tests.TestNotApplicable("Platform doesn't support forking")
 
3407
        # Make sure the fork code is actually invoked by claiming two cores
 
3408
        self.overrideAttr(osutils, "local_concurrency", lambda: 2)
 
3409
        kwargs.setdefault("suite_decorators", []).append(tests.fork_decorator)
 
3410
        return super(_ForkedSelftest, self)._run_selftest(**kwargs)
 
3411
 
 
3412
 
 
3413
class TestParallelFork(_ForkedSelftest, tests.TestCase):
 
3414
    """Check operation of --parallel=fork selftest option"""
 
3415
 
 
3416
    def test_error_in_child_during_fork(self):
 
3417
        """Error in a forked child during test setup should get reported"""
 
3418
        class Test(tests.TestCase):
 
3419
            def testMethod(self):
 
3420
                pass
 
3421
        # We don't care what, just break something that a child will run
 
3422
        self.overrideAttr(tests, "workaround_zealous_crypto_random", None)
 
3423
        out = self._run_selftest(test_suite_factory=Test)
 
3424
        # Lines from the tracebacks of the two child processes may be mixed
 
3425
        # together due to the way subunit parses and forwards the streams,
 
3426
        # so permit extra lines between each part of the error output.
 
3427
        self.assertContainsRe(out,
 
3428
            "Traceback.*:\n"
 
3429
            "(?:.*\n)*"
 
3430
            ".+ in fork_for_tests\n"
 
3431
            "(?:.*\n)*"
 
3432
            "\s*workaround_zealous_crypto_random\(\)\n"
 
3433
            "(?:.*\n)*"
 
3434
            "TypeError:")
 
3435
 
 
3436
 
 
3437
class TestUncollectedWarnings(_Selftest, tests.TestCase):
 
3438
    """Check a test case still alive after being run emits a warning"""
 
3439
 
 
3440
    class Test(tests.TestCase):
 
3441
        def test_pass(self):
 
3442
            pass
 
3443
        def test_self_ref(self):
 
3444
            self.also_self = self.test_self_ref
 
3445
        def test_skip(self):
 
3446
            self.skip("Don't need")
 
3447
 
 
3448
    def _get_suite(self):
 
3449
        return TestUtil.TestSuite([
 
3450
            self.Test("test_pass"),
 
3451
            self.Test("test_self_ref"),
 
3452
            self.Test("test_skip"),
 
3453
            ])
 
3454
 
 
3455
    def _run_selftest_with_suite(self, **kwargs):
 
3456
        old_flags = tests.selftest_debug_flags
 
3457
        tests.selftest_debug_flags = old_flags.union(["uncollected_cases"])
 
3458
        gc_on = gc.isenabled()
 
3459
        if gc_on:
 
3460
            gc.disable()
 
3461
        try:
 
3462
            output = self._run_selftest(test_suite_factory=self._get_suite,
 
3463
                **kwargs)
 
3464
        finally:
 
3465
            if gc_on:
 
3466
                gc.enable()
 
3467
            tests.selftest_debug_flags = old_flags
 
3468
        self.assertNotContainsRe(output, "Uncollected test case.*test_pass")
 
3469
        self.assertContainsRe(output, "Uncollected test case.*test_self_ref")
 
3470
        return output
 
3471
 
 
3472
    def test_testsuite(self):
 
3473
        self._run_selftest_with_suite()
 
3474
 
 
3475
    def test_pattern(self):
 
3476
        out = self._run_selftest_with_suite(pattern="test_(?:pass|self_ref)$")
 
3477
        self.assertNotContainsRe(out, "test_skip")
 
3478
 
 
3479
    def test_exclude_pattern(self):
 
3480
        out = self._run_selftest_with_suite(exclude_pattern="test_skip$")
 
3481
        self.assertNotContainsRe(out, "test_skip")
 
3482
 
 
3483
    def test_random_seed(self):
 
3484
        self._run_selftest_with_suite(random_seed="now")
 
3485
 
 
3486
    def test_matching_tests_first(self):
 
3487
        self._run_selftest_with_suite(matching_tests_first=True,
 
3488
            pattern="test_self_ref$")
 
3489
 
 
3490
    def test_starting_with_and_exclude(self):
 
3491
        out = self._run_selftest_with_suite(starting_with=["bt."],
 
3492
            exclude_pattern="test_skip$")
 
3493
        self.assertNotContainsRe(out, "test_skip")
 
3494
 
 
3495
    def test_additonal_decorator(self):
 
3496
        out = self._run_selftest_with_suite(
 
3497
            suite_decorators=[tests.TestDecorator])
 
3498
 
 
3499
 
 
3500
class TestUncollectedWarningsSubunit(TestUncollectedWarnings):
 
3501
    """Check warnings from tests staying alive are emitted with subunit"""
 
3502
 
 
3503
    _test_needs_features = [features.subunit]
 
3504
 
 
3505
    def _run_selftest_with_suite(self, **kwargs):
 
3506
        return TestUncollectedWarnings._run_selftest_with_suite(self,
 
3507
            runner_class=tests.SubUnitBzrRunner, **kwargs)
 
3508
 
 
3509
 
 
3510
class TestUncollectedWarningsForked(_ForkedSelftest, TestUncollectedWarnings):
 
3511
    """Check warnings from tests staying alive are emitted when forking"""
 
3512
 
 
3513
 
 
3514
class TestEnvironHandling(tests.TestCase):
 
3515
 
 
3516
    def test_overrideEnv_None_called_twice_doesnt_leak(self):
 
3517
        self.assertFalse('MYVAR' in os.environ)
 
3518
        self.overrideEnv('MYVAR', '42')
 
3519
        # We use an embedded test to make sure we fix the _captureVar bug
 
3520
        class Test(tests.TestCase):
 
3521
            def test_me(self):
 
3522
                # The first call save the 42 value
 
3523
                self.overrideEnv('MYVAR', None)
 
3524
                self.assertEquals(None, os.environ.get('MYVAR'))
 
3525
                # Make sure we can call it twice
 
3526
                self.overrideEnv('MYVAR', None)
 
3527
                self.assertEquals(None, os.environ.get('MYVAR'))
 
3528
        output = StringIO()
 
3529
        result = tests.TextTestResult(output, 0, 1)
 
3530
        Test('test_me').run(result)
 
3531
        if not result.wasStrictlySuccessful():
 
3532
            self.fail(output.getvalue())
 
3533
        # We get our value back
 
3534
        self.assertEquals('42', os.environ.get('MYVAR'))
 
3535
 
 
3536
 
 
3537
class TestIsolatedEnv(tests.TestCase):
 
3538
    """Test isolating tests from os.environ.
 
3539
 
 
3540
    Since we use tests that are already isolated from os.environ a bit of care
 
3541
    should be taken when designing the tests to avoid bootstrap side-effects.
 
3542
    The tests start an already clean os.environ which allow doing valid
 
3543
    assertions about which variables are present or not and design tests around
 
3544
    these assertions.
 
3545
    """
 
3546
 
 
3547
    class ScratchMonkey(tests.TestCase):
 
3548
 
 
3549
        def test_me(self):
 
3550
            pass
 
3551
 
 
3552
    def test_basics(self):
 
3553
        # Make sure we know the definition of BZR_HOME: not part of os.environ
 
3554
        # for tests.TestCase.
 
3555
        self.assertTrue('BZR_HOME' in tests.isolated_environ)
 
3556
        self.assertEquals(None, tests.isolated_environ['BZR_HOME'])
 
3557
        # Being part of isolated_environ, BZR_HOME should not appear here
 
3558
        self.assertFalse('BZR_HOME' in os.environ)
 
3559
        # Make sure we know the definition of LINES: part of os.environ for
 
3560
        # tests.TestCase
 
3561
        self.assertTrue('LINES' in tests.isolated_environ)
 
3562
        self.assertEquals('25', tests.isolated_environ['LINES'])
 
3563
        self.assertEquals('25', os.environ['LINES'])
 
3564
 
 
3565
    def test_injecting_unknown_variable(self):
 
3566
        # BZR_HOME is known to be absent from os.environ
 
3567
        test = self.ScratchMonkey('test_me')
 
3568
        tests.override_os_environ(test, {'BZR_HOME': 'foo'})
 
3569
        self.assertEquals('foo', os.environ['BZR_HOME'])
 
3570
        tests.restore_os_environ(test)
 
3571
        self.assertFalse('BZR_HOME' in os.environ)
 
3572
 
 
3573
    def test_injecting_known_variable(self):
 
3574
        test = self.ScratchMonkey('test_me')
 
3575
        # LINES is known to be present in os.environ
 
3576
        tests.override_os_environ(test, {'LINES': '42'})
 
3577
        self.assertEquals('42', os.environ['LINES'])
 
3578
        tests.restore_os_environ(test)
 
3579
        self.assertEquals('25', os.environ['LINES'])
 
3580
 
 
3581
    def test_deleting_variable(self):
 
3582
        test = self.ScratchMonkey('test_me')
 
3583
        # LINES is known to be present in os.environ
 
3584
        tests.override_os_environ(test, {'LINES': None})
 
3585
        self.assertTrue('LINES' not in os.environ)
 
3586
        tests.restore_os_environ(test)
 
3587
        self.assertEquals('25', os.environ['LINES'])
 
3588
 
 
3589
 
 
3590
class TestDocTestSuiteIsolation(tests.TestCase):
 
3591
    """Test that `tests.DocTestSuite` isolates doc tests from os.environ.
 
3592
 
 
3593
    Since tests.TestCase alreay provides an isolation from os.environ, we use
 
3594
    the clean environment as a base for testing. To precisely capture the
 
3595
    isolation provided by tests.DocTestSuite, we use doctest.DocTestSuite to
 
3596
    compare against.
 
3597
 
 
3598
    We want to make sure `tests.DocTestSuite` respect `tests.isolated_environ`,
 
3599
    not `os.environ` so each test overrides it to suit its needs.
 
3600
 
 
3601
    """
 
3602
 
 
3603
    def get_doctest_suite_for_string(self, klass, string):
 
3604
        class Finder(doctest.DocTestFinder):
 
3605
 
 
3606
            def find(*args, **kwargs):
 
3607
                test = doctest.DocTestParser().get_doctest(
 
3608
                    string, {}, 'foo', 'foo.py', 0)
 
3609
                return [test]
 
3610
 
 
3611
        suite = klass(test_finder=Finder())
 
3612
        return suite
 
3613
 
 
3614
    def run_doctest_suite_for_string(self, klass, string):
 
3615
        suite = self.get_doctest_suite_for_string(klass, string)
 
3616
        output = StringIO()
 
3617
        result = tests.TextTestResult(output, 0, 1)
 
3618
        suite.run(result)
 
3619
        return result, output
 
3620
 
 
3621
    def assertDocTestStringSucceds(self, klass, string):
 
3622
        result, output = self.run_doctest_suite_for_string(klass, string)
 
3623
        if not result.wasStrictlySuccessful():
 
3624
            self.fail(output.getvalue())
 
3625
 
 
3626
    def assertDocTestStringFails(self, klass, string):
 
3627
        result, output = self.run_doctest_suite_for_string(klass, string)
 
3628
        if result.wasStrictlySuccessful():
 
3629
            self.fail(output.getvalue())
 
3630
 
 
3631
    def test_injected_variable(self):
 
3632
        self.overrideAttr(tests, 'isolated_environ', {'LINES': '42'})
 
3633
        test = """
 
3634
            >>> import os
 
3635
            >>> os.environ['LINES']
 
3636
            '42'
 
3637
            """
 
3638
        # doctest.DocTestSuite fails as it sees '25'
 
3639
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
 
3640
        # tests.DocTestSuite sees '42'
 
3641
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
 
3642
 
 
3643
    def test_deleted_variable(self):
 
3644
        self.overrideAttr(tests, 'isolated_environ', {'LINES': None})
 
3645
        test = """
 
3646
            >>> import os
 
3647
            >>> os.environ.get('LINES')
 
3648
            """
 
3649
        # doctest.DocTestSuite fails as it sees '25'
 
3650
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
 
3651
        # tests.DocTestSuite sees None
 
3652
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
 
3653
 
 
3654
 
 
3655
class TestSelftestExcludePatterns(tests.TestCase):
 
3656
 
 
3657
    def setUp(self):
 
3658
        super(TestSelftestExcludePatterns, self).setUp()
 
3659
        self.overrideAttr(tests, 'test_suite', self.suite_factory)
 
3660
 
 
3661
    def suite_factory(self, keep_only=None, starting_with=None):
 
3662
        """A test suite factory with only a few tests."""
 
3663
        class Test(tests.TestCase):
 
3664
            def id(self):
 
3665
                # We don't need the full class path
 
3666
                return self._testMethodName
 
3667
            def a(self):
 
3668
                pass
 
3669
            def b(self):
 
3670
                pass
 
3671
            def c(self):
 
3672
                pass
 
3673
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
 
3674
 
 
3675
    def assertTestList(self, expected, *selftest_args):
 
3676
        # We rely on setUp installing the right test suite factory so we can
 
3677
        # test at the command level without loading the whole test suite
 
3678
        out, err = self.run_bzr(('selftest', '--list') + selftest_args)
 
3679
        actual = out.splitlines()
 
3680
        self.assertEquals(expected, actual)
 
3681
 
 
3682
    def test_full_list(self):
 
3683
        self.assertTestList(['a', 'b', 'c'])
 
3684
 
 
3685
    def test_single_exclude(self):
 
3686
        self.assertTestList(['b', 'c'], '-x', 'a')
 
3687
 
 
3688
    def test_mutiple_excludes(self):
 
3689
        self.assertTestList(['c'], '-x', 'a', '-x', 'b')
 
3690
 
 
3691
 
 
3692
class TestCounterHooks(tests.TestCase, SelfTestHelper):
 
3693
 
 
3694
    _test_needs_features = [features.subunit]
 
3695
 
 
3696
    def setUp(self):
 
3697
        super(TestCounterHooks, self).setUp()
 
3698
        class Test(tests.TestCase):
 
3699
 
 
3700
            def setUp(self):
 
3701
                super(Test, self).setUp()
 
3702
                self.hooks = hooks.Hooks()
 
3703
                self.hooks.add_hook('myhook', 'Foo bar blah', (2,4))
 
3704
                self.install_counter_hook(self.hooks, 'myhook')
 
3705
 
 
3706
            def no_hook(self):
 
3707
                pass
 
3708
 
 
3709
            def run_hook_once(self):
 
3710
                for hook in self.hooks['myhook']:
 
3711
                    hook(self)
 
3712
 
 
3713
        self.test_class = Test
 
3714
 
 
3715
    def assertHookCalls(self, expected_calls, test_name):
 
3716
        test = self.test_class(test_name)
 
3717
        result = unittest.TestResult()
 
3718
        test.run(result)
 
3719
        self.assertTrue(hasattr(test, '_counters'))
 
3720
        self.assertTrue(test._counters.has_key('myhook'))
 
3721
        self.assertEquals(expected_calls, test._counters['myhook'])
 
3722
 
 
3723
    def test_no_hook(self):
 
3724
        self.assertHookCalls(0, 'no_hook')
 
3725
 
 
3726
    def test_run_hook_once(self):
 
3727
        tt = features.testtools
 
3728
        if tt.module.__version__ < (0, 9, 8):
 
3729
            raise tests.TestSkipped('testtools-0.9.8 required for addDetail')
 
3730
        self.assertHookCalls(1, 'run_hook_once')