Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1 | """TestSuite""" |
| 2 | |
| 3 | from . import case |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame^] | 4 | from . import util |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +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): |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame^] | 21 | return "<%s tests=%s>" % (util.strclass(self.__class__), list(self)) |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +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 | def __iter__(self): |
| 32 | return iter(self._tests) |
| 33 | |
| 34 | def countTestCases(self): |
| 35 | cases = 0 |
| 36 | for test in self: |
| 37 | cases += test.countTestCases() |
| 38 | return cases |
| 39 | |
| 40 | def addTest(self, test): |
| 41 | # sanity checks |
| 42 | if not hasattr(test, '__call__'): |
| 43 | raise TypeError("the test to add must be callable") |
| 44 | if isinstance(test, type) and issubclass(test, |
| 45 | (case.TestCase, TestSuite)): |
| 46 | raise TypeError("TestCases and TestSuites must be instantiated " |
| 47 | "before passing them to addTest()") |
| 48 | self._tests.append(test) |
| 49 | |
| 50 | def addTests(self, tests): |
| 51 | if isinstance(tests, str): |
| 52 | raise TypeError("tests must be an iterable of tests, not a string") |
| 53 | for test in tests: |
| 54 | self.addTest(test) |
| 55 | |
| 56 | def run(self, result): |
| 57 | for test in self: |
| 58 | if result.shouldStop: |
| 59 | break |
| 60 | test(result) |
| 61 | return result |
| 62 | |
| 63 | def __call__(self, *args, **kwds): |
| 64 | return self.run(*args, **kwds) |
| 65 | |
| 66 | def debug(self): |
| 67 | """Run the tests without collecting errors in a TestResult""" |
| 68 | for test in self: |
| 69 | test.debug() |