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