Benjamin Peterson | d7b0eeb | 2009-07-19 20:18:21 +0000 | [diff] [blame] | 1 | """TestSuite""" |
| 2 | |
| 3 | from . import case |
Michael Foord | e91ea56 | 2009-09-13 19:07:03 +0000 | [diff] [blame] | 4 | from . import util |
Benjamin Peterson | d7b0eeb | 2009-07-19 20:18:21 +0000 | [diff] [blame] | 5 | |
| 6 | |
| 7 | class TestSuite(object): |
| 8 | """A test suite is a composite test consisting of a number of TestCases. |
| 9 | |
| 10 | For use, create an instance of TestSuite, then add test case instances. |
| 11 | When all tests have been added, the suite can be passed to a test |
| 12 | runner, such as TextTestRunner. It will run the individual test cases |
| 13 | in the order in which they were added, aggregating the results. When |
| 14 | subclassing, do not forget to call the base class constructor. |
| 15 | """ |
| 16 | def __init__(self, tests=()): |
| 17 | self._tests = [] |
| 18 | self.addTests(tests) |
| 19 | |
| 20 | def __repr__(self): |
Michael Foord | e91ea56 | 2009-09-13 19:07:03 +0000 | [diff] [blame] | 21 | return "<%s tests=%s>" % (util.strclass(self.__class__), list(self)) |
Benjamin Peterson | d7b0eeb | 2009-07-19 20:18:21 +0000 | [diff] [blame] | 22 | |
| 23 | def __eq__(self, other): |
| 24 | if not isinstance(other, self.__class__): |
| 25 | return NotImplemented |
| 26 | return list(self) == list(other) |
| 27 | |
| 28 | def __ne__(self, other): |
| 29 | return not self == other |
| 30 | |
| 31 | # Can't guarantee hash invariant, so flag as unhashable |
| 32 | __hash__ = None |
| 33 | |
| 34 | def __iter__(self): |
| 35 | return iter(self._tests) |
| 36 | |
| 37 | def countTestCases(self): |
| 38 | cases = 0 |
| 39 | for test in self: |
| 40 | cases += test.countTestCases() |
| 41 | return cases |
| 42 | |
| 43 | def addTest(self, test): |
| 44 | # sanity checks |
| 45 | if not hasattr(test, '__call__'): |
R. David Murray | b5d7400 | 2010-01-28 21:16:33 +0000 | [diff] [blame^] | 46 | raise TypeError("{} is not callable".format(repr(test))) |
Benjamin Peterson | d7b0eeb | 2009-07-19 20:18:21 +0000 | [diff] [blame] | 47 | if isinstance(test, type) and issubclass(test, |
| 48 | (case.TestCase, TestSuite)): |
| 49 | raise TypeError("TestCases and TestSuites must be instantiated " |
| 50 | "before passing them to addTest()") |
| 51 | self._tests.append(test) |
| 52 | |
| 53 | def addTests(self, tests): |
| 54 | if isinstance(tests, basestring): |
| 55 | raise TypeError("tests must be an iterable of tests, not a string") |
| 56 | for test in tests: |
| 57 | self.addTest(test) |
| 58 | |
| 59 | def run(self, result): |
| 60 | for test in self: |
| 61 | if result.shouldStop: |
| 62 | break |
| 63 | test(result) |
| 64 | return result |
| 65 | |
| 66 | def __call__(self, *args, **kwds): |
| 67 | return self.run(*args, **kwds) |
| 68 | |
| 69 | def debug(self): |
| 70 | """Run the tests without collecting errors in a TestResult""" |
| 71 | for test in self: |
| 72 | test.debug() |