jpayne@68: """TestSuite""" jpayne@68: jpayne@68: import sys jpayne@68: jpayne@68: from . import case jpayne@68: from . import util jpayne@68: jpayne@68: __unittest = True jpayne@68: jpayne@68: jpayne@68: def _call_if_exists(parent, attr): jpayne@68: func = getattr(parent, attr, lambda: None) jpayne@68: func() jpayne@68: jpayne@68: jpayne@68: class BaseTestSuite(object): jpayne@68: """A simple test suite that doesn't provide class or module shared fixtures. jpayne@68: """ jpayne@68: _cleanup = True jpayne@68: jpayne@68: def __init__(self, tests=()): jpayne@68: self._tests = [] jpayne@68: self._removed_tests = 0 jpayne@68: self.addTests(tests) jpayne@68: jpayne@68: def __repr__(self): jpayne@68: return "<%s tests=%s>" % (util.strclass(self.__class__), list(self)) jpayne@68: jpayne@68: def __eq__(self, other): jpayne@68: if not isinstance(other, self.__class__): jpayne@68: return NotImplemented jpayne@68: return list(self) == list(other) jpayne@68: jpayne@68: def __iter__(self): jpayne@68: return iter(self._tests) jpayne@68: jpayne@68: def countTestCases(self): jpayne@68: cases = self._removed_tests jpayne@68: for test in self: jpayne@68: if test: jpayne@68: cases += test.countTestCases() jpayne@68: return cases jpayne@68: jpayne@68: def addTest(self, test): jpayne@68: # sanity checks jpayne@68: if not callable(test): jpayne@68: raise TypeError("{} is not callable".format(repr(test))) jpayne@68: if isinstance(test, type) and issubclass(test, jpayne@68: (case.TestCase, TestSuite)): jpayne@68: raise TypeError("TestCases and TestSuites must be instantiated " jpayne@68: "before passing them to addTest()") jpayne@68: self._tests.append(test) jpayne@68: jpayne@68: def addTests(self, tests): jpayne@68: if isinstance(tests, str): jpayne@68: raise TypeError("tests must be an iterable of tests, not a string") jpayne@68: for test in tests: jpayne@68: self.addTest(test) jpayne@68: jpayne@68: def run(self, result): jpayne@68: for index, test in enumerate(self): jpayne@68: if result.shouldStop: jpayne@68: break jpayne@68: test(result) jpayne@68: if self._cleanup: jpayne@68: self._removeTestAtIndex(index) jpayne@68: return result jpayne@68: jpayne@68: def _removeTestAtIndex(self, index): jpayne@68: """Stop holding a reference to the TestCase at index.""" jpayne@68: try: jpayne@68: test = self._tests[index] jpayne@68: except TypeError: jpayne@68: # support for suite implementations that have overridden self._tests jpayne@68: pass jpayne@68: else: jpayne@68: # Some unittest tests add non TestCase/TestSuite objects to jpayne@68: # the suite. jpayne@68: if hasattr(test, 'countTestCases'): jpayne@68: self._removed_tests += test.countTestCases() jpayne@68: self._tests[index] = None jpayne@68: jpayne@68: def __call__(self, *args, **kwds): jpayne@68: return self.run(*args, **kwds) jpayne@68: jpayne@68: def debug(self): jpayne@68: """Run the tests without collecting errors in a TestResult""" jpayne@68: for test in self: jpayne@68: test.debug() jpayne@68: jpayne@68: jpayne@68: class TestSuite(BaseTestSuite): jpayne@68: """A test suite is a composite test consisting of a number of TestCases. jpayne@68: jpayne@68: For use, create an instance of TestSuite, then add test case instances. jpayne@68: When all tests have been added, the suite can be passed to a test jpayne@68: runner, such as TextTestRunner. It will run the individual test cases jpayne@68: in the order in which they were added, aggregating the results. When jpayne@68: subclassing, do not forget to call the base class constructor. jpayne@68: """ jpayne@68: jpayne@68: def run(self, result, debug=False): jpayne@68: topLevel = False jpayne@68: if getattr(result, '_testRunEntered', False) is False: jpayne@68: result._testRunEntered = topLevel = True jpayne@68: jpayne@68: for index, test in enumerate(self): jpayne@68: if result.shouldStop: jpayne@68: break jpayne@68: jpayne@68: if _isnotsuite(test): jpayne@68: self._tearDownPreviousClass(test, result) jpayne@68: self._handleModuleFixture(test, result) jpayne@68: self._handleClassSetUp(test, result) jpayne@68: result._previousTestClass = test.__class__ jpayne@68: jpayne@68: if (getattr(test.__class__, '_classSetupFailed', False) or jpayne@68: getattr(result, '_moduleSetUpFailed', False)): jpayne@68: continue jpayne@68: jpayne@68: if not debug: jpayne@68: test(result) jpayne@68: else: jpayne@68: test.debug() jpayne@68: jpayne@68: if self._cleanup: jpayne@68: self._removeTestAtIndex(index) jpayne@68: jpayne@68: if topLevel: jpayne@68: self._tearDownPreviousClass(None, result) jpayne@68: self._handleModuleTearDown(result) jpayne@68: result._testRunEntered = False jpayne@68: return result jpayne@68: jpayne@68: def debug(self): jpayne@68: """Run the tests without collecting errors in a TestResult""" jpayne@68: debug = _DebugResult() jpayne@68: self.run(debug, True) jpayne@68: jpayne@68: ################################ jpayne@68: jpayne@68: def _handleClassSetUp(self, test, result): jpayne@68: previousClass = getattr(result, '_previousTestClass', None) jpayne@68: currentClass = test.__class__ jpayne@68: if currentClass == previousClass: jpayne@68: return jpayne@68: if result._moduleSetUpFailed: jpayne@68: return jpayne@68: if getattr(currentClass, "__unittest_skip__", False): jpayne@68: return jpayne@68: jpayne@68: try: jpayne@68: currentClass._classSetupFailed = False jpayne@68: except TypeError: jpayne@68: # test may actually be a function jpayne@68: # so its class will be a builtin-type jpayne@68: pass jpayne@68: jpayne@68: setUpClass = getattr(currentClass, 'setUpClass', None) jpayne@68: if setUpClass is not None: jpayne@68: _call_if_exists(result, '_setupStdout') jpayne@68: try: jpayne@68: setUpClass() jpayne@68: except Exception as e: jpayne@68: if isinstance(result, _DebugResult): jpayne@68: raise jpayne@68: currentClass._classSetupFailed = True jpayne@68: className = util.strclass(currentClass) jpayne@68: self._createClassOrModuleLevelException(result, e, jpayne@68: 'setUpClass', jpayne@68: className) jpayne@68: finally: jpayne@68: _call_if_exists(result, '_restoreStdout') jpayne@68: if currentClass._classSetupFailed is True: jpayne@68: currentClass.doClassCleanups() jpayne@68: if len(currentClass.tearDown_exceptions) > 0: jpayne@68: for exc in currentClass.tearDown_exceptions: jpayne@68: self._createClassOrModuleLevelException( jpayne@68: result, exc[1], 'setUpClass', className, jpayne@68: info=exc) jpayne@68: jpayne@68: def _get_previous_module(self, result): jpayne@68: previousModule = None jpayne@68: previousClass = getattr(result, '_previousTestClass', None) jpayne@68: if previousClass is not None: jpayne@68: previousModule = previousClass.__module__ jpayne@68: return previousModule jpayne@68: jpayne@68: jpayne@68: def _handleModuleFixture(self, test, result): jpayne@68: previousModule = self._get_previous_module(result) jpayne@68: currentModule = test.__class__.__module__ jpayne@68: if currentModule == previousModule: jpayne@68: return jpayne@68: jpayne@68: self._handleModuleTearDown(result) jpayne@68: jpayne@68: jpayne@68: result._moduleSetUpFailed = False jpayne@68: try: jpayne@68: module = sys.modules[currentModule] jpayne@68: except KeyError: jpayne@68: return jpayne@68: setUpModule = getattr(module, 'setUpModule', None) jpayne@68: if setUpModule is not None: jpayne@68: _call_if_exists(result, '_setupStdout') jpayne@68: try: jpayne@68: setUpModule() jpayne@68: except Exception as e: jpayne@68: try: jpayne@68: case.doModuleCleanups() jpayne@68: except Exception as exc: jpayne@68: self._createClassOrModuleLevelException(result, exc, jpayne@68: 'setUpModule', jpayne@68: currentModule) jpayne@68: if isinstance(result, _DebugResult): jpayne@68: raise jpayne@68: result._moduleSetUpFailed = True jpayne@68: self._createClassOrModuleLevelException(result, e, jpayne@68: 'setUpModule', jpayne@68: currentModule) jpayne@68: finally: jpayne@68: _call_if_exists(result, '_restoreStdout') jpayne@68: jpayne@68: def _createClassOrModuleLevelException(self, result, exc, method_name, jpayne@68: parent, info=None): jpayne@68: errorName = f'{method_name} ({parent})' jpayne@68: self._addClassOrModuleLevelException(result, exc, errorName, info) jpayne@68: jpayne@68: def _addClassOrModuleLevelException(self, result, exception, errorName, jpayne@68: info=None): jpayne@68: error = _ErrorHolder(errorName) jpayne@68: addSkip = getattr(result, 'addSkip', None) jpayne@68: if addSkip is not None and isinstance(exception, case.SkipTest): jpayne@68: addSkip(error, str(exception)) jpayne@68: else: jpayne@68: if not info: jpayne@68: result.addError(error, sys.exc_info()) jpayne@68: else: jpayne@68: result.addError(error, info) jpayne@68: jpayne@68: def _handleModuleTearDown(self, result): jpayne@68: previousModule = self._get_previous_module(result) jpayne@68: if previousModule is None: jpayne@68: return jpayne@68: if result._moduleSetUpFailed: jpayne@68: return jpayne@68: jpayne@68: try: jpayne@68: module = sys.modules[previousModule] jpayne@68: except KeyError: jpayne@68: return jpayne@68: jpayne@68: tearDownModule = getattr(module, 'tearDownModule', None) jpayne@68: if tearDownModule is not None: jpayne@68: _call_if_exists(result, '_setupStdout') jpayne@68: try: jpayne@68: tearDownModule() jpayne@68: except Exception as e: jpayne@68: if isinstance(result, _DebugResult): jpayne@68: raise jpayne@68: self._createClassOrModuleLevelException(result, e, jpayne@68: 'tearDownModule', jpayne@68: previousModule) jpayne@68: finally: jpayne@68: _call_if_exists(result, '_restoreStdout') jpayne@68: try: jpayne@68: case.doModuleCleanups() jpayne@68: except Exception as e: jpayne@68: self._createClassOrModuleLevelException(result, e, jpayne@68: 'tearDownModule', jpayne@68: previousModule) jpayne@68: jpayne@68: def _tearDownPreviousClass(self, test, result): jpayne@68: previousClass = getattr(result, '_previousTestClass', None) jpayne@68: currentClass = test.__class__ jpayne@68: if currentClass == previousClass: jpayne@68: return jpayne@68: if getattr(previousClass, '_classSetupFailed', False): jpayne@68: return jpayne@68: if getattr(result, '_moduleSetUpFailed', False): jpayne@68: return jpayne@68: if getattr(previousClass, "__unittest_skip__", False): jpayne@68: return jpayne@68: jpayne@68: tearDownClass = getattr(previousClass, 'tearDownClass', None) jpayne@68: if tearDownClass is not None: jpayne@68: _call_if_exists(result, '_setupStdout') jpayne@68: try: jpayne@68: tearDownClass() jpayne@68: except Exception as e: jpayne@68: if isinstance(result, _DebugResult): jpayne@68: raise jpayne@68: className = util.strclass(previousClass) jpayne@68: self._createClassOrModuleLevelException(result, e, jpayne@68: 'tearDownClass', jpayne@68: className) jpayne@68: finally: jpayne@68: _call_if_exists(result, '_restoreStdout') jpayne@68: previousClass.doClassCleanups() jpayne@68: if len(previousClass.tearDown_exceptions) > 0: jpayne@68: for exc in previousClass.tearDown_exceptions: jpayne@68: className = util.strclass(previousClass) jpayne@68: self._createClassOrModuleLevelException(result, exc[1], jpayne@68: 'tearDownClass', jpayne@68: className, jpayne@68: info=exc) jpayne@68: jpayne@68: jpayne@68: class _ErrorHolder(object): jpayne@68: """ jpayne@68: Placeholder for a TestCase inside a result. As far as a TestResult jpayne@68: is concerned, this looks exactly like a unit test. Used to insert jpayne@68: arbitrary errors into a test suite run. jpayne@68: """ jpayne@68: # Inspired by the ErrorHolder from Twisted: jpayne@68: # http://twistedmatrix.com/trac/browser/trunk/twisted/trial/runner.py jpayne@68: jpayne@68: # attribute used by TestResult._exc_info_to_string jpayne@68: failureException = None jpayne@68: jpayne@68: def __init__(self, description): jpayne@68: self.description = description jpayne@68: jpayne@68: def id(self): jpayne@68: return self.description jpayne@68: jpayne@68: def shortDescription(self): jpayne@68: return None jpayne@68: jpayne@68: def __repr__(self): jpayne@68: return "" % (self.description,) jpayne@68: jpayne@68: def __str__(self): jpayne@68: return self.id() jpayne@68: jpayne@68: def run(self, result): jpayne@68: # could call result.addError(...) - but this test-like object jpayne@68: # shouldn't be run anyway jpayne@68: pass jpayne@68: jpayne@68: def __call__(self, result): jpayne@68: return self.run(result) jpayne@68: jpayne@68: def countTestCases(self): jpayne@68: return 0 jpayne@68: jpayne@68: def _isnotsuite(test): jpayne@68: "A crude way to tell apart testcases and suites with duck-typing" jpayne@68: try: jpayne@68: iter(test) jpayne@68: except TypeError: jpayne@68: return True jpayne@68: return False jpayne@68: jpayne@68: jpayne@68: class _DebugResult(object): jpayne@68: "Used by the TestSuite to hold previous class when running in debug." jpayne@68: _previousTestClass = None jpayne@68: _moduleSetUpFailed = False jpayne@68: shouldStop = False