~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-12-09 02:53:42 UTC
  • mfrom: (4873.2.3 2.1.0b4-win32-test-imports)
  • Revision ID: pqm@pqm.ubuntu.com-20091209025342-sidvxfcqdgxmuz59
(jam) Get the test suite running again on Windows, (bug #492561)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
"""Tests for the test framework."""
18
18
 
19
19
from cStringIO import StringIO
20
 
import doctest
21
20
import os
22
21
import signal
23
22
import sys
24
 
import threading
25
23
import time
26
24
import unittest
27
25
import warnings
28
26
 
29
 
from testtools import (
30
 
    ExtendedToOriginalDecorator,
31
 
    MultiTestResult,
32
 
    __version__ as testtools_version,
33
 
    )
34
 
from testtools.content import Content
35
 
from testtools.content_type import ContentType
36
 
from testtools.matchers import (
37
 
    DocTestMatches,
38
 
    Equals,
39
 
    )
40
 
import testtools.testresult.doubles
41
 
 
42
27
import bzrlib
43
28
from bzrlib import (
44
29
    branchbuilder,
45
30
    bzrdir,
 
31
    debug,
46
32
    errors,
47
 
    hooks,
48
33
    lockdir,
49
34
    memorytree,
50
35
    osutils,
 
36
    progress,
51
37
    remote,
52
38
    repository,
53
39
    symbol_versioning,
54
40
    tests,
55
41
    transport,
56
42
    workingtree,
57
 
    workingtree_3,
58
 
    workingtree_4,
59
43
    )
60
44
from bzrlib.repofmt import (
61
45
    groupcompress_repo,
 
46
    pack_repo,
 
47
    weaverepo,
62
48
    )
63
49
from bzrlib.symbol_versioning import (
64
50
    deprecated_function,
66
52
    deprecated_method,
67
53
    )
68
54
from bzrlib.tests import (
69
 
    features,
 
55
    SubUnitFeature,
70
56
    test_lsprof,
71
 
    test_server,
 
57
    test_sftp_transport,
72
58
    TestUtil,
73
59
    )
74
 
from bzrlib.trace import note, mutter
75
 
from bzrlib.transport import memory
 
60
from bzrlib.trace import note
 
61
from bzrlib.transport.memory import MemoryServer, MemoryTransport
 
62
from bzrlib.version import _get_bzr_source_tree
76
63
 
77
64
 
78
65
def _test_ids(test_suite):
80
67
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
81
68
 
82
69
 
 
70
class SelftestTests(tests.TestCase):
 
71
 
 
72
    def test_import_tests(self):
 
73
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
 
74
        self.assertEqual(mod.SelftestTests, SelftestTests)
 
75
 
 
76
    def test_import_test_failure(self):
 
77
        self.assertRaises(ImportError,
 
78
                          TestUtil._load_module_by_name,
 
79
                          'bzrlib.no-name-yet')
 
80
 
83
81
class MetaTestLog(tests.TestCase):
84
82
 
85
83
    def test_logging(self):
86
84
        """Test logs are captured when a test fails."""
87
85
        self.log('a test message')
88
 
        details = self.getDetails()
89
 
        log = details['log']
90
 
        self.assertThat(log.content_type, Equals(ContentType(
91
 
            "text", "plain", {"charset": "utf8"})))
92
 
        self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
93
 
        self.assertThat(self.get_log(),
94
 
            DocTestMatches(u"...a test message\n", doctest.ELLIPSIS))
 
86
        self._log_file.flush()
 
87
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
88
                              'a test message\n')
 
89
 
 
90
 
 
91
class TestUnicodeFilename(tests.TestCase):
 
92
 
 
93
    def test_probe_passes(self):
 
94
        """UnicodeFilename._probe passes."""
 
95
        # We can't test much more than that because the behaviour depends
 
96
        # on the platform.
 
97
        tests.UnicodeFilename._probe()
95
98
 
96
99
 
97
100
class TestTreeShape(tests.TestCaseInTempDir):
98
101
 
99
102
    def test_unicode_paths(self):
100
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
103
        self.requireFeature(tests.UnicodeFilename)
101
104
 
102
105
        filename = u'hell\u00d8'
103
106
        self.build_tree_contents([(filename, 'contents of hello')])
104
 
        self.assertPathExists(filename)
105
 
 
106
 
 
107
 
class TestClassesAvailable(tests.TestCase):
108
 
    """As a convenience we expose Test* classes from bzrlib.tests"""
109
 
 
110
 
    def test_test_case(self):
111
 
        from bzrlib.tests import TestCase
112
 
 
113
 
    def test_test_loader(self):
114
 
        from bzrlib.tests import TestLoader
115
 
 
116
 
    def test_test_suite(self):
117
 
        from bzrlib.tests import TestSuite
 
107
        self.failUnlessExists(filename)
118
108
 
119
109
 
120
110
class TestTransportScenarios(tests.TestCase):
203
193
    def test_scenarios(self):
204
194
        # check that constructor parameters are passed through to the adapted
205
195
        # test.
206
 
        from bzrlib.tests.per_controldir import make_scenarios
 
196
        from bzrlib.tests.per_bzrdir import make_scenarios
207
197
        vfs_factory = "v"
208
198
        server1 = "a"
209
199
        server2 = "b"
307
297
        from bzrlib.tests.per_interrepository import make_scenarios
308
298
        server1 = "a"
309
299
        server2 = "b"
310
 
        formats = [("C0", "C1", "C2", "C3"), ("D0", "D1", "D2", "D3")]
 
300
        formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
311
301
        scenarios = make_scenarios(server1, server2, formats)
312
302
        self.assertEqual([
313
303
            ('C0,str,str',
314
304
             {'repository_format': 'C1',
315
305
              'repository_format_to': 'C2',
316
306
              'transport_readonly_server': 'b',
317
 
              'transport_server': 'a',
318
 
              'extra_setup': 'C3'}),
 
307
              'transport_server': 'a'}),
319
308
            ('D0,str,str',
320
309
             {'repository_format': 'D1',
321
310
              'repository_format_to': 'D2',
322
311
              'transport_readonly_server': 'b',
323
 
              'transport_server': 'a',
324
 
              'extra_setup': 'D3'})],
 
312
              'transport_server': 'a'})],
325
313
            scenarios)
326
314
 
327
315
 
333
321
        from bzrlib.tests.per_workingtree import make_scenarios
334
322
        server1 = "a"
335
323
        server2 = "b"
336
 
        formats = [workingtree_4.WorkingTreeFormat4(),
337
 
                   workingtree_3.WorkingTreeFormat3(),]
 
324
        formats = [workingtree.WorkingTreeFormat2(),
 
325
                   workingtree.WorkingTreeFormat3(),]
338
326
        scenarios = make_scenarios(server1, server2, formats)
339
327
        self.assertEqual([
340
 
            ('WorkingTreeFormat4',
 
328
            ('WorkingTreeFormat2',
341
329
             {'bzrdir_format': formats[0]._matchingbzrdir,
342
330
              'transport_readonly_server': 'b',
343
331
              'transport_server': 'a',
370
358
            )
371
359
        server1 = "a"
372
360
        server2 = "b"
373
 
        formats = [workingtree_4.WorkingTreeFormat4(),
374
 
                   workingtree_3.WorkingTreeFormat3(),]
 
361
        formats = [workingtree.WorkingTreeFormat2(),
 
362
                   workingtree.WorkingTreeFormat3(),]
375
363
        scenarios = make_scenarios(server1, server2, formats)
376
364
        self.assertEqual(7, len(scenarios))
377
 
        default_wt_format = workingtree.format_registry.get_default()
378
 
        wt4_format = workingtree_4.WorkingTreeFormat4()
379
 
        wt5_format = workingtree_4.WorkingTreeFormat5()
 
365
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
 
366
        wt4_format = workingtree.WorkingTreeFormat4()
 
367
        wt5_format = workingtree.WorkingTreeFormat5()
380
368
        expected_scenarios = [
381
 
            ('WorkingTreeFormat4',
 
369
            ('WorkingTreeFormat2',
382
370
             {'bzrdir_format': formats[0]._matchingbzrdir,
383
371
              'transport_readonly_server': 'b',
384
372
              'transport_server': 'a',
444
432
        # ones to add.
445
433
        from bzrlib.tests.per_tree import (
446
434
            return_parameter,
 
435
            revision_tree_from_workingtree
447
436
            )
448
437
        from bzrlib.tests.per_intertree import (
449
438
            make_scenarios,
450
439
            )
451
 
        from bzrlib.workingtree_3 import WorkingTreeFormat3
452
 
        from bzrlib.workingtree_4 import WorkingTreeFormat4
 
440
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
453
441
        input_test = TestInterTreeScenarios(
454
442
            "test_scenarios")
455
443
        server1 = "a"
456
444
        server2 = "b"
457
 
        format1 = WorkingTreeFormat4()
 
445
        format1 = WorkingTreeFormat2()
458
446
        format2 = WorkingTreeFormat3()
459
447
        formats = [("1", str, format1, format2, "converter1"),
460
448
            ("2", int, format2, format1, "converter2")]
506
494
        self.assertRaises(AssertionError, self.assertEqualStat,
507
495
            os.lstat("foo"), os.lstat("longname"))
508
496
 
509
 
    def test_failUnlessExists(self):
510
 
        """Deprecated failUnlessExists and failIfExists"""
511
 
        self.applyDeprecated(
512
 
            deprecated_in((2, 4)),
513
 
            self.failUnlessExists, '.')
514
 
        self.build_tree(['foo/', 'foo/bar'])
515
 
        self.applyDeprecated(
516
 
            deprecated_in((2, 4)),
517
 
            self.failUnlessExists, 'foo/bar')
518
 
        self.applyDeprecated(
519
 
            deprecated_in((2, 4)),
520
 
            self.failIfExists, 'foo/foo')
521
 
 
522
 
    def test_assertPathExists(self):
523
 
        self.assertPathExists('.')
524
 
        self.build_tree(['foo/', 'foo/bar'])
525
 
        self.assertPathExists('foo/bar')
526
 
        self.assertPathDoesNotExist('foo/foo')
527
 
 
528
497
 
529
498
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
530
499
 
564
533
        tree = self.make_branch_and_memory_tree('dir')
565
534
        # Guard against regression into MemoryTransport leaking
566
535
        # files to disk instead of keeping them in memory.
567
 
        self.assertFalse(osutils.lexists('dir'))
 
536
        self.failIf(osutils.lexists('dir'))
568
537
        self.assertIsInstance(tree, memorytree.MemoryTree)
569
538
 
570
539
    def test_make_branch_and_memory_tree_with_format(self):
571
540
        """make_branch_and_memory_tree should accept a format option."""
572
541
        format = bzrdir.BzrDirMetaFormat1()
573
 
        format.repository_format = repository.format_registry.get_default()
 
542
        format.repository_format = weaverepo.RepositoryFormat7()
574
543
        tree = self.make_branch_and_memory_tree('dir', format=format)
575
544
        # Guard against regression into MemoryTransport leaking
576
545
        # files to disk instead of keeping them in memory.
577
 
        self.assertFalse(osutils.lexists('dir'))
 
546
        self.failIf(osutils.lexists('dir'))
578
547
        self.assertIsInstance(tree, memorytree.MemoryTree)
579
548
        self.assertEqual(format.repository_format.__class__,
580
549
            tree.branch.repository._format.__class__)
584
553
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
585
554
        # Guard against regression into MemoryTransport leaking
586
555
        # files to disk instead of keeping them in memory.
587
 
        self.assertFalse(osutils.lexists('dir'))
 
556
        self.failIf(osutils.lexists('dir'))
588
557
 
589
558
    def test_make_branch_builder_with_format(self):
590
559
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
591
560
        # that the format objects are used.
592
561
        format = bzrdir.BzrDirMetaFormat1()
593
 
        repo_format = repository.format_registry.get_default()
 
562
        repo_format = weaverepo.RepositoryFormat7()
594
563
        format.repository_format = repo_format
595
564
        builder = self.make_branch_builder('dir', format=format)
596
565
        the_branch = builder.get_branch()
597
566
        # Guard against regression into MemoryTransport leaking
598
567
        # files to disk instead of keeping them in memory.
599
 
        self.assertFalse(osutils.lexists('dir'))
 
568
        self.failIf(osutils.lexists('dir'))
600
569
        self.assertEqual(format.repository_format.__class__,
601
570
                         the_branch.repository._format.__class__)
602
571
        self.assertEqual(repo_format.get_format_string(),
608
577
        the_branch = builder.get_branch()
609
578
        # Guard against regression into MemoryTransport leaking
610
579
        # files to disk instead of keeping them in memory.
611
 
        self.assertFalse(osutils.lexists('dir'))
 
580
        self.failIf(osutils.lexists('dir'))
612
581
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
613
582
        self.assertEqual(dir_format.repository_format.__class__,
614
583
                         the_branch.repository._format.__class__)
619
588
    def test_dangling_locks_cause_failures(self):
620
589
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
621
590
            def test_function(self):
622
 
                t = self.get_transport_from_path('.')
 
591
                t = self.get_transport('.')
623
592
                l = lockdir.LockDir(t, 'lock')
624
593
                l.create()
625
594
                l.attempt_lock()
626
595
        test = TestDanglingLock('test_function')
627
596
        result = test.run()
628
 
        total_failures = result.errors + result.failures
629
597
        if self._lock_check_thorough:
630
 
            self.assertEqual(1, len(total_failures))
 
598
            self.assertEqual(1, len(result.errors))
631
599
        else:
632
600
            # When _lock_check_thorough is disabled, then we don't trigger a
633
601
            # failure
634
 
            self.assertEqual(0, len(total_failures))
 
602
            self.assertEqual(0, len(result.errors))
635
603
 
636
604
 
637
605
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
638
606
    """Tests for the convenience functions TestCaseWithTransport introduces."""
639
607
 
640
608
    def test_get_readonly_url_none(self):
 
609
        from bzrlib.transport import get_transport
 
610
        from bzrlib.transport.memory import MemoryServer
641
611
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
642
 
        self.vfs_transport_factory = memory.MemoryServer
 
612
        self.vfs_transport_factory = MemoryServer
643
613
        self.transport_readonly_server = None
644
614
        # calling get_readonly_transport() constructs a decorator on the url
645
615
        # for the server
646
616
        url = self.get_readonly_url()
647
617
        url2 = self.get_readonly_url('foo/bar')
648
 
        t = transport.get_transport_from_url(url)
649
 
        t2 = transport.get_transport_from_url(url2)
650
 
        self.assertIsInstance(t, ReadonlyTransportDecorator)
651
 
        self.assertIsInstance(t2, ReadonlyTransportDecorator)
 
618
        t = get_transport(url)
 
619
        t2 = get_transport(url2)
 
620
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
 
621
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
652
622
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
653
623
 
654
624
    def test_get_readonly_url_http(self):
655
625
        from bzrlib.tests.http_server import HttpServer
 
626
        from bzrlib.transport import get_transport
 
627
        from bzrlib.transport.local import LocalURLServer
656
628
        from bzrlib.transport.http import HttpTransportBase
657
 
        self.transport_server = test_server.LocalURLServer
 
629
        self.transport_server = LocalURLServer
658
630
        self.transport_readonly_server = HttpServer
659
631
        # calling get_readonly_transport() gives us a HTTP server instance.
660
632
        url = self.get_readonly_url()
661
633
        url2 = self.get_readonly_url('foo/bar')
662
634
        # the transport returned may be any HttpTransportBase subclass
663
 
        t = transport.get_transport_from_url(url)
664
 
        t2 = transport.get_transport_from_url(url2)
665
 
        self.assertIsInstance(t, HttpTransportBase)
666
 
        self.assertIsInstance(t2, HttpTransportBase)
 
635
        t = get_transport(url)
 
636
        t2 = get_transport(url2)
 
637
        self.failUnless(isinstance(t, HttpTransportBase))
 
638
        self.failUnless(isinstance(t2, HttpTransportBase))
667
639
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
668
640
 
669
641
    def test_is_directory(self):
677
649
    def test_make_branch_builder(self):
678
650
        builder = self.make_branch_builder('dir')
679
651
        rev_id = builder.build_commit()
680
 
        self.assertPathExists('dir')
 
652
        self.failUnlessExists('dir')
681
653
        a_dir = bzrdir.BzrDir.open('dir')
682
654
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
683
655
        a_branch = a_dir.open_branch()
691
663
 
692
664
    def setUp(self):
693
665
        super(TestTestCaseTransports, self).setUp()
694
 
        self.vfs_transport_factory = memory.MemoryServer
 
666
        self.vfs_transport_factory = MemoryServer
695
667
 
696
668
    def test_make_bzrdir_preserves_transport(self):
697
669
        t = self.get_transport()
698
670
        result_bzrdir = self.make_bzrdir('subdir')
699
671
        self.assertIsInstance(result_bzrdir.transport,
700
 
                              memory.MemoryTransport)
 
672
                              MemoryTransport)
701
673
        # should not be on disk, should only be in memory
702
 
        self.assertPathDoesNotExist('subdir')
 
674
        self.failIfExists('subdir')
703
675
 
704
676
 
705
677
class TestChrootedTest(tests.ChrootedTestCase):
706
678
 
707
679
    def test_root_is_root(self):
708
 
        t = transport.get_transport_from_url(self.get_readonly_url())
 
680
        from bzrlib.transport import get_transport
 
681
        t = get_transport(self.get_readonly_url())
709
682
        url = t.base
710
683
        self.assertEqual(url, t.clone('..').base)
711
684
 
713
686
class TestProfileResult(tests.TestCase):
714
687
 
715
688
    def test_profiles_tests(self):
716
 
        self.requireFeature(features.lsprof_feature)
717
 
        terminal = testtools.testresult.doubles.ExtendedTestResult()
 
689
        self.requireFeature(test_lsprof.LSProfFeature)
 
690
        terminal = unittest.TestResult()
718
691
        result = tests.ProfileResult(terminal)
719
692
        class Sample(tests.TestCase):
720
693
            def a(self):
722
695
            def sample_function(self):
723
696
                pass
724
697
        test = Sample("a")
 
698
        test.attrs_to_keep = test.attrs_to_keep + ('_benchcalls',)
725
699
        test.run(result)
726
 
        case = terminal._events[0][1]
727
 
        self.assertLength(1, case._benchcalls)
 
700
        self.assertLength(1, test._benchcalls)
728
701
        # We must be able to unpack it as the test reporting code wants
729
 
        (_, _, _), stats = case._benchcalls[0]
 
702
        (_, _, _), stats = test._benchcalls[0]
730
703
        self.assertTrue(callable(stats.pprint))
731
704
 
732
705
 
737
710
                descriptions=0,
738
711
                verbosity=1,
739
712
                )
740
 
        capture = testtools.testresult.doubles.ExtendedTestResult()
741
 
        test_case.run(MultiTestResult(result, capture))
742
 
        run_case = capture._events[0][1]
743
 
        timed_string = result._testTimeString(run_case)
 
713
        test_case.run(result)
 
714
        timed_string = result._testTimeString(test_case)
744
715
        self.assertContainsRe(timed_string, expected_re)
745
716
 
746
717
    def test_test_reporting(self):
764
735
        self.check_timing(ShortDelayTestCase('test_short_delay'),
765
736
                          r"^ +[0-9]+ms$")
766
737
 
 
738
    def _patch_get_bzr_source_tree(self):
 
739
        # Reading from the actual source tree breaks isolation, but we don't
 
740
        # want to assume that thats *all* that would happen.
 
741
        def _get_bzr_source_tree():
 
742
            return None
 
743
        orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
 
744
        bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
 
745
        def restore():
 
746
            bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
 
747
        self.addCleanup(restore)
 
748
 
 
749
    def test_assigned_benchmark_file_stores_date(self):
 
750
        self._patch_get_bzr_source_tree()
 
751
        output = StringIO()
 
752
        result = bzrlib.tests.TextTestResult(self._log_file,
 
753
                                        descriptions=0,
 
754
                                        verbosity=1,
 
755
                                        bench_history=output
 
756
                                        )
 
757
        output_string = output.getvalue()
 
758
        # if you are wondering about the regexp please read the comment in
 
759
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
760
        # XXX: what comment?  -- Andrew Bennetts
 
761
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
762
 
 
763
    def test_benchhistory_records_test_times(self):
 
764
        self._patch_get_bzr_source_tree()
 
765
        result_stream = StringIO()
 
766
        result = bzrlib.tests.TextTestResult(
 
767
            self._log_file,
 
768
            descriptions=0,
 
769
            verbosity=1,
 
770
            bench_history=result_stream
 
771
            )
 
772
 
 
773
        # we want profile a call and check that its test duration is recorded
 
774
        # make a new test instance that when run will generate a benchmark
 
775
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
776
        # execute the test, which should succeed and record times
 
777
        example_test_case.run(result)
 
778
        lines = result_stream.getvalue().splitlines()
 
779
        self.assertEqual(2, len(lines))
 
780
        self.assertContainsRe(lines[1],
 
781
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
782
            "._time_hello_world_encoding")
 
783
 
767
784
    def _time_hello_world_encoding(self):
768
785
        """Profile two sleep calls
769
786
 
774
791
 
775
792
    def test_lsprofiling(self):
776
793
        """Verbose test result prints lsprof statistics from test cases."""
777
 
        self.requireFeature(features.lsprof_feature)
 
794
        self.requireFeature(test_lsprof.LSProfFeature)
778
795
        result_stream = StringIO()
779
796
        result = bzrlib.tests.VerboseTestResult(
780
 
            result_stream,
 
797
            unittest._WritelnDecorator(result_stream),
781
798
            descriptions=0,
782
799
            verbosity=2,
783
800
            )
809
826
        self.assertContainsRe(output,
810
827
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
811
828
 
812
 
    def test_uses_time_from_testtools(self):
813
 
        """Test case timings in verbose results should use testtools times"""
814
 
        import datetime
815
 
        class TimeAddedVerboseTestResult(tests.VerboseTestResult):
816
 
            def startTest(self, test):
817
 
                self.time(datetime.datetime.utcfromtimestamp(1.145))
818
 
                super(TimeAddedVerboseTestResult, self).startTest(test)
819
 
            def addSuccess(self, test):
820
 
                self.time(datetime.datetime.utcfromtimestamp(51.147))
821
 
                super(TimeAddedVerboseTestResult, self).addSuccess(test)
822
 
            def report_tests_starting(self): pass
823
 
        sio = StringIO()
824
 
        self.get_passing_test().run(TimeAddedVerboseTestResult(sio, 0, 2))
825
 
        self.assertEndsWith(sio.getvalue(), "OK    50002ms\n")
826
 
 
827
829
    def test_known_failure(self):
828
 
        """Using knownFailure should trigger several result actions."""
 
830
        """A KnownFailure being raised should trigger several result actions."""
829
831
        class InstrumentedTestResult(tests.ExtendedTestResult):
830
832
            def stopTestRun(self): pass
831
 
            def report_tests_starting(self): pass
832
 
            def report_known_failure(self, test, err=None, details=None):
833
 
                self._call = test, 'known failure'
 
833
            def startTests(self): pass
 
834
            def report_test_start(self, test): pass
 
835
            def report_known_failure(self, test, err):
 
836
                self._call = test, err
834
837
        result = InstrumentedTestResult(None, None, None, None)
835
838
        class Test(tests.TestCase):
836
839
            def test_function(self):
837
 
                self.knownFailure('failed!')
 
840
                raise tests.KnownFailure('failed!')
838
841
        test = Test("test_function")
839
842
        test.run(result)
840
843
        # it should invoke 'report_known_failure'.
841
844
        self.assertEqual(2, len(result._call))
842
 
        self.assertEqual(test.id(), result._call[0].id())
843
 
        self.assertEqual('known failure', result._call[1])
 
845
        self.assertEqual(test, result._call[0])
 
846
        self.assertEqual(tests.KnownFailure, result._call[1][0])
 
847
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
844
848
        # we dont introspec the traceback, if the rest is ok, it would be
845
849
        # exceptional for it not to be.
846
850
        # it should update the known_failure_count on the object.
852
856
        # verbose test output formatting
853
857
        result_stream = StringIO()
854
858
        result = bzrlib.tests.VerboseTestResult(
855
 
            result_stream,
 
859
            unittest._WritelnDecorator(result_stream),
856
860
            descriptions=0,
857
861
            verbosity=2,
858
862
            )
859
 
        _get_test("test_xfail").run(result)
860
 
        self.assertContainsRe(result_stream.getvalue(),
861
 
            "\n\\S+\\.test_xfail\\s+XFAIL\\s+\\d+ms\n"
862
 
            "\\s*(?:Text attachment: )?reason"
863
 
            "(?:\n-+\n|: {{{)"
864
 
            "this_fails"
865
 
            "(?:\n-+\n|}}}\n)")
 
863
        test = self.get_passing_test()
 
864
        result.startTest(test)
 
865
        prefix = len(result_stream.getvalue())
 
866
        # the err parameter has the shape:
 
867
        # (class, exception object, traceback)
 
868
        # KnownFailures dont get their tracebacks shown though, so we
 
869
        # can skip that.
 
870
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
871
        result.report_known_failure(test, err)
 
872
        output = result_stream.getvalue()[prefix:]
 
873
        lines = output.splitlines()
 
874
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
 
875
        self.assertEqual(lines[1], '    foo')
 
876
        self.assertEqual(2, len(lines))
866
877
 
867
878
    def get_passing_test(self):
868
879
        """Return a test object that can't be run usefully."""
874
885
        """Test the behaviour of invoking addNotSupported."""
875
886
        class InstrumentedTestResult(tests.ExtendedTestResult):
876
887
            def stopTestRun(self): pass
877
 
            def report_tests_starting(self): pass
 
888
            def startTests(self): pass
 
889
            def report_test_start(self, test): pass
878
890
            def report_unsupported(self, test, feature):
879
891
                self._call = test, feature
880
892
        result = InstrumentedTestResult(None, None, None, None)
881
893
        test = SampleTestCase('_test_pass')
882
 
        feature = features.Feature()
 
894
        feature = tests.Feature()
883
895
        result.startTest(test)
884
896
        result.addNotSupported(test, feature)
885
897
        # it should invoke 'report_unsupported'.
899
911
        # verbose test output formatting
900
912
        result_stream = StringIO()
901
913
        result = bzrlib.tests.VerboseTestResult(
902
 
            result_stream,
 
914
            unittest._WritelnDecorator(result_stream),
903
915
            descriptions=0,
904
916
            verbosity=2,
905
917
            )
906
918
        test = self.get_passing_test()
907
 
        feature = features.Feature()
 
919
        feature = tests.Feature()
908
920
        result.startTest(test)
909
921
        prefix = len(result_stream.getvalue())
910
922
        result.report_unsupported(test, feature)
919
931
        """An UnavailableFeature being raised should invoke addNotSupported."""
920
932
        class InstrumentedTestResult(tests.ExtendedTestResult):
921
933
            def stopTestRun(self): pass
922
 
            def report_tests_starting(self): pass
 
934
            def startTests(self): pass
 
935
            def report_test_start(self, test): pass
923
936
            def addNotSupported(self, test, feature):
924
937
                self._call = test, feature
925
938
        result = InstrumentedTestResult(None, None, None, None)
926
 
        feature = features.Feature()
 
939
        feature = tests.Feature()
927
940
        class Test(tests.TestCase):
928
941
            def test_function(self):
929
942
                raise tests.UnavailableFeature(feature)
931
944
        test.run(result)
932
945
        # it should invoke 'addNotSupported'.
933
946
        self.assertEqual(2, len(result._call))
934
 
        self.assertEqual(test.id(), result._call[0].id())
 
947
        self.assertEqual(test, result._call[0])
935
948
        self.assertEqual(feature, result._call[1])
936
949
        # and not count as an error
937
950
        self.assertEqual(0, result.error_count)
948
961
    def test_strict_with_known_failure(self):
949
962
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
950
963
                                             verbosity=1)
951
 
        test = _get_test("test_xfail")
952
 
        test.run(result)
 
964
        test = self.get_passing_test()
 
965
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
966
        result.addExpectedFailure(test, err)
953
967
        self.assertFalse(result.wasStrictlySuccessful())
954
968
        self.assertEqual(None, result._extractBenchmarkTime(test))
955
969
 
966
980
        class InstrumentedTestResult(tests.ExtendedTestResult):
967
981
            calls = 0
968
982
            def startTests(self): self.calls += 1
 
983
            def report_test_start(self, test): pass
969
984
        result = InstrumentedTestResult(None, None, None, None)
970
985
        def test_function():
971
986
            pass
973
988
        test.run(result)
974
989
        self.assertEquals(1, result.calls)
975
990
 
976
 
    def test_startTests_only_once(self):
977
 
        """With multiple tests startTests should still only be called once"""
978
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
979
 
            calls = 0
980
 
            def startTests(self): self.calls += 1
981
 
        result = InstrumentedTestResult(None, None, None, None)
982
 
        suite = unittest.TestSuite([
983
 
            unittest.FunctionTestCase(lambda: None),
984
 
            unittest.FunctionTestCase(lambda: None)])
985
 
        suite.run(result)
986
 
        self.assertEquals(1, result.calls)
987
 
        self.assertEquals(2, result.count)
 
991
 
 
992
class TestUnicodeFilenameFeature(tests.TestCase):
 
993
 
 
994
    def test_probe_passes(self):
 
995
        """UnicodeFilenameFeature._probe passes."""
 
996
        # We can't test much more than that because the behaviour depends
 
997
        # on the platform.
 
998
        tests.UnicodeFilenameFeature._probe()
988
999
 
989
1000
 
990
1001
class TestRunner(tests.TestCase):
1003
1014
        because of our use of global state.
1004
1015
        """
1005
1016
        old_root = tests.TestCaseInTempDir.TEST_ROOT
 
1017
        old_leak = tests.TestCase._first_thread_leaker_id
1006
1018
        try:
1007
1019
            tests.TestCaseInTempDir.TEST_ROOT = None
 
1020
            tests.TestCase._first_thread_leaker_id = None
1008
1021
            return testrunner.run(test)
1009
1022
        finally:
1010
1023
            tests.TestCaseInTempDir.TEST_ROOT = old_root
 
1024
            tests.TestCase._first_thread_leaker_id = old_leak
1011
1025
 
1012
1026
    def test_known_failure_failed_run(self):
1013
1027
        # run a test that generates a known failure which should be printed in
1014
1028
        # the final output when real failures occur.
1015
1029
        class Test(tests.TestCase):
1016
1030
            def known_failure_test(self):
1017
 
                self.expectFailure('failed', self.assertTrue, False)
 
1031
                raise tests.KnownFailure('failed')
1018
1032
        test = unittest.TestSuite()
1019
1033
        test.addTest(Test("known_failure_test"))
1020
1034
        def failing_test():
1025
1039
        result = self.run_test_runner(runner, test)
1026
1040
        lines = stream.getvalue().splitlines()
1027
1041
        self.assertContainsRe(stream.getvalue(),
1028
 
            '(?sm)^bzr selftest.*$'
 
1042
            '(?sm)^testing.*$'
1029
1043
            '.*'
1030
1044
            '^======================================================================\n'
1031
 
            '^FAIL: failing_test\n'
 
1045
            '^FAIL: unittest.FunctionTestCase \\(failing_test\\)\n'
1032
1046
            '^----------------------------------------------------------------------\n'
1033
1047
            'Traceback \\(most recent call last\\):\n'
1034
1048
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1044
1058
        # the final output.
1045
1059
        class Test(tests.TestCase):
1046
1060
            def known_failure_test(self):
1047
 
                self.knownFailure("Never works...")
 
1061
                raise tests.KnownFailure('failed')
1048
1062
        test = Test("known_failure_test")
1049
1063
        stream = StringIO()
1050
1064
        runner = tests.TextTestRunner(stream=stream)
1056
1070
            '\n'
1057
1071
            'OK \\(known_failures=1\\)\n')
1058
1072
 
1059
 
    def test_unexpected_success_bad(self):
1060
 
        class Test(tests.TestCase):
1061
 
            def test_truth(self):
1062
 
                self.expectFailure("No absolute truth", self.assertTrue, True)
1063
 
        runner = tests.TextTestRunner(stream=StringIO())
1064
 
        result = self.run_test_runner(runner, Test("test_truth"))
1065
 
        if testtools_version[:3] <= (0, 9, 11):
1066
 
            self.assertContainsRe(runner.stream.getvalue(),
1067
 
                "=+\n"
1068
 
                "FAIL: \\S+\.test_truth\n"
1069
 
                "-+\n"
1070
 
                "(?:.*\n)*"
1071
 
                "No absolute truth\n"
1072
 
                "(?:.*\n)*"
1073
 
                "-+\n"
1074
 
                "Ran 1 test in .*\n"
1075
 
                "\n"
1076
 
                "FAILED \\(failures=1\\)\n\\Z")
1077
 
        else:
1078
 
            self.assertContainsRe(runner.stream.getvalue(),
1079
 
                "=+\n"
1080
 
                "FAIL: \\S+\.test_truth\n"
1081
 
                "-+\n"
1082
 
                "Empty attachments:\n"
1083
 
                "  log\n"
1084
 
                "\n"
1085
 
                "reason: {{{No absolute truth}}}\n"
1086
 
                "-+\n"
1087
 
                "Ran 1 test in .*\n"
1088
 
                "\n"
1089
 
                "FAILED \\(failures=1\\)\n\\Z")
1090
 
 
1091
1073
    def test_result_decorator(self):
1092
1074
        # decorate results
1093
1075
        calls = []
1094
 
        class LoggingDecorator(ExtendedToOriginalDecorator):
 
1076
        class LoggingDecorator(tests.ForwardingResult):
1095
1077
            def startTest(self, test):
1096
 
                ExtendedToOriginalDecorator.startTest(self, test)
 
1078
                tests.ForwardingResult.startTest(self, test)
1097
1079
                calls.append('start')
1098
1080
        test = unittest.FunctionTestCase(lambda:None)
1099
1081
        stream = StringIO()
1177
1159
 
1178
1160
    def test_unsupported_features_listed(self):
1179
1161
        """When unsupported features are encountered they are detailed."""
1180
 
        class Feature1(features.Feature):
 
1162
        class Feature1(tests.Feature):
1181
1163
            def _probe(self): return False
1182
 
        class Feature2(features.Feature):
 
1164
        class Feature2(tests.Feature):
1183
1165
            def _probe(self): return False
1184
1166
        # create sample tests
1185
1167
        test1 = SampleTestCase('_test_pass')
1200
1182
            ],
1201
1183
            lines[-3:])
1202
1184
 
1203
 
    def test_verbose_test_count(self):
1204
 
        """A verbose test run reports the right test count at the start"""
1205
 
        suite = TestUtil.TestSuite([
1206
 
            unittest.FunctionTestCase(lambda:None),
1207
 
            unittest.FunctionTestCase(lambda:None)])
1208
 
        self.assertEqual(suite.countTestCases(), 2)
1209
 
        stream = StringIO()
1210
 
        runner = tests.TextTestRunner(stream=stream, verbosity=2)
1211
 
        # Need to use the CountingDecorator as that's what sets num_tests
1212
 
        result = self.run_test_runner(runner, tests.CountingDecorator(suite))
1213
 
        self.assertStartsWith(stream.getvalue(), "running 2 tests")
 
1185
    def _patch_get_bzr_source_tree(self):
 
1186
        # Reading from the actual source tree breaks isolation, but we don't
 
1187
        # want to assume that thats *all* that would happen.
 
1188
        self._get_source_tree_calls = []
 
1189
        def _get_bzr_source_tree():
 
1190
            self._get_source_tree_calls.append("called")
 
1191
            return None
 
1192
        orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
 
1193
        bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
 
1194
        def restore():
 
1195
            bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
 
1196
        self.addCleanup(restore)
 
1197
 
 
1198
    def test_bench_history(self):
 
1199
        # tests that the running the benchmark passes bench_history into
 
1200
        # the test result object. We can tell that happens if
 
1201
        # _get_bzr_source_tree is called.
 
1202
        self._patch_get_bzr_source_tree()
 
1203
        test = TestRunner('dummy_test')
 
1204
        output = StringIO()
 
1205
        runner = tests.TextTestRunner(stream=self._log_file,
 
1206
                                      bench_history=output)
 
1207
        result = self.run_test_runner(runner, test)
 
1208
        output_string = output.getvalue()
 
1209
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
1210
        self.assertLength(1, self._get_source_tree_calls)
 
1211
 
 
1212
    def assertLogDeleted(self, test):
 
1213
        log = test._get_log()
 
1214
        self.assertEqual("DELETED log file to reduce memory footprint", log)
 
1215
        self.assertEqual('', test._log_contents)
 
1216
        self.assertIs(None, test._log_file_name)
 
1217
 
 
1218
    def test_success_log_deleted(self):
 
1219
        """Successful tests have their log deleted"""
 
1220
 
 
1221
        class LogTester(tests.TestCase):
 
1222
 
 
1223
            def test_success(self):
 
1224
                self.log('this will be removed\n')
 
1225
 
 
1226
        sio = StringIO()
 
1227
        runner = tests.TextTestRunner(stream=sio)
 
1228
        test = LogTester('test_success')
 
1229
        result = self.run_test_runner(runner, test)
 
1230
 
 
1231
        self.assertLogDeleted(test)
 
1232
 
 
1233
    def test_skipped_log_deleted(self):
 
1234
        """Skipped tests have their log deleted"""
 
1235
 
 
1236
        class LogTester(tests.TestCase):
 
1237
 
 
1238
            def test_skipped(self):
 
1239
                self.log('this will be removed\n')
 
1240
                raise tests.TestSkipped()
 
1241
 
 
1242
        sio = StringIO()
 
1243
        runner = tests.TextTestRunner(stream=sio)
 
1244
        test = LogTester('test_skipped')
 
1245
        result = self.run_test_runner(runner, test)
 
1246
 
 
1247
        self.assertLogDeleted(test)
 
1248
 
 
1249
    def test_not_aplicable_log_deleted(self):
 
1250
        """Not applicable tests have their log deleted"""
 
1251
 
 
1252
        class LogTester(tests.TestCase):
 
1253
 
 
1254
            def test_not_applicable(self):
 
1255
                self.log('this will be removed\n')
 
1256
                raise tests.TestNotApplicable()
 
1257
 
 
1258
        sio = StringIO()
 
1259
        runner = tests.TextTestRunner(stream=sio)
 
1260
        test = LogTester('test_not_applicable')
 
1261
        result = self.run_test_runner(runner, test)
 
1262
 
 
1263
        self.assertLogDeleted(test)
 
1264
 
 
1265
    def test_known_failure_log_deleted(self):
 
1266
        """Know failure tests have their log deleted"""
 
1267
 
 
1268
        class LogTester(tests.TestCase):
 
1269
 
 
1270
            def test_known_failure(self):
 
1271
                self.log('this will be removed\n')
 
1272
                raise tests.KnownFailure()
 
1273
 
 
1274
        sio = StringIO()
 
1275
        runner = tests.TextTestRunner(stream=sio)
 
1276
        test = LogTester('test_known_failure')
 
1277
        result = self.run_test_runner(runner, test)
 
1278
 
 
1279
        self.assertLogDeleted(test)
 
1280
 
 
1281
    def test_fail_log_kept(self):
 
1282
        """Failed tests have their log kept"""
 
1283
 
 
1284
        class LogTester(tests.TestCase):
 
1285
 
 
1286
            def test_fail(self):
 
1287
                self.log('this will be kept\n')
 
1288
                self.fail('this test fails')
 
1289
 
 
1290
        sio = StringIO()
 
1291
        runner = tests.TextTestRunner(stream=sio)
 
1292
        test = LogTester('test_fail')
 
1293
        result = self.run_test_runner(runner, test)
 
1294
 
 
1295
        text = sio.getvalue()
 
1296
        self.assertContainsRe(text, 'this will be kept')
 
1297
        self.assertContainsRe(text, 'this test fails')
 
1298
 
 
1299
        log = test._get_log()
 
1300
        self.assertContainsRe(log, 'this will be kept')
 
1301
        self.assertEqual(log, test._log_contents)
 
1302
 
 
1303
    def test_error_log_kept(self):
 
1304
        """Tests with errors have their log kept"""
 
1305
 
 
1306
        class LogTester(tests.TestCase):
 
1307
 
 
1308
            def test_error(self):
 
1309
                self.log('this will be kept\n')
 
1310
                raise ValueError('random exception raised')
 
1311
 
 
1312
        sio = StringIO()
 
1313
        runner = tests.TextTestRunner(stream=sio)
 
1314
        test = LogTester('test_error')
 
1315
        result = self.run_test_runner(runner, test)
 
1316
 
 
1317
        text = sio.getvalue()
 
1318
        self.assertContainsRe(text, 'this will be kept')
 
1319
        self.assertContainsRe(text, 'random exception raised')
 
1320
 
 
1321
        log = test._get_log()
 
1322
        self.assertContainsRe(log, 'this will be kept')
 
1323
        self.assertEqual(log, test._log_contents)
1214
1324
 
1215
1325
    def test_startTestRun(self):
1216
1326
        """run should call result.startTestRun()"""
1217
1327
        calls = []
1218
 
        class LoggingDecorator(ExtendedToOriginalDecorator):
 
1328
        class LoggingDecorator(tests.ForwardingResult):
1219
1329
            def startTestRun(self):
1220
 
                ExtendedToOriginalDecorator.startTestRun(self)
 
1330
                tests.ForwardingResult.startTestRun(self)
1221
1331
                calls.append('startTestRun')
1222
1332
        test = unittest.FunctionTestCase(lambda:None)
1223
1333
        stream = StringIO()
1229
1339
    def test_stopTestRun(self):
1230
1340
        """run should call result.stopTestRun()"""
1231
1341
        calls = []
1232
 
        class LoggingDecorator(ExtendedToOriginalDecorator):
 
1342
        class LoggingDecorator(tests.ForwardingResult):
1233
1343
            def stopTestRun(self):
1234
 
                ExtendedToOriginalDecorator.stopTestRun(self)
 
1344
                tests.ForwardingResult.stopTestRun(self)
1235
1345
                calls.append('stopTestRun')
1236
1346
        test = unittest.FunctionTestCase(lambda:None)
1237
1347
        stream = StringIO()
1240
1350
        result = self.run_test_runner(runner, test)
1241
1351
        self.assertLength(1, calls)
1242
1352
 
1243
 
    def test_unicode_test_output_on_ascii_stream(self):
1244
 
        """Showing results should always succeed even on an ascii console"""
1245
 
        class FailureWithUnicode(tests.TestCase):
1246
 
            def test_log_unicode(self):
1247
 
                self.log(u"\u2606")
1248
 
                self.fail("Now print that log!")
1249
 
        out = StringIO()
1250
 
        self.overrideAttr(osutils, "get_terminal_encoding",
1251
 
            lambda trace=False: "ascii")
1252
 
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
1253
 
            FailureWithUnicode("test_log_unicode"))
1254
 
        if testtools_version[:3] > (0, 9, 11):
1255
 
            self.assertContainsRe(out.getvalue(), "log: {{{\d+\.\d+  \\\\u2606}}}")
1256
 
        else:
1257
 
            self.assertContainsRe(out.getvalue(),
1258
 
                "Text attachment: log\n"
1259
 
                "-+\n"
1260
 
                "\d+\.\d+  \\\\u2606\n"
1261
 
                "-+\n")
1262
 
 
1263
1353
 
1264
1354
class SampleTestCase(tests.TestCase):
1265
1355
 
1330
1420
        self.assertEqual(flags, bzrlib.debug.debug_flags)
1331
1421
 
1332
1422
    def change_selftest_debug_flags(self, new_flags):
1333
 
        self.overrideAttr(tests, 'selftest_debug_flags', set(new_flags))
 
1423
        orig_selftest_flags = tests.selftest_debug_flags
 
1424
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
 
1425
        tests.selftest_debug_flags = set(new_flags)
 
1426
 
 
1427
    def _restore_selftest_debug_flags(self, flags):
 
1428
        tests.selftest_debug_flags = flags
1334
1429
 
1335
1430
    def test_allow_debug_flag(self):
1336
1431
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1396
1491
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1397
1492
 
1398
1493
    def make_test_result(self):
1399
 
        """Get a test result that writes to the test log file."""
1400
1494
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1401
1495
 
1402
1496
    def inner_test(self):
1410
1504
        result = self.make_test_result()
1411
1505
        self.inner_test.run(result)
1412
1506
        note("outer finish")
1413
 
        self.addCleanup(osutils.delete_any, self._log_file_name)
1414
1507
 
1415
1508
    def test_trace_nesting(self):
1416
1509
        # this tests that each test case nests its trace facility correctly.
1428
1521
        outer_test = TestTestCase("outer_child")
1429
1522
        result = self.make_test_result()
1430
1523
        outer_test.run(result)
 
1524
        self.addCleanup(osutils.delete_any, outer_test._log_file_name)
1431
1525
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
1432
1526
 
1433
1527
    def method_that_times_a_bit_twice(self):
1440
1534
        sample_test = TestTestCase("method_that_times_a_bit_twice")
1441
1535
        output_stream = StringIO()
1442
1536
        result = bzrlib.tests.VerboseTestResult(
1443
 
            output_stream,
 
1537
            unittest._WritelnDecorator(output_stream),
1444
1538
            descriptions=0,
1445
1539
            verbosity=2)
1446
1540
        sample_test.run(result)
1453
1547
        # Note this test won't fail with hooks that the core library doesn't
1454
1548
        # use - but it trigger with a plugin that adds hooks, so its still a
1455
1549
        # useful warning in that case.
1456
 
        self.assertEqual(bzrlib.branch.BranchHooks(), bzrlib.branch.Branch.hooks)
1457
 
        self.assertEqual(
1458
 
            bzrlib.smart.server.SmartServerHooks(),
 
1550
        self.assertEqual(bzrlib.branch.BranchHooks(),
 
1551
            bzrlib.branch.Branch.hooks)
 
1552
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1459
1553
            bzrlib.smart.server.SmartTCPServer.hooks)
1460
 
        self.assertEqual(
1461
 
            bzrlib.commands.CommandHooks(), bzrlib.commands.Command.hooks)
 
1554
        self.assertEqual(bzrlib.commands.CommandHooks(),
 
1555
            bzrlib.commands.Command.hooks)
1462
1556
 
1463
1557
    def test__gather_lsprof_in_benchmarks(self):
1464
1558
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1465
1559
 
1466
1560
        Each self.time() call is individually and separately profiled.
1467
1561
        """
1468
 
        self.requireFeature(features.lsprof_feature)
 
1562
        self.requireFeature(test_lsprof.LSProfFeature)
1469
1563
        # overrides the class member with an instance member so no cleanup
1470
1564
        # needed.
1471
1565
        self._gather_lsprof_in_benchmarks = True
1487
1581
        # permitted.
1488
1582
        # Manually set one up (TestCase doesn't and shouldn't provide magic
1489
1583
        # machinery)
1490
 
        transport_server = memory.MemoryServer()
1491
 
        transport_server.start_server()
1492
 
        self.addCleanup(transport_server.stop_server)
1493
 
        t = transport.get_transport_from_url(transport_server.get_url())
 
1584
        transport_server = MemoryServer()
 
1585
        transport_server.setUp()
 
1586
        self.addCleanup(transport_server.tearDown)
 
1587
        t = transport.get_transport(transport_server.get_url())
1494
1588
        bzrdir.BzrDir.create(t.base)
1495
1589
        self.assertRaises(errors.BzrError,
1496
1590
            bzrdir.BzrDir.open_from_transport, t)
1501
1595
 
1502
1596
    def test_requireFeature_available(self):
1503
1597
        """self.requireFeature(available) is a no-op."""
1504
 
        class Available(features.Feature):
 
1598
        class Available(tests.Feature):
1505
1599
            def _probe(self):return True
1506
1600
        feature = Available()
1507
1601
        self.requireFeature(feature)
1508
1602
 
1509
1603
    def test_requireFeature_unavailable(self):
1510
1604
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1511
 
        class Unavailable(features.Feature):
 
1605
        class Unavailable(tests.Feature):
1512
1606
            def _probe(self):return False
1513
1607
        feature = Unavailable()
1514
1608
        self.assertRaises(tests.UnavailableFeature,
1548
1642
        """Test disabled tests behaviour with support aware results."""
1549
1643
        test = SampleTestCase('_test_pass')
1550
1644
        class DisabledFeature(object):
1551
 
            def __eq__(self, other):
1552
 
                return isinstance(other, DisabledFeature)
1553
1645
            def available(self):
1554
1646
                return False
1555
1647
        the_feature = DisabledFeature()
1566
1658
                self.calls.append(('addNotSupported', test, feature))
1567
1659
        result = InstrumentedTestResult()
1568
1660
        test.run(result)
1569
 
        case = result.calls[0][1]
1570
1661
        self.assertEqual([
1571
 
            ('startTest', case),
1572
 
            ('addNotSupported', case, the_feature),
1573
 
            ('stopTest', case),
 
1662
            ('startTest', test),
 
1663
            ('addNotSupported', test, the_feature),
 
1664
            ('stopTest', test),
1574
1665
            ],
1575
1666
            result.calls)
1576
1667
 
1577
1668
    def test_start_server_registers_url(self):
1578
 
        transport_server = memory.MemoryServer()
 
1669
        transport_server = MemoryServer()
1579
1670
        # A little strict, but unlikely to be changed soon.
1580
1671
        self.assertEqual([], self._bzr_selftest_roots)
1581
1672
        self.start_server(transport_server)
1637
1728
        self.assertRaises(AssertionError,
1638
1729
            self.assertListRaises, _TestException, success_generator)
1639
1730
 
1640
 
    def test_overrideAttr_without_value(self):
1641
 
        self.test_attr = 'original' # Define a test attribute
1642
 
        obj = self # Make 'obj' visible to the embedded test
1643
 
        class Test(tests.TestCase):
1644
 
 
1645
 
            def setUp(self):
1646
 
                tests.TestCase.setUp(self)
1647
 
                self.orig = self.overrideAttr(obj, 'test_attr')
1648
 
 
1649
 
            def test_value(self):
1650
 
                self.assertEqual('original', self.orig)
1651
 
                self.assertEqual('original', obj.test_attr)
1652
 
                obj.test_attr = 'modified'
1653
 
                self.assertEqual('modified', obj.test_attr)
1654
 
 
1655
 
        test = Test('test_value')
1656
 
        test.run(unittest.TestResult())
1657
 
        self.assertEqual('original', obj.test_attr)
1658
 
 
1659
 
    def test_overrideAttr_with_value(self):
1660
 
        self.test_attr = 'original' # Define a test attribute
1661
 
        obj = self # Make 'obj' visible to the embedded test
1662
 
        class Test(tests.TestCase):
1663
 
 
1664
 
            def setUp(self):
1665
 
                tests.TestCase.setUp(self)
1666
 
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
1667
 
 
1668
 
            def test_value(self):
1669
 
                self.assertEqual('original', self.orig)
1670
 
                self.assertEqual('modified', obj.test_attr)
1671
 
 
1672
 
        test = Test('test_value')
1673
 
        test.run(unittest.TestResult())
1674
 
        self.assertEqual('original', obj.test_attr)
1675
 
 
1676
 
    def test_recordCalls(self):
1677
 
        from bzrlib.tests import test_selftest
1678
 
        calls = self.recordCalls(
1679
 
            test_selftest, '_add_numbers')
1680
 
        self.assertEqual(test_selftest._add_numbers(2, 10),
1681
 
            12)
1682
 
        self.assertEquals(calls, [((2, 10), {})])
1683
 
 
1684
 
 
1685
 
def _add_numbers(a, b):
1686
 
    return a + b
1687
 
 
1688
 
 
1689
 
class _MissingFeature(features.Feature):
1690
 
    def _probe(self):
1691
 
        return False
1692
 
missing_feature = _MissingFeature()
1693
 
 
1694
 
 
1695
 
def _get_test(name):
1696
 
    """Get an instance of a specific example test.
1697
 
 
1698
 
    We protect this in a function so that they don't auto-run in the test
1699
 
    suite.
1700
 
    """
1701
 
 
1702
 
    class ExampleTests(tests.TestCase):
1703
 
 
1704
 
        def test_fail(self):
1705
 
            mutter('this was a failing test')
1706
 
            self.fail('this test will fail')
1707
 
 
1708
 
        def test_error(self):
1709
 
            mutter('this test errored')
1710
 
            raise RuntimeError('gotcha')
1711
 
 
1712
 
        def test_missing_feature(self):
1713
 
            mutter('missing the feature')
1714
 
            self.requireFeature(missing_feature)
1715
 
 
1716
 
        def test_skip(self):
1717
 
            mutter('this test will be skipped')
1718
 
            raise tests.TestSkipped('reason')
1719
 
 
1720
 
        def test_success(self):
1721
 
            mutter('this test succeeds')
1722
 
 
1723
 
        def test_xfail(self):
1724
 
            mutter('test with expected failure')
1725
 
            self.knownFailure('this_fails')
1726
 
 
1727
 
        def test_unexpected_success(self):
1728
 
            mutter('test with unexpected success')
1729
 
            self.expectFailure('should_fail', lambda: None)
1730
 
 
1731
 
    return ExampleTests(name)
1732
 
 
1733
 
 
1734
 
class TestTestCaseLogDetails(tests.TestCase):
1735
 
 
1736
 
    def _run_test(self, test_name):
1737
 
        test = _get_test(test_name)
1738
 
        result = testtools.TestResult()
1739
 
        test.run(result)
1740
 
        return result
1741
 
 
1742
 
    def test_fail_has_log(self):
1743
 
        result = self._run_test('test_fail')
1744
 
        self.assertEqual(1, len(result.failures))
1745
 
        result_content = result.failures[0][1]
1746
 
        if testtools_version < (0, 9, 12):
1747
 
            self.assertContainsRe(result_content, 'Text attachment: log')
1748
 
        self.assertContainsRe(result_content, 'this was a failing test')
1749
 
 
1750
 
    def test_error_has_log(self):
1751
 
        result = self._run_test('test_error')
1752
 
        self.assertEqual(1, len(result.errors))
1753
 
        result_content = result.errors[0][1]
1754
 
        if testtools_version < (0, 9, 12):
1755
 
            self.assertContainsRe(result_content, 'Text attachment: log')
1756
 
        self.assertContainsRe(result_content, 'this test errored')
1757
 
 
1758
 
    def test_skip_has_no_log(self):
1759
 
        result = self._run_test('test_skip')
1760
 
        self.assertEqual(['reason'], result.skip_reasons.keys())
1761
 
        skips = result.skip_reasons['reason']
1762
 
        self.assertEqual(1, len(skips))
1763
 
        test = skips[0]
1764
 
        self.assertFalse('log' in test.getDetails())
1765
 
 
1766
 
    def test_missing_feature_has_no_log(self):
1767
 
        # testtools doesn't know about addNotSupported, so it just gets
1768
 
        # considered as a skip
1769
 
        result = self._run_test('test_missing_feature')
1770
 
        self.assertEqual([missing_feature], result.skip_reasons.keys())
1771
 
        skips = result.skip_reasons[missing_feature]
1772
 
        self.assertEqual(1, len(skips))
1773
 
        test = skips[0]
1774
 
        self.assertFalse('log' in test.getDetails())
1775
 
 
1776
 
    def test_xfail_has_no_log(self):
1777
 
        result = self._run_test('test_xfail')
1778
 
        self.assertEqual(1, len(result.expectedFailures))
1779
 
        result_content = result.expectedFailures[0][1]
1780
 
        self.assertNotContainsRe(result_content, 'Text attachment: log')
1781
 
        self.assertNotContainsRe(result_content, 'test with expected failure')
1782
 
 
1783
 
    def test_unexpected_success_has_log(self):
1784
 
        result = self._run_test('test_unexpected_success')
1785
 
        self.assertEqual(1, len(result.unexpectedSuccesses))
1786
 
        # Inconsistency, unexpectedSuccesses is a list of tests,
1787
 
        # expectedFailures is a list of reasons?
1788
 
        test = result.unexpectedSuccesses[0]
1789
 
        details = test.getDetails()
1790
 
        self.assertTrue('log' in details)
1791
 
 
1792
 
 
1793
 
class TestTestCloning(tests.TestCase):
1794
 
    """Tests that test cloning of TestCases (as used by multiply_tests)."""
1795
 
 
1796
 
    def test_cloned_testcase_does_not_share_details(self):
1797
 
        """A TestCase cloned with clone_test does not share mutable attributes
1798
 
        such as details or cleanups.
1799
 
        """
1800
 
        class Test(tests.TestCase):
1801
 
            def test_foo(self):
1802
 
                self.addDetail('foo', Content('text/plain', lambda: 'foo'))
1803
 
        orig_test = Test('test_foo')
1804
 
        cloned_test = tests.clone_test(orig_test, orig_test.id() + '(cloned)')
1805
 
        orig_test.run(unittest.TestResult())
1806
 
        self.assertEqual('foo', orig_test.getDetails()['foo'].iter_bytes())
1807
 
        self.assertEqual(None, cloned_test.getDetails().get('foo'))
1808
 
 
1809
 
    def test_double_apply_scenario_preserves_first_scenario(self):
1810
 
        """Applying two levels of scenarios to a test preserves the attributes
1811
 
        added by both scenarios.
1812
 
        """
1813
 
        class Test(tests.TestCase):
1814
 
            def test_foo(self):
1815
 
                pass
1816
 
        test = Test('test_foo')
1817
 
        scenarios_x = [('x=1', {'x': 1}), ('x=2', {'x': 2})]
1818
 
        scenarios_y = [('y=1', {'y': 1}), ('y=2', {'y': 2})]
1819
 
        suite = tests.multiply_tests(test, scenarios_x, unittest.TestSuite())
1820
 
        suite = tests.multiply_tests(suite, scenarios_y, unittest.TestSuite())
1821
 
        all_tests = list(tests.iter_suite_tests(suite))
1822
 
        self.assertLength(4, all_tests)
1823
 
        all_xys = sorted((t.x, t.y) for t in all_tests)
1824
 
        self.assertEqual([(1, 1), (1, 2), (2, 1), (2, 2)], all_xys)
1825
 
 
1826
1731
 
1827
1732
# NB: Don't delete this; it's not actually from 0.11!
1828
1733
@deprecated_function(deprecated_in((0, 11, 0)))
1956
1861
    def test_make_branch_and_tree_with_format(self):
1957
1862
        # we should be able to supply a format to make_branch_and_tree
1958
1863
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
 
1864
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1959
1865
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1960
1866
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
1867
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
 
1868
                              bzrlib.bzrdir.BzrDirFormat6)
1961
1869
 
1962
1870
    def test_make_branch_and_memory_tree(self):
1963
1871
        # we should be able to get a new branch and a mutable tree from
1969
1877
        # make_branch_and_tree has to use local branch and repositories
1970
1878
        # when the vfs transport and local disk are colocated, even if
1971
1879
        # a different transport is in use for url generation.
1972
 
        self.transport_server = test_server.FakeVFATServer
 
1880
        from bzrlib.transport.fakevfat import FakeVFATServer
 
1881
        self.transport_server = FakeVFATServer
1973
1882
        self.assertFalse(self.get_url('t1').startswith('file://'))
1974
1883
        tree = self.make_branch_and_tree('t1')
1975
1884
        base = tree.bzrdir.root_transport.base
1980
1889
                tree.branch.repository.bzrdir.root_transport)
1981
1890
 
1982
1891
 
1983
 
class SelfTestHelper(object):
 
1892
class SelfTestHelper:
1984
1893
 
1985
1894
    def run_selftest(self, **kwargs):
1986
1895
        """Run selftest returning its output."""
2040
1949
        self.assertLength(2, output.readlines())
2041
1950
 
2042
1951
    def test_lsprof_tests(self):
2043
 
        self.requireFeature(features.lsprof_feature)
2044
 
        results = []
 
1952
        self.requireFeature(test_lsprof.LSProfFeature)
 
1953
        calls = []
2045
1954
        class Test(object):
2046
1955
            def __call__(test, result):
2047
1956
                test.run(result)
2048
1957
            def run(test, result):
2049
 
                results.append(result)
 
1958
                self.assertIsInstance(result, tests.ForwardingResult)
 
1959
                calls.append("called")
2050
1960
            def countTestCases(self):
2051
1961
                return 1
2052
1962
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
2053
 
        self.assertLength(1, results)
2054
 
        self.assertIsInstance(results.pop(), ExtendedToOriginalDecorator)
 
1963
        self.assertLength(1, calls)
2055
1964
 
2056
1965
    def test_random(self):
2057
1966
        # test randomising by listing a number of tests.
2073
1982
        self.assertEqual(expected.getvalue(), repeated.getvalue())
2074
1983
 
2075
1984
    def test_runner_class(self):
2076
 
        self.requireFeature(features.subunit)
 
1985
        self.requireFeature(SubUnitFeature)
2077
1986
        from subunit import ProtocolTestCase
2078
1987
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
2079
1988
            test_suite_factory=self.factory)
2111
2020
        self.assertEqual(transport_server, captured_transport[0])
2112
2021
 
2113
2022
    def test_transport_sftp(self):
2114
 
        self.requireFeature(features.paramiko)
2115
 
        from bzrlib.tests import stub_sftp
2116
 
        self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
 
2023
        try:
 
2024
            import bzrlib.transport.sftp
 
2025
        except errors.ParamikoNotPresent:
 
2026
            raise tests.TestSkipped("Paramiko not present")
 
2027
        self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
2117
2028
 
2118
2029
    def test_transport_memory(self):
2119
 
        self.check_transport_set(memory.MemoryServer)
 
2030
        self.check_transport_set(bzrlib.transport.memory.MemoryServer)
2120
2031
 
2121
2032
 
2122
2033
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
2137
2048
            load_list='missing file name', list_only=True)
2138
2049
 
2139
2050
 
2140
 
class TestSubunitLogDetails(tests.TestCase, SelfTestHelper):
2141
 
 
2142
 
    _test_needs_features = [features.subunit]
2143
 
 
2144
 
    def run_subunit_stream(self, test_name):
2145
 
        from subunit import ProtocolTestCase
2146
 
        def factory():
2147
 
            return TestUtil.TestSuite([_get_test(test_name)])
2148
 
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
2149
 
            test_suite_factory=factory)
2150
 
        test = ProtocolTestCase(stream)
2151
 
        result = testtools.TestResult()
2152
 
        test.run(result)
2153
 
        content = stream.getvalue()
2154
 
        return content, result
2155
 
 
2156
 
    def test_fail_has_log(self):
2157
 
        content, result = self.run_subunit_stream('test_fail')
2158
 
        self.assertEqual(1, len(result.failures))
2159
 
        self.assertContainsRe(content, '(?m)^log$')
2160
 
        self.assertContainsRe(content, 'this test will fail')
2161
 
 
2162
 
    def test_error_has_log(self):
2163
 
        content, result = self.run_subunit_stream('test_error')
2164
 
        self.assertContainsRe(content, '(?m)^log$')
2165
 
        self.assertContainsRe(content, 'this test errored')
2166
 
 
2167
 
    def test_skip_has_no_log(self):
2168
 
        content, result = self.run_subunit_stream('test_skip')
2169
 
        self.assertNotContainsRe(content, '(?m)^log$')
2170
 
        self.assertNotContainsRe(content, 'this test will be skipped')
2171
 
        self.assertEqual(['reason'], result.skip_reasons.keys())
2172
 
        skips = result.skip_reasons['reason']
2173
 
        self.assertEqual(1, len(skips))
2174
 
        test = skips[0]
2175
 
        # RemotedTestCase doesn't preserve the "details"
2176
 
        ## self.assertFalse('log' in test.getDetails())
2177
 
 
2178
 
    def test_missing_feature_has_no_log(self):
2179
 
        content, result = self.run_subunit_stream('test_missing_feature')
2180
 
        self.assertNotContainsRe(content, '(?m)^log$')
2181
 
        self.assertNotContainsRe(content, 'missing the feature')
2182
 
        self.assertEqual(['_MissingFeature\n'], result.skip_reasons.keys())
2183
 
        skips = result.skip_reasons['_MissingFeature\n']
2184
 
        self.assertEqual(1, len(skips))
2185
 
        test = skips[0]
2186
 
        # RemotedTestCase doesn't preserve the "details"
2187
 
        ## self.assertFalse('log' in test.getDetails())
2188
 
 
2189
 
    def test_xfail_has_no_log(self):
2190
 
        content, result = self.run_subunit_stream('test_xfail')
2191
 
        self.assertNotContainsRe(content, '(?m)^log$')
2192
 
        self.assertNotContainsRe(content, 'test with expected failure')
2193
 
        self.assertEqual(1, len(result.expectedFailures))
2194
 
        result_content = result.expectedFailures[0][1]
2195
 
        self.assertNotContainsRe(result_content, 'Text attachment: log')
2196
 
        self.assertNotContainsRe(result_content, 'test with expected failure')
2197
 
 
2198
 
    def test_unexpected_success_has_log(self):
2199
 
        content, result = self.run_subunit_stream('test_unexpected_success')
2200
 
        self.assertContainsRe(content, '(?m)^log$')
2201
 
        self.assertContainsRe(content, 'test with unexpected success')
2202
 
        # GZ 2011-05-18: Old versions of subunit treat unexpected success as a
2203
 
        #                success, if a min version check is added remove this
2204
 
        from subunit import TestProtocolClient as _Client
2205
 
        if _Client.addUnexpectedSuccess.im_func is _Client.addSuccess.im_func:
2206
 
            self.expectFailure('subunit treats "unexpectedSuccess"'
2207
 
                               ' as a plain success',
2208
 
                self.assertEqual, 1, len(result.unexpectedSuccesses))
2209
 
        self.assertEqual(1, len(result.unexpectedSuccesses))
2210
 
        test = result.unexpectedSuccesses[0]
2211
 
        # RemotedTestCase doesn't preserve the "details"
2212
 
        ## self.assertTrue('log' in test.getDetails())
2213
 
 
2214
 
    def test_success_has_no_log(self):
2215
 
        content, result = self.run_subunit_stream('test_success')
2216
 
        self.assertEqual(1, result.testsRun)
2217
 
        self.assertNotContainsRe(content, '(?m)^log$')
2218
 
        self.assertNotContainsRe(content, 'this test succeeds')
2219
 
 
2220
 
 
2221
2051
class TestRunBzr(tests.TestCase):
2222
2052
 
2223
2053
    out = ''
2346
2176
        # stdout and stderr of the invoked run_bzr
2347
2177
        current_factory = bzrlib.ui.ui_factory
2348
2178
        self.run_bzr(['foo'])
2349
 
        self.assertFalse(current_factory is self.factory)
 
2179
        self.failIf(current_factory is self.factory)
2350
2180
        self.assertNotEqual(sys.stdout, self.factory.stdout)
2351
2181
        self.assertNotEqual(sys.stderr, self.factory.stderr)
2352
2182
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
2509
2339
 
2510
2340
 
2511
2341
class TestStartBzrSubProcess(tests.TestCase):
2512
 
    """Stub test start_bzr_subprocess."""
2513
2342
 
2514
 
    def _subprocess_log_cleanup(self):
2515
 
        """Inhibits the base version as we don't produce a log file."""
 
2343
    def check_popen_state(self):
 
2344
        """Replace to make assertions when popen is called."""
2516
2345
 
2517
2346
    def _popen(self, *args, **kwargs):
2518
 
        """Override the base version to record the command that is run.
2519
 
 
2520
 
        From there we can ensure it is correct without spawning a real process.
2521
 
        """
 
2347
        """Record the command that is run, so that we can ensure it is correct"""
2522
2348
        self.check_popen_state()
2523
2349
        self._popen_args = args
2524
2350
        self._popen_kwargs = kwargs
2525
2351
        raise _DontSpawnProcess()
2526
2352
 
2527
 
    def check_popen_state(self):
2528
 
        """Replace to make assertions when popen is called."""
2529
 
 
2530
2353
    def test_run_bzr_subprocess_no_plugins(self):
2531
2354
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2532
2355
        command = self._popen_args[0]
2536
2359
 
2537
2360
    def test_allow_plugins(self):
2538
2361
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2539
 
                          allow_plugins=True)
 
2362
            allow_plugins=True)
2540
2363
        command = self._popen_args[0]
2541
2364
        self.assertEqual([], command[2:])
2542
2365
 
2543
2366
    def test_set_env(self):
2544
 
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2367
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
2545
2368
        # set in the child
2546
2369
        def check_environment():
2547
2370
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2548
2371
        self.check_popen_state = check_environment
2549
2372
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2550
 
                          env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2373
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
2551
2374
        # not set in theparent
2552
2375
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2553
2376
 
2554
2377
    def test_run_bzr_subprocess_env_del(self):
2555
2378
        """run_bzr_subprocess can remove environment variables too."""
2556
 
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2379
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
2557
2380
        def check_environment():
2558
2381
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2559
2382
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2560
2383
        self.check_popen_state = check_environment
2561
2384
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2562
 
                          env_changes={'EXISTANT_ENV_VAR':None})
 
2385
            env_changes={'EXISTANT_ENV_VAR':None})
2563
2386
        # Still set in parent
2564
2387
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2565
2388
        del os.environ['EXISTANT_ENV_VAR']
2566
2389
 
2567
2390
    def test_env_del_missing(self):
2568
 
        self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
 
2391
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2569
2392
        def check_environment():
2570
2393
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2571
2394
        self.check_popen_state = check_environment
2572
2395
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2573
 
                          env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2396
            env_changes={'NON_EXISTANT_ENV_VAR':None})
2574
2397
 
2575
2398
    def test_working_dir(self):
2576
2399
        """Test that we can specify the working dir for the child"""
2579
2402
        chdirs = []
2580
2403
        def chdir(path):
2581
2404
            chdirs.append(path)
2582
 
        self.overrideAttr(os, 'chdir', chdir)
2583
 
        def getcwd():
2584
 
            return 'current'
2585
 
        self.overrideAttr(osutils, 'getcwd', getcwd)
2586
 
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2587
 
                          working_dir='foo')
 
2405
        os.chdir = chdir
 
2406
        try:
 
2407
            def getcwd():
 
2408
                return 'current'
 
2409
            osutils.getcwd = getcwd
 
2410
            try:
 
2411
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2412
                    working_dir='foo')
 
2413
            finally:
 
2414
                osutils.getcwd = orig_getcwd
 
2415
        finally:
 
2416
            os.chdir = orig_chdir
2588
2417
        self.assertEqual(['foo', 'current'], chdirs)
2589
2418
 
2590
 
    def test_get_bzr_path_with_cwd_bzrlib(self):
2591
 
        self.get_source_path = lambda: ""
2592
 
        self.overrideAttr(os.path, "isfile", lambda path: True)
2593
 
        self.assertEqual(self.get_bzr_path(), "bzr")
2594
 
 
2595
2419
 
2596
2420
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2597
2421
    """Tests that really need to do things with an external bzr."""
2610
2434
        self.assertEqual('bzr: interrupted\n', result[1])
2611
2435
 
2612
2436
 
 
2437
class TestKnownFailure(tests.TestCase):
 
2438
 
 
2439
    def test_known_failure(self):
 
2440
        """Check that KnownFailure is defined appropriately."""
 
2441
        # a KnownFailure is an assertion error for compatability with unaware
 
2442
        # runners.
 
2443
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
 
2444
 
 
2445
    def test_expect_failure(self):
 
2446
        try:
 
2447
            self.expectFailure("Doomed to failure", self.assertTrue, False)
 
2448
        except tests.KnownFailure, e:
 
2449
            self.assertEqual('Doomed to failure', e.args[0])
 
2450
        try:
 
2451
            self.expectFailure("Doomed to failure", self.assertTrue, True)
 
2452
        except AssertionError, e:
 
2453
            self.assertEqual('Unexpected success.  Should have failed:'
 
2454
                             ' Doomed to failure', e.args[0])
 
2455
        else:
 
2456
            self.fail('Assertion not raised')
 
2457
 
 
2458
 
 
2459
class TestFeature(tests.TestCase):
 
2460
 
 
2461
    def test_caching(self):
 
2462
        """Feature._probe is called by the feature at most once."""
 
2463
        class InstrumentedFeature(tests.Feature):
 
2464
            def __init__(self):
 
2465
                super(InstrumentedFeature, self).__init__()
 
2466
                self.calls = []
 
2467
            def _probe(self):
 
2468
                self.calls.append('_probe')
 
2469
                return False
 
2470
        feature = InstrumentedFeature()
 
2471
        feature.available()
 
2472
        self.assertEqual(['_probe'], feature.calls)
 
2473
        feature.available()
 
2474
        self.assertEqual(['_probe'], feature.calls)
 
2475
 
 
2476
    def test_named_str(self):
 
2477
        """Feature.__str__ should thunk to feature_name()."""
 
2478
        class NamedFeature(tests.Feature):
 
2479
            def feature_name(self):
 
2480
                return 'symlinks'
 
2481
        feature = NamedFeature()
 
2482
        self.assertEqual('symlinks', str(feature))
 
2483
 
 
2484
    def test_default_str(self):
 
2485
        """Feature.__str__ should default to __class__.__name__."""
 
2486
        class NamedFeature(tests.Feature):
 
2487
            pass
 
2488
        feature = NamedFeature()
 
2489
        self.assertEqual('NamedFeature', str(feature))
 
2490
 
 
2491
 
 
2492
class TestUnavailableFeature(tests.TestCase):
 
2493
 
 
2494
    def test_access_feature(self):
 
2495
        feature = tests.Feature()
 
2496
        exception = tests.UnavailableFeature(feature)
 
2497
        self.assertIs(feature, exception.args[0])
 
2498
 
 
2499
 
 
2500
class TestModuleAvailableFeature(tests.TestCase):
 
2501
 
 
2502
    def test_available_module(self):
 
2503
        feature = tests.ModuleAvailableFeature('bzrlib.tests')
 
2504
        self.assertEqual('bzrlib.tests', feature.module_name)
 
2505
        self.assertEqual('bzrlib.tests', str(feature))
 
2506
        self.assertTrue(feature.available())
 
2507
        self.assertIs(tests, feature.module)
 
2508
 
 
2509
    def test_unavailable_module(self):
 
2510
        feature = tests.ModuleAvailableFeature('bzrlib.no_such_module_exists')
 
2511
        self.assertEqual('bzrlib.no_such_module_exists', str(feature))
 
2512
        self.assertFalse(feature.available())
 
2513
        self.assertIs(None, feature.module)
 
2514
 
 
2515
 
2613
2516
class TestSelftestFiltering(tests.TestCase):
2614
2517
 
2615
2518
    def setUp(self):
2766
2669
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2767
2670
 
2768
2671
 
2769
 
class TestCheckTreeShape(tests.TestCaseWithTransport):
 
2672
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2770
2673
 
2771
 
    def test_check_tree_shape(self):
 
2674
    def test_check_inventory_shape(self):
2772
2675
        files = ['a', 'b/', 'b/c']
2773
2676
        tree = self.make_branch_and_tree('.')
2774
2677
        self.build_tree(files)
2775
2678
        tree.add(files)
2776
2679
        tree.lock_read()
2777
2680
        try:
2778
 
            self.check_tree_shape(tree, files)
 
2681
            self.check_inventory_shape(tree.inventory, files)
2779
2682
        finally:
2780
2683
            tree.unlock()
2781
2684
 
2794
2697
        # the test framework
2795
2698
        self.assertEquals('always fails', str(e))
2796
2699
        # check that there's no traceback in the test log
2797
 
        self.assertNotContainsRe(self.get_log(), r'Traceback')
 
2700
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
 
2701
            r'Traceback')
2798
2702
 
2799
2703
    def test_run_bzr_user_error_caught(self):
2800
2704
        # Running bzr in blackbox mode, normal/expected/user errors should be
2801
2705
        # caught in the regular way and turned into an error message plus exit
2802
2706
        # code.
2803
 
        transport_server = memory.MemoryServer()
2804
 
        transport_server.start_server()
2805
 
        self.addCleanup(transport_server.stop_server)
 
2707
        transport_server = MemoryServer()
 
2708
        transport_server.setUp()
 
2709
        self.addCleanup(transport_server.tearDown)
2806
2710
        url = transport_server.get_url()
2807
2711
        self.permit_url(url)
2808
2712
        out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
2952
2856
        # Test that a plausible list of modules to doctest is returned
2953
2857
        # by _test_suite_modules_to_doctest.
2954
2858
        test_list = tests._test_suite_modules_to_doctest()
2955
 
        if __doc__ is None:
2956
 
            # When docstrings are stripped, there are no modules to doctest
2957
 
            self.assertEqual([], test_list)
2958
 
            return
2959
2859
        self.assertSubset([
2960
2860
            'bzrlib.timestamp',
2961
2861
            ],
2968
2868
        # test doubles that supply a few sample tests to load, and check they
2969
2869
        # are loaded.
2970
2870
        calls = []
2971
 
        def testmod_names():
 
2871
        def _test_suite_testmod_names():
2972
2872
            calls.append("testmod_names")
2973
2873
            return [
2974
2874
                'bzrlib.tests.blackbox.test_branch',
2975
2875
                'bzrlib.tests.per_transport',
2976
2876
                'bzrlib.tests.test_selftest',
2977
2877
                ]
2978
 
        self.overrideAttr(tests, '_test_suite_testmod_names', testmod_names)
2979
 
        def doctests():
 
2878
        original_testmod_names = tests._test_suite_testmod_names
 
2879
        def _test_suite_modules_to_doctest():
2980
2880
            calls.append("modules_to_doctest")
2981
 
            if __doc__ is None:
2982
 
                return []
2983
2881
            return ['bzrlib.timestamp']
2984
 
        self.overrideAttr(tests, '_test_suite_modules_to_doctest', doctests)
 
2882
        orig_modules_to_doctest = tests._test_suite_modules_to_doctest
 
2883
        def restore_names():
 
2884
            tests._test_suite_testmod_names = original_testmod_names
 
2885
            tests._test_suite_modules_to_doctest = orig_modules_to_doctest
 
2886
        self.addCleanup(restore_names)
 
2887
        tests._test_suite_testmod_names = _test_suite_testmod_names
 
2888
        tests._test_suite_modules_to_doctest = _test_suite_modules_to_doctest
2985
2889
        expected_test_list = [
2986
2890
            # testmod_names
2987
2891
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2988
2892
            ('bzrlib.tests.per_transport.TransportTests'
2989
2893
             '.test_abspath(LocalTransport,LocalURLServer)'),
2990
2894
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
 
2895
            # modules_to_doctest
 
2896
            'bzrlib.timestamp.format_highres_date',
2991
2897
            # plugins can't be tested that way since selftest may be run with
2992
2898
            # --no-plugins
2993
2899
            ]
2994
 
        if __doc__ is not None:
2995
 
            expected_test_list.extend([
2996
 
                # modules_to_doctest
2997
 
                'bzrlib.timestamp.format_highres_date',
2998
 
                ])
2999
2900
        suite = tests.test_suite()
3000
2901
        self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
3001
2902
            set(calls))
3056
2957
    def test_load_tests(self):
3057
2958
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
3058
2959
        loader = self._create_loader(test_list)
 
2960
 
3059
2961
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
3060
2962
        self.assertEquals(test_list, _test_ids(suite))
3061
2963
 
3062
2964
    def test_exclude_tests(self):
3063
2965
        test_list = ['bogus']
3064
2966
        loader = self._create_loader(test_list)
 
2967
 
3065
2968
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
3066
2969
        self.assertEquals([], _test_ids(suite))
3067
2970
 
3112
3015
        tpr.register('bar', 'bbb.aaa.rrr')
3113
3016
        tpr.register('bar', 'bBB.aAA.rRR')
3114
3017
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
3115
 
        self.assertThat(self.get_log(),
3116
 
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR",
3117
 
                           doctest.ELLIPSIS))
 
3018
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
3019
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
3118
3020
 
3119
3021
    def test_get_unknown_prefix(self):
3120
3022
        tpr = self._get_registry()
3140
3042
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
3141
3043
 
3142
3044
 
3143
 
class TestThreadLeakDetection(tests.TestCase):
3144
 
    """Ensure when tests leak threads we detect and report it"""
3145
 
 
3146
 
    class LeakRecordingResult(tests.ExtendedTestResult):
3147
 
        def __init__(self):
3148
 
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
3149
 
            self.leaks = []
3150
 
        def _report_thread_leak(self, test, leaks, alive):
3151
 
            self.leaks.append((test, leaks))
3152
 
 
3153
 
    def test_testcase_without_addCleanups(self):
3154
 
        """Check old TestCase instances don't break with leak detection"""
3155
 
        class Test(unittest.TestCase):
3156
 
            def runTest(self):
3157
 
                pass
3158
 
        result = self.LeakRecordingResult()
3159
 
        test = Test()
3160
 
        result.startTestRun()
3161
 
        test.run(result)
3162
 
        result.stopTestRun()
3163
 
        self.assertEqual(result._tests_leaking_threads_count, 0)
3164
 
        self.assertEqual(result.leaks, [])
3165
 
        
3166
 
    def test_thread_leak(self):
3167
 
        """Ensure a thread that outlives the running of a test is reported
3168
 
 
3169
 
        Uses a thread that blocks on an event, and is started by the inner
3170
 
        test case. As the thread outlives the inner case's run, it should be
3171
 
        detected as a leak, but the event is then set so that the thread can
3172
 
        be safely joined in cleanup so it's not leaked for real.
3173
 
        """
3174
 
        event = threading.Event()
3175
 
        thread = threading.Thread(name="Leaker", target=event.wait)
3176
 
        class Test(tests.TestCase):
3177
 
            def test_leak(self):
3178
 
                thread.start()
3179
 
        result = self.LeakRecordingResult()
3180
 
        test = Test("test_leak")
3181
 
        self.addCleanup(thread.join)
3182
 
        self.addCleanup(event.set)
3183
 
        result.startTestRun()
3184
 
        test.run(result)
3185
 
        result.stopTestRun()
3186
 
        self.assertEqual(result._tests_leaking_threads_count, 1)
3187
 
        self.assertEqual(result._first_thread_leaker_id, test.id())
3188
 
        self.assertEqual(result.leaks, [(test, set([thread]))])
3189
 
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
3190
 
 
3191
 
    def test_multiple_leaks(self):
3192
 
        """Check multiple leaks are blamed on the test cases at fault
3193
 
 
3194
 
        Same concept as the previous test, but has one inner test method that
3195
 
        leaks two threads, and one that doesn't leak at all.
3196
 
        """
3197
 
        event = threading.Event()
3198
 
        thread_a = threading.Thread(name="LeakerA", target=event.wait)
3199
 
        thread_b = threading.Thread(name="LeakerB", target=event.wait)
3200
 
        thread_c = threading.Thread(name="LeakerC", target=event.wait)
3201
 
        class Test(tests.TestCase):
3202
 
            def test_first_leak(self):
3203
 
                thread_b.start()
3204
 
            def test_second_no_leak(self):
3205
 
                pass
3206
 
            def test_third_leak(self):
3207
 
                thread_c.start()
3208
 
                thread_a.start()
3209
 
        result = self.LeakRecordingResult()
3210
 
        first_test = Test("test_first_leak")
3211
 
        third_test = Test("test_third_leak")
3212
 
        self.addCleanup(thread_a.join)
3213
 
        self.addCleanup(thread_b.join)
3214
 
        self.addCleanup(thread_c.join)
3215
 
        self.addCleanup(event.set)
3216
 
        result.startTestRun()
3217
 
        unittest.TestSuite(
3218
 
            [first_test, Test("test_second_no_leak"), third_test]
3219
 
            ).run(result)
3220
 
        result.stopTestRun()
3221
 
        self.assertEqual(result._tests_leaking_threads_count, 2)
3222
 
        self.assertEqual(result._first_thread_leaker_id, first_test.id())
3223
 
        self.assertEqual(result.leaks, [
3224
 
            (first_test, set([thread_b])),
3225
 
            (third_test, set([thread_a, thread_c]))])
3226
 
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
3227
 
 
3228
 
 
3229
 
class TestPostMortemDebugging(tests.TestCase):
3230
 
    """Check post mortem debugging works when tests fail or error"""
3231
 
 
3232
 
    class TracebackRecordingResult(tests.ExtendedTestResult):
3233
 
        def __init__(self):
3234
 
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
3235
 
            self.postcode = None
3236
 
        def _post_mortem(self, tb=None):
3237
 
            """Record the code object at the end of the current traceback"""
3238
 
            tb = tb or sys.exc_info()[2]
3239
 
            if tb is not None:
3240
 
                next = tb.tb_next
3241
 
                while next is not None:
3242
 
                    tb = next
3243
 
                    next = next.tb_next
3244
 
                self.postcode = tb.tb_frame.f_code
3245
 
        def report_error(self, test, err):
3246
 
            pass
3247
 
        def report_failure(self, test, err):
3248
 
            pass
3249
 
 
3250
 
    def test_location_unittest_error(self):
3251
 
        """Needs right post mortem traceback with erroring unittest case"""
3252
 
        class Test(unittest.TestCase):
3253
 
            def runTest(self):
3254
 
                raise RuntimeError
3255
 
        result = self.TracebackRecordingResult()
3256
 
        Test().run(result)
3257
 
        self.assertEqual(result.postcode, Test.runTest.func_code)
3258
 
 
3259
 
    def test_location_unittest_failure(self):
3260
 
        """Needs right post mortem traceback with failing unittest case"""
3261
 
        class Test(unittest.TestCase):
3262
 
            def runTest(self):
3263
 
                raise self.failureException
3264
 
        result = self.TracebackRecordingResult()
3265
 
        Test().run(result)
3266
 
        self.assertEqual(result.postcode, Test.runTest.func_code)
3267
 
 
3268
 
    def test_location_bt_error(self):
3269
 
        """Needs right post mortem traceback with erroring bzrlib.tests case"""
3270
 
        class Test(tests.TestCase):
3271
 
            def test_error(self):
3272
 
                raise RuntimeError
3273
 
        result = self.TracebackRecordingResult()
3274
 
        Test("test_error").run(result)
3275
 
        self.assertEqual(result.postcode, Test.test_error.func_code)
3276
 
 
3277
 
    def test_location_bt_failure(self):
3278
 
        """Needs right post mortem traceback with failing bzrlib.tests case"""
3279
 
        class Test(tests.TestCase):
3280
 
            def test_failure(self):
3281
 
                raise self.failureException
3282
 
        result = self.TracebackRecordingResult()
3283
 
        Test("test_failure").run(result)
3284
 
        self.assertEqual(result.postcode, Test.test_failure.func_code)
3285
 
 
3286
 
    def test_env_var_triggers_post_mortem(self):
3287
 
        """Check pdb.post_mortem is called iff BZR_TEST_PDB is set"""
3288
 
        import pdb
3289
 
        result = tests.ExtendedTestResult(StringIO(), 0, 1)
3290
 
        post_mortem_calls = []
3291
 
        self.overrideAttr(pdb, "post_mortem", post_mortem_calls.append)
3292
 
        self.overrideEnv('BZR_TEST_PDB', None)
3293
 
        result._post_mortem(1)
3294
 
        self.overrideEnv('BZR_TEST_PDB', 'on')
3295
 
        result._post_mortem(2)
3296
 
        self.assertEqual([2], post_mortem_calls)
3297
 
 
3298
 
 
3299
3045
class TestRunSuite(tests.TestCase):
3300
3046
 
3301
3047
    def test_runner_class(self):
3312
3058
                                                self.verbosity)
3313
3059
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
3314
3060
        self.assertLength(1, calls)
3315
 
 
3316
 
 
3317
 
class TestEnvironHandling(tests.TestCase):
3318
 
 
3319
 
    def test_overrideEnv_None_called_twice_doesnt_leak(self):
3320
 
        self.assertFalse('MYVAR' in os.environ)
3321
 
        self.overrideEnv('MYVAR', '42')
3322
 
        # We use an embedded test to make sure we fix the _captureVar bug
3323
 
        class Test(tests.TestCase):
3324
 
            def test_me(self):
3325
 
                # The first call save the 42 value
3326
 
                self.overrideEnv('MYVAR', None)
3327
 
                self.assertEquals(None, os.environ.get('MYVAR'))
3328
 
                # Make sure we can call it twice
3329
 
                self.overrideEnv('MYVAR', None)
3330
 
                self.assertEquals(None, os.environ.get('MYVAR'))
3331
 
        output = StringIO()
3332
 
        result = tests.TextTestResult(output, 0, 1)
3333
 
        Test('test_me').run(result)
3334
 
        if not result.wasStrictlySuccessful():
3335
 
            self.fail(output.getvalue())
3336
 
        # We get our value back
3337
 
        self.assertEquals('42', os.environ.get('MYVAR'))
3338
 
 
3339
 
 
3340
 
class TestIsolatedEnv(tests.TestCase):
3341
 
    """Test isolating tests from os.environ.
3342
 
 
3343
 
    Since we use tests that are already isolated from os.environ a bit of care
3344
 
    should be taken when designing the tests to avoid bootstrap side-effects.
3345
 
    The tests start an already clean os.environ which allow doing valid
3346
 
    assertions about which variables are present or not and design tests around
3347
 
    these assertions.
3348
 
    """
3349
 
 
3350
 
    class ScratchMonkey(tests.TestCase):
3351
 
 
3352
 
        def test_me(self):
3353
 
            pass
3354
 
 
3355
 
    def test_basics(self):
3356
 
        # Make sure we know the definition of BZR_HOME: not part of os.environ
3357
 
        # for tests.TestCase.
3358
 
        self.assertTrue('BZR_HOME' in tests.isolated_environ)
3359
 
        self.assertEquals(None, tests.isolated_environ['BZR_HOME'])
3360
 
        # Being part of isolated_environ, BZR_HOME should not appear here
3361
 
        self.assertFalse('BZR_HOME' in os.environ)
3362
 
        # Make sure we know the definition of LINES: part of os.environ for
3363
 
        # tests.TestCase
3364
 
        self.assertTrue('LINES' in tests.isolated_environ)
3365
 
        self.assertEquals('25', tests.isolated_environ['LINES'])
3366
 
        self.assertEquals('25', os.environ['LINES'])
3367
 
 
3368
 
    def test_injecting_unknown_variable(self):
3369
 
        # BZR_HOME is known to be absent from os.environ
3370
 
        test = self.ScratchMonkey('test_me')
3371
 
        tests.override_os_environ(test, {'BZR_HOME': 'foo'})
3372
 
        self.assertEquals('foo', os.environ['BZR_HOME'])
3373
 
        tests.restore_os_environ(test)
3374
 
        self.assertFalse('BZR_HOME' in os.environ)
3375
 
 
3376
 
    def test_injecting_known_variable(self):
3377
 
        test = self.ScratchMonkey('test_me')
3378
 
        # LINES is known to be present in os.environ
3379
 
        tests.override_os_environ(test, {'LINES': '42'})
3380
 
        self.assertEquals('42', os.environ['LINES'])
3381
 
        tests.restore_os_environ(test)
3382
 
        self.assertEquals('25', os.environ['LINES'])
3383
 
 
3384
 
    def test_deleting_variable(self):
3385
 
        test = self.ScratchMonkey('test_me')
3386
 
        # LINES is known to be present in os.environ
3387
 
        tests.override_os_environ(test, {'LINES': None})
3388
 
        self.assertTrue('LINES' not in os.environ)
3389
 
        tests.restore_os_environ(test)
3390
 
        self.assertEquals('25', os.environ['LINES'])
3391
 
 
3392
 
 
3393
 
class TestDocTestSuiteIsolation(tests.TestCase):
3394
 
    """Test that `tests.DocTestSuite` isolates doc tests from os.environ.
3395
 
 
3396
 
    Since tests.TestCase alreay provides an isolation from os.environ, we use
3397
 
    the clean environment as a base for testing. To precisely capture the
3398
 
    isolation provided by tests.DocTestSuite, we use doctest.DocTestSuite to
3399
 
    compare against.
3400
 
 
3401
 
    We want to make sure `tests.DocTestSuite` respect `tests.isolated_environ`,
3402
 
    not `os.environ` so each test overrides it to suit its needs.
3403
 
 
3404
 
    """
3405
 
 
3406
 
    def get_doctest_suite_for_string(self, klass, string):
3407
 
        class Finder(doctest.DocTestFinder):
3408
 
 
3409
 
            def find(*args, **kwargs):
3410
 
                test = doctest.DocTestParser().get_doctest(
3411
 
                    string, {}, 'foo', 'foo.py', 0)
3412
 
                return [test]
3413
 
 
3414
 
        suite = klass(test_finder=Finder())
3415
 
        return suite
3416
 
 
3417
 
    def run_doctest_suite_for_string(self, klass, string):
3418
 
        suite = self.get_doctest_suite_for_string(klass, string)
3419
 
        output = StringIO()
3420
 
        result = tests.TextTestResult(output, 0, 1)
3421
 
        suite.run(result)
3422
 
        return result, output
3423
 
 
3424
 
    def assertDocTestStringSucceds(self, klass, string):
3425
 
        result, output = self.run_doctest_suite_for_string(klass, string)
3426
 
        if not result.wasStrictlySuccessful():
3427
 
            self.fail(output.getvalue())
3428
 
 
3429
 
    def assertDocTestStringFails(self, klass, string):
3430
 
        result, output = self.run_doctest_suite_for_string(klass, string)
3431
 
        if result.wasStrictlySuccessful():
3432
 
            self.fail(output.getvalue())
3433
 
 
3434
 
    def test_injected_variable(self):
3435
 
        self.overrideAttr(tests, 'isolated_environ', {'LINES': '42'})
3436
 
        test = """
3437
 
            >>> import os
3438
 
            >>> os.environ['LINES']
3439
 
            '42'
3440
 
            """
3441
 
        # doctest.DocTestSuite fails as it sees '25'
3442
 
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
3443
 
        # tests.DocTestSuite sees '42'
3444
 
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
3445
 
 
3446
 
    def test_deleted_variable(self):
3447
 
        self.overrideAttr(tests, 'isolated_environ', {'LINES': None})
3448
 
        test = """
3449
 
            >>> import os
3450
 
            >>> os.environ.get('LINES')
3451
 
            """
3452
 
        # doctest.DocTestSuite fails as it sees '25'
3453
 
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
3454
 
        # tests.DocTestSuite sees None
3455
 
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
3456
 
 
3457
 
 
3458
 
class TestSelftestExcludePatterns(tests.TestCase):
3459
 
 
3460
 
    def setUp(self):
3461
 
        super(TestSelftestExcludePatterns, self).setUp()
3462
 
        self.overrideAttr(tests, 'test_suite', self.suite_factory)
3463
 
 
3464
 
    def suite_factory(self, keep_only=None, starting_with=None):
3465
 
        """A test suite factory with only a few tests."""
3466
 
        class Test(tests.TestCase):
3467
 
            def id(self):
3468
 
                # We don't need the full class path
3469
 
                return self._testMethodName
3470
 
            def a(self):
3471
 
                pass
3472
 
            def b(self):
3473
 
                pass
3474
 
            def c(self):
3475
 
                pass
3476
 
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
3477
 
 
3478
 
    def assertTestList(self, expected, *selftest_args):
3479
 
        # We rely on setUp installing the right test suite factory so we can
3480
 
        # test at the command level without loading the whole test suite
3481
 
        out, err = self.run_bzr(('selftest', '--list') + selftest_args)
3482
 
        actual = out.splitlines()
3483
 
        self.assertEquals(expected, actual)
3484
 
 
3485
 
    def test_full_list(self):
3486
 
        self.assertTestList(['a', 'b', 'c'])
3487
 
 
3488
 
    def test_single_exclude(self):
3489
 
        self.assertTestList(['b', 'c'], '-x', 'a')
3490
 
 
3491
 
    def test_mutiple_excludes(self):
3492
 
        self.assertTestList(['c'], '-x', 'a', '-x', 'b')
3493
 
 
3494
 
 
3495
 
class TestCounterHooks(tests.TestCase, SelfTestHelper):
3496
 
 
3497
 
    _test_needs_features = [features.subunit]
3498
 
 
3499
 
    def setUp(self):
3500
 
        super(TestCounterHooks, self).setUp()
3501
 
        class Test(tests.TestCase):
3502
 
 
3503
 
            def setUp(self):
3504
 
                super(Test, self).setUp()
3505
 
                self.hooks = hooks.Hooks()
3506
 
                self.hooks.add_hook('myhook', 'Foo bar blah', (2,4))
3507
 
                self.install_counter_hook(self.hooks, 'myhook')
3508
 
 
3509
 
            def no_hook(self):
3510
 
                pass
3511
 
 
3512
 
            def run_hook_once(self):
3513
 
                for hook in self.hooks['myhook']:
3514
 
                    hook(self)
3515
 
 
3516
 
        self.test_class = Test
3517
 
 
3518
 
    def assertHookCalls(self, expected_calls, test_name):
3519
 
        test = self.test_class(test_name)
3520
 
        result = unittest.TestResult()
3521
 
        test.run(result)
3522
 
        self.assertTrue(hasattr(test, '_counters'))
3523
 
        self.assertTrue(test._counters.has_key('myhook'))
3524
 
        self.assertEquals(expected_calls, test._counters['myhook'])
3525
 
 
3526
 
    def test_no_hook(self):
3527
 
        self.assertHookCalls(0, 'no_hook')
3528
 
 
3529
 
    def test_run_hook_once(self):
3530
 
        tt = features.testtools
3531
 
        if tt.module.__version__ < (0, 9, 8):
3532
 
            raise tests.TestSkipped('testtools-0.9.8 required for addDetail')
3533
 
        self.assertHookCalls(1, 'run_hook_once')