1
# Copyright (C) 2005 by Canonical Ltd
 
 
3
# This program is free software; you can redistribute it and/or modify
 
 
4
# it under the terms of the GNU General Public License as published by
 
 
5
# the Free Software Foundation; either version 2 of the License, or
 
 
6
# (at your option) any later version.
 
 
8
# This program is distributed in the hope that it will be useful,
 
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
11
# GNU General Public License for more details.
 
 
13
# You should have received a copy of the GNU General Public License
 
 
14
# along with this program; if not, write to the Free Software
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
18
"""Enhanced layer on unittest.
 
 
20
This does several things:
 
 
22
* nicer reporting as tests run
 
 
24
* test code can log messages into a buffer that is recorded to disk
 
 
25
  and displayed if the test fails
 
 
27
* tests can be run in a separate directory, which is useful for code that
 
 
30
* utilities to run external commands and check their return code
 
 
33
Test cases should normally subclass testsweet.TestCase.  The test runner should
 
 
36
This is meant to become independent of bzr, though that's not quite
 
 
42
from bzrlib.selftest import TestUtil
 
 
44
# XXX: Don't need this anymore now we depend on python2.4
 
 
45
def _need_subprocess():
 
 
46
    sys.stderr.write("sorry, this test suite requires the subprocess module\n"
 
 
47
                     "this is shipped with python2.4 and available separately for 2.3\n")
 
 
50
class CommandFailed(Exception):
 
 
54
class TestSkipped(Exception):
 
 
55
    """Indicates that a test was intentionally skipped, rather than failing."""
 
 
60
class EarlyStoppingTestResultAdapter(object):
 
 
61
    """An adapter for TestResult to stop at the first first failure or error"""
 
 
63
    def __init__(self, result):
 
 
66
    def addError(self, test, err):
 
 
67
        self._result.addError(test, err)
 
 
70
    def addFailure(self, test, err):
 
 
71
        self._result.addFailure(test, err)
 
 
74
    def __getattr__(self, name):
 
 
75
        return getattr(self._result, name)
 
 
77
    def __setattr__(self, name, value):
 
 
79
            object.__setattr__(self, name, value)
 
 
80
        return setattr(self._result, name, value)
 
 
83
class _MyResult(unittest._TextTestResult):
 
 
87
    No special behaviour for now.
 
 
90
    def startTest(self, test):
 
 
91
        unittest.TestResult.startTest(self, test)
 
 
92
        # TODO: Maybe show test.shortDescription somewhere?
 
 
94
        # python2.3 has the bad habit of just "runit" for doctests
 
 
96
            what = test.shortDescription()
 
 
98
            self.stream.write('%-60.60s' % what)
 
 
101
    def addError(self, test, err):
 
 
102
        super(_MyResult, self).addError(test, err)
 
 
105
    def addFailure(self, test, err):
 
 
106
        super(_MyResult, self).addFailure(test, err)
 
 
109
    def addSuccess(self, test):
 
 
111
            self.stream.writeln('OK')
 
 
113
            self.stream.write('~')
 
 
115
        unittest.TestResult.addSuccess(self, test)
 
 
117
    def printErrorList(self, flavour, errors):
 
 
118
        for test, err in errors:
 
 
119
            self.stream.writeln(self.separator1)
 
 
120
            self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
 
 
121
            self.stream.writeln(self.separator2)
 
 
122
            self.stream.writeln("%s" % err)
 
 
123
            if hasattr(test, '_get_log'):
 
 
124
                self.stream.writeln()
 
 
125
                self.stream.writeln('log from this test:')
 
 
126
                print >>self.stream, test._get_log()
 
 
129
class TextTestRunner(unittest.TextTestRunner):
 
 
131
    def _makeResult(self):
 
 
132
        result = _MyResult(self.stream, self.descriptions, self.verbosity)
 
 
133
        return EarlyStoppingTestResultAdapter(result)
 
 
136
class filteringVisitor(TestUtil.TestVisitor):
 
 
137
    """I accruse all the testCases I visit that pass a regexp filter on id
 
 
141
    def __init__(self, filter):
 
 
143
        TestUtil.TestVisitor.__init__(self)
 
 
145
        self.filter=re.compile(filter)
 
 
148
        """answer the suite we are building"""
 
 
149
        if self._suite is None:
 
 
150
            self._suite=TestUtil.TestSuite()
 
 
153
    def visitCase(self, aCase):
 
 
154
        if self.filter.match(aCase.id()):
 
 
155
            self.suite().addTest(aCase)
 
 
158
def run_suite(suite, name='test', verbose=False, pattern=".*"):
 
 
160
    from bzrlib.selftest import FunctionalTestCase
 
 
161
    FunctionalTestCase._TEST_NAME = name
 
 
166
    runner = TextTestRunner(stream=sys.stdout,
 
 
169
    visitor = filteringVisitor(pattern)
 
 
171
    result = runner.run(visitor.suite())
 
 
172
    # This is still a little bogus, 
 
 
173
    # but only a little. Folk not using our testrunner will
 
 
174
    # have to delete their temp directories themselves.
 
 
175
    if result.wasSuccessful():
 
 
176
        if FunctionalTestCase.TEST_ROOT:
 
 
177
            shutil.rmtree(FunctionalTestCase.TEST_ROOT) 
 
 
179
        print "Failed tests working directories are in '%s'\n" % FunctionalTestCase.TEST_ROOT
 
 
180
    return result.wasSuccessful()