1
# Copyright (C) 2005-2011 Canonical Ltd
2
# Author: Robert Collins <robert.collins@canonical.com>
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23
from bzrlib import pyutils
25
# Mark this python module as being part of the implementation
26
# of unittest: this gives us better tracebacks where the last
27
# shown frame is the test code, not our assertXYZ.
31
class LogCollector(logging.Handler):
34
logging.Handler.__init__(self)
37
def emit(self, record):
38
self.records.append(record.getMessage())
41
def makeCollectingLogger():
42
"""I make a logger instance that collects its logs for programmatic analysis
43
-> (logger, collector)"""
44
logger=logging.Logger("collector")
45
handler=LogCollector()
46
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
47
logger.addHandler(handler)
48
return logger, handler
51
def visitTests(suite, visitor):
52
"""A foreign method for visiting the tests in a test suite."""
53
for test in suite._tests:
54
#Abusing types to avoid monkey patching unittest.TestCase.
55
# Maybe that would be better?
58
except AttributeError:
59
if isinstance(test, unittest.TestCase):
60
visitor.visitCase(test)
61
elif isinstance(test, unittest.TestSuite):
62
visitor.visitSuite(test)
63
visitTests(test, visitor)
65
print "unvisitable non-unittest.TestCase element %r (%r)" % (
69
class TestSuite(unittest.TestSuite):
70
"""I am an extended TestSuite with a visitor interface.
71
This is primarily to allow filtering of tests - and suites or
72
more in the future. An iterator of just tests wouldn't scale..."""
74
def visit(self, visitor):
75
"""visit the composite. Visiting is depth-first.
76
current callbacks are visitSuite and visitCase."""
77
visitor.visitSuite(self)
78
visitTests(self, visitor)
80
def run(self, result):
81
"""Run the tests in the suite, discarding references after running."""
87
self._tests = reversed(tests)
89
tests.pop().run(result)
93
class TestLoader(unittest.TestLoader):
94
"""Custom TestLoader to extend the stock python one."""
96
suiteClass = TestSuite
97
# Memoize test names by test class dict
100
def loadTestsFromModuleNames(self, names):
101
"""use a custom means to load tests from modules.
103
There is an undesirable glitch in the python TestLoader where a
104
import error is ignore. We think this can be solved by ensuring the
105
requested name is resolvable, if its not raising the original error.
107
result = self.suiteClass()
109
result.addTests(self.loadTestsFromModuleName(name))
112
def loadTestsFromModuleName(self, name):
113
result = self.suiteClass()
114
module = pyutils.get_named_object(name)
116
result.addTests(self.loadTestsFromModule(module))
119
def loadTestsFromModule(self, module):
120
"""Load tests from a module object.
122
This extension of the python test loader looks for an attribute
123
load_tests in the module object, and if not found falls back to the
124
regular python loadTestsFromModule.
126
If a load_tests attribute is found, it is called and the result is
129
load_tests should be defined like so:
130
>>> def load_tests(standard_tests, module, loader):
133
standard_tests is the tests found by the stock TestLoader in the
134
module, module and loader are the module and loader instances.
136
For instance, to run every test twice, you might do:
137
>>> def load_tests(standard_tests, module, loader):
138
>>> result = loader.suiteClass()
139
>>> for test in iter_suite_tests(standard_tests):
140
>>> result.addTests([test, test])
143
if sys.version_info < (2, 7):
144
basic_tests = super(TestLoader, self).loadTestsFromModule(module)
146
# GZ 2010-07-19: Python 2.7 unittest also uses load_tests but with
147
# a different and incompatible signature
148
basic_tests = super(TestLoader, self).loadTestsFromModule(module,
149
use_load_tests=False)
150
load_tests = getattr(module, "load_tests", None)
151
if load_tests is not None:
152
return load_tests(basic_tests, module, self)
156
def getTestCaseNames(self, test_case_class):
157
test_fn_names = self.test_func_names.get(test_case_class, None)
158
if test_fn_names is not None:
159
# We already know them
162
test_fn_names = unittest.TestLoader.getTestCaseNames(self,
164
self.test_func_names[test_case_class] = test_fn_names
168
class FilteredByModuleTestLoader(TestLoader):
169
"""A test loader that import only the needed modules."""
171
def __init__(self, needs_module):
174
:param needs_module: a callable taking a module name as a
175
parameter returing True if the module should be loaded.
177
TestLoader.__init__(self)
178
self.needs_module = needs_module
180
def loadTestsFromModuleName(self, name):
181
if self.needs_module(name):
182
return TestLoader.loadTestsFromModuleName(self, name)
184
return self.suiteClass()
187
class TestVisitor(object):
188
"""A visitor for Tests"""
190
def visitSuite(self, aTestSuite):
193
def visitCase(self, aTestCase):