suite.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. """TestSuite"""
  2. import sys
  3. from . import case
  4. from . import util
  5. __unittest = True
  6. def _call_if_exists(parent, attr):
  7. func = getattr(parent, attr, lambda: None)
  8. func()
  9. class BaseTestSuite(object):
  10. """A simple test suite that doesn't provide class or module shared fixtures.
  11. """
  12. _cleanup = True
  13. def __init__(self, tests=()):
  14. self._tests = []
  15. self._removed_tests = 0
  16. self.addTests(tests)
  17. def __repr__(self):
  18. return "<%s tests=%s>" % (util.strclass(self.__class__), list(self))
  19. def __eq__(self, other):
  20. if not isinstance(other, self.__class__):
  21. return NotImplemented
  22. return list(self) == list(other)
  23. def __iter__(self):
  24. return iter(self._tests)
  25. def countTestCases(self):
  26. cases = self._removed_tests
  27. for test in self:
  28. if test:
  29. cases += test.countTestCases()
  30. return cases
  31. def addTest(self, test):
  32. # sanity checks
  33. if not callable(test):
  34. raise TypeError("{} is not callable".format(repr(test)))
  35. if isinstance(test, type) and issubclass(test,
  36. (case.TestCase, TestSuite)):
  37. raise TypeError("TestCases and TestSuites must be instantiated "
  38. "before passing them to addTest()")
  39. self._tests.append(test)
  40. def addTests(self, tests):
  41. if isinstance(tests, str):
  42. raise TypeError("tests must be an iterable of tests, not a string")
  43. for test in tests:
  44. self.addTest(test)
  45. def run(self, result):
  46. for index, test in enumerate(self):
  47. if result.shouldStop:
  48. break
  49. test(result)
  50. if self._cleanup:
  51. self._removeTestAtIndex(index)
  52. return result
  53. def _removeTestAtIndex(self, index):
  54. """Stop holding a reference to the TestCase at index."""
  55. try:
  56. test = self._tests[index]
  57. except TypeError:
  58. # support for suite implementations that have overridden self._tests
  59. pass
  60. else:
  61. # Some unittest tests add non TestCase/TestSuite objects to
  62. # the suite.
  63. if hasattr(test, 'countTestCases'):
  64. self._removed_tests += test.countTestCases()
  65. self._tests[index] = None
  66. def __call__(self, *args, **kwds):
  67. return self.run(*args, **kwds)
  68. def debug(self):
  69. """Run the tests without collecting errors in a TestResult"""
  70. for test in self:
  71. test.debug()
  72. class TestSuite(BaseTestSuite):
  73. """A test suite is a composite test consisting of a number of TestCases.
  74. For use, create an instance of TestSuite, then add test case instances.
  75. When all tests have been added, the suite can be passed to a test
  76. runner, such as TextTestRunner. It will run the individual test cases
  77. in the order in which they were added, aggregating the results. When
  78. subclassing, do not forget to call the base class constructor.
  79. """
  80. def run(self, result, debug=False):
  81. topLevel = False
  82. if getattr(result, '_testRunEntered', False) is False:
  83. result._testRunEntered = topLevel = True
  84. for index, test in enumerate(self):
  85. if result.shouldStop:
  86. break
  87. if _isnotsuite(test):
  88. self._tearDownPreviousClass(test, result)
  89. self._handleModuleFixture(test, result)
  90. self._handleClassSetUp(test, result)
  91. result._previousTestClass = test.__class__
  92. if (getattr(test.__class__, '_classSetupFailed', False) or
  93. getattr(result, '_moduleSetUpFailed', False)):
  94. continue
  95. if not debug:
  96. test(result)
  97. else:
  98. test.debug()
  99. if self._cleanup:
  100. self._removeTestAtIndex(index)
  101. if topLevel:
  102. self._tearDownPreviousClass(None, result)
  103. self._handleModuleTearDown(result)
  104. result._testRunEntered = False
  105. return result
  106. def debug(self):
  107. """Run the tests without collecting errors in a TestResult"""
  108. debug = _DebugResult()
  109. self.run(debug, True)
  110. ################################
  111. def _handleClassSetUp(self, test, result):
  112. previousClass = getattr(result, '_previousTestClass', None)
  113. currentClass = test.__class__
  114. if currentClass == previousClass:
  115. return
  116. if result._moduleSetUpFailed:
  117. return
  118. if getattr(currentClass, "__unittest_skip__", False):
  119. return
  120. try:
  121. currentClass._classSetupFailed = False
  122. except TypeError:
  123. # test may actually be a function
  124. # so its class will be a builtin-type
  125. pass
  126. setUpClass = getattr(currentClass, 'setUpClass', None)
  127. if setUpClass is not None:
  128. _call_if_exists(result, '_setupStdout')
  129. try:
  130. setUpClass()
  131. except Exception as e:
  132. if isinstance(result, _DebugResult):
  133. raise
  134. currentClass._classSetupFailed = True
  135. className = util.strclass(currentClass)
  136. errorName = 'setUpClass (%s)' % className
  137. self._addClassOrModuleLevelException(result, e, errorName)
  138. finally:
  139. _call_if_exists(result, '_restoreStdout')
  140. def _get_previous_module(self, result):
  141. previousModule = None
  142. previousClass = getattr(result, '_previousTestClass', None)
  143. if previousClass is not None:
  144. previousModule = previousClass.__module__
  145. return previousModule
  146. def _handleModuleFixture(self, test, result):
  147. previousModule = self._get_previous_module(result)
  148. currentModule = test.__class__.__module__
  149. if currentModule == previousModule:
  150. return
  151. self._handleModuleTearDown(result)
  152. result._moduleSetUpFailed = False
  153. try:
  154. module = sys.modules[currentModule]
  155. except KeyError:
  156. return
  157. setUpModule = getattr(module, 'setUpModule', None)
  158. if setUpModule is not None:
  159. _call_if_exists(result, '_setupStdout')
  160. try:
  161. setUpModule()
  162. except Exception as e:
  163. if isinstance(result, _DebugResult):
  164. raise
  165. result._moduleSetUpFailed = True
  166. errorName = 'setUpModule (%s)' % currentModule
  167. self._addClassOrModuleLevelException(result, e, errorName)
  168. finally:
  169. _call_if_exists(result, '_restoreStdout')
  170. def _addClassOrModuleLevelException(self, result, exception, errorName):
  171. error = _ErrorHolder(errorName)
  172. addSkip = getattr(result, 'addSkip', None)
  173. if addSkip is not None and isinstance(exception, case.SkipTest):
  174. addSkip(error, str(exception))
  175. else:
  176. result.addError(error, sys.exc_info())
  177. def _handleModuleTearDown(self, result):
  178. previousModule = self._get_previous_module(result)
  179. if previousModule is None:
  180. return
  181. if result._moduleSetUpFailed:
  182. return
  183. try:
  184. module = sys.modules[previousModule]
  185. except KeyError:
  186. return
  187. tearDownModule = getattr(module, 'tearDownModule', None)
  188. if tearDownModule is not None:
  189. _call_if_exists(result, '_setupStdout')
  190. try:
  191. tearDownModule()
  192. except Exception as e:
  193. if isinstance(result, _DebugResult):
  194. raise
  195. errorName = 'tearDownModule (%s)' % previousModule
  196. self._addClassOrModuleLevelException(result, e, errorName)
  197. finally:
  198. _call_if_exists(result, '_restoreStdout')
  199. def _tearDownPreviousClass(self, test, result):
  200. previousClass = getattr(result, '_previousTestClass', None)
  201. currentClass = test.__class__
  202. if currentClass == previousClass:
  203. return
  204. if getattr(previousClass, '_classSetupFailed', False):
  205. return
  206. if getattr(result, '_moduleSetUpFailed', False):
  207. return
  208. if getattr(previousClass, "__unittest_skip__", False):
  209. return
  210. tearDownClass = getattr(previousClass, 'tearDownClass', None)
  211. if tearDownClass is not None:
  212. _call_if_exists(result, '_setupStdout')
  213. try:
  214. tearDownClass()
  215. except Exception as e:
  216. if isinstance(result, _DebugResult):
  217. raise
  218. className = util.strclass(previousClass)
  219. errorName = 'tearDownClass (%s)' % className
  220. self._addClassOrModuleLevelException(result, e, errorName)
  221. finally:
  222. _call_if_exists(result, '_restoreStdout')
  223. class _ErrorHolder(object):
  224. """
  225. Placeholder for a TestCase inside a result. As far as a TestResult
  226. is concerned, this looks exactly like a unit test. Used to insert
  227. arbitrary errors into a test suite run.
  228. """
  229. # Inspired by the ErrorHolder from Twisted:
  230. # http://twistedmatrix.com/trac/browser/trunk/twisted/trial/runner.py
  231. # attribute used by TestResult._exc_info_to_string
  232. failureException = None
  233. def __init__(self, description):
  234. self.description = description
  235. def id(self):
  236. return self.description
  237. def shortDescription(self):
  238. return None
  239. def __repr__(self):
  240. return "<ErrorHolder description=%r>" % (self.description,)
  241. def __str__(self):
  242. return self.id()
  243. def run(self, result):
  244. # could call result.addError(...) - but this test-like object
  245. # shouldn't be run anyway
  246. pass
  247. def __call__(self, result):
  248. return self.run(result)
  249. def countTestCases(self):
  250. return 0
  251. def _isnotsuite(test):
  252. "A crude way to tell apart testcases and suites with duck-typing"
  253. try:
  254. iter(test)
  255. except TypeError:
  256. return True
  257. return False
  258. class _DebugResult(object):
  259. "Used by the TestSuite to hold previous class when running in debug."
  260. _previousTestClass = None
  261. _moduleSetUpFailed = False
  262. shouldStop = False