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