runner.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. """Running tests"""
  2. import sys
  3. import time
  4. import warnings
  5. from . import result
  6. from .signals import registerResult
  7. __unittest = True
  8. class _WritelnDecorator(object):
  9. """Used to decorate file-like objects with a handy 'writeln' method"""
  10. def __init__(self,stream):
  11. self.stream = stream
  12. def __getattr__(self, attr):
  13. if attr in ('stream', '__getstate__'):
  14. raise AttributeError(attr)
  15. return getattr(self.stream,attr)
  16. def writeln(self, arg=None):
  17. if arg:
  18. self.write(arg)
  19. self.write('\n') # text-mode streams translate to \r\n if needed
  20. class TextTestResult(result.TestResult):
  21. """A test result class that can print formatted text results to a stream.
  22. Used by TextTestRunner.
  23. """
  24. separator1 = '=' * 70
  25. separator2 = '-' * 70
  26. def __init__(self, stream, descriptions, verbosity):
  27. super(TextTestResult, self).__init__(stream, descriptions, verbosity)
  28. self.stream = stream
  29. self.showAll = verbosity > 1
  30. self.dots = verbosity == 1
  31. self.descriptions = descriptions
  32. def getDescription(self, test):
  33. doc_first_line = test.shortDescription()
  34. if self.descriptions and doc_first_line:
  35. return '\n'.join((str(test), doc_first_line))
  36. else:
  37. return str(test)
  38. def startTest(self, test):
  39. super(TextTestResult, self).startTest(test)
  40. if self.showAll:
  41. self.stream.write(self.getDescription(test))
  42. self.stream.write(" ... ")
  43. self.stream.flush()
  44. def addSuccess(self, test):
  45. super(TextTestResult, self).addSuccess(test)
  46. if self.showAll:
  47. self.stream.writeln("ok")
  48. elif self.dots:
  49. self.stream.write('.')
  50. self.stream.flush()
  51. def addError(self, test, err):
  52. super(TextTestResult, self).addError(test, err)
  53. if self.showAll:
  54. self.stream.writeln("ERROR")
  55. elif self.dots:
  56. self.stream.write('E')
  57. self.stream.flush()
  58. def addFailure(self, test, err):
  59. super(TextTestResult, self).addFailure(test, err)
  60. if self.showAll:
  61. self.stream.writeln("FAIL")
  62. elif self.dots:
  63. self.stream.write('F')
  64. self.stream.flush()
  65. def addSkip(self, test, reason):
  66. super(TextTestResult, self).addSkip(test, reason)
  67. if self.showAll:
  68. self.stream.writeln("skipped {0!r}".format(reason))
  69. elif self.dots:
  70. self.stream.write("s")
  71. self.stream.flush()
  72. def addExpectedFailure(self, test, err):
  73. super(TextTestResult, self).addExpectedFailure(test, err)
  74. if self.showAll:
  75. self.stream.writeln("expected failure")
  76. elif self.dots:
  77. self.stream.write("x")
  78. self.stream.flush()
  79. def addUnexpectedSuccess(self, test):
  80. super(TextTestResult, self).addUnexpectedSuccess(test)
  81. if self.showAll:
  82. self.stream.writeln("unexpected success")
  83. elif self.dots:
  84. self.stream.write("u")
  85. self.stream.flush()
  86. def printErrors(self):
  87. if self.dots or self.showAll:
  88. self.stream.writeln()
  89. self.printErrorList('ERROR', self.errors)
  90. self.printErrorList('FAIL', self.failures)
  91. def printErrorList(self, flavour, errors):
  92. for test, err in errors:
  93. self.stream.writeln(self.separator1)
  94. self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
  95. self.stream.writeln(self.separator2)
  96. self.stream.writeln("%s" % err)
  97. class TextTestRunner(object):
  98. """A test runner class that displays results in textual form.
  99. It prints out the names of tests as they are run, errors as they
  100. occur, and a summary of the results at the end of the test run.
  101. """
  102. resultclass = TextTestResult
  103. def __init__(self, stream=None, descriptions=True, verbosity=1,
  104. failfast=False, buffer=False, resultclass=None, warnings=None,
  105. *, tb_locals=False):
  106. """Construct a TextTestRunner.
  107. Subclasses should accept **kwargs to ensure compatibility as the
  108. interface changes.
  109. """
  110. if stream is None:
  111. stream = sys.stderr
  112. self.stream = _WritelnDecorator(stream)
  113. self.descriptions = descriptions
  114. self.verbosity = verbosity
  115. self.failfast = failfast
  116. self.buffer = buffer
  117. self.tb_locals = tb_locals
  118. self.warnings = warnings
  119. if resultclass is not None:
  120. self.resultclass = resultclass
  121. def _makeResult(self):
  122. return self.resultclass(self.stream, self.descriptions, self.verbosity)
  123. def run(self, test):
  124. "Run the given test case or test suite."
  125. result = self._makeResult()
  126. registerResult(result)
  127. result.failfast = self.failfast
  128. result.buffer = self.buffer
  129. result.tb_locals = self.tb_locals
  130. with warnings.catch_warnings():
  131. if self.warnings:
  132. # if self.warnings is set, use it to filter all the warnings
  133. warnings.simplefilter(self.warnings)
  134. # if the filter is 'default' or 'always', special-case the
  135. # warnings from the deprecated unittest methods to show them
  136. # no more than once per module, because they can be fairly
  137. # noisy. The -Wd and -Wa flags can be used to bypass this
  138. # only when self.warnings is None.
  139. if self.warnings in ['default', 'always']:
  140. warnings.filterwarnings('module',
  141. category=DeprecationWarning,
  142. message='Please use assert\w+ instead.')
  143. startTime = time.time()
  144. startTestRun = getattr(result, 'startTestRun', None)
  145. if startTestRun is not None:
  146. startTestRun()
  147. try:
  148. test(result)
  149. finally:
  150. stopTestRun = getattr(result, 'stopTestRun', None)
  151. if stopTestRun is not None:
  152. stopTestRun()
  153. stopTime = time.time()
  154. timeTaken = stopTime - startTime
  155. result.printErrors()
  156. if hasattr(result, 'separator2'):
  157. self.stream.writeln(result.separator2)
  158. run = result.testsRun
  159. self.stream.writeln("Ran %d test%s in %.3fs" %
  160. (run, run != 1 and "s" or "", timeTaken))
  161. self.stream.writeln()
  162. expectedFails = unexpectedSuccesses = skipped = 0
  163. try:
  164. results = map(len, (result.expectedFailures,
  165. result.unexpectedSuccesses,
  166. result.skipped))
  167. except AttributeError:
  168. pass
  169. else:
  170. expectedFails, unexpectedSuccesses, skipped = results
  171. infos = []
  172. if not result.wasSuccessful():
  173. self.stream.write("FAILED")
  174. failed, errored = len(result.failures), len(result.errors)
  175. if failed:
  176. infos.append("failures=%d" % failed)
  177. if errored:
  178. infos.append("errors=%d" % errored)
  179. else:
  180. self.stream.write("OK")
  181. if skipped:
  182. infos.append("skipped=%d" % skipped)
  183. if expectedFails:
  184. infos.append("expected failures=%d" % expectedFails)
  185. if unexpectedSuccesses:
  186. infos.append("unexpected successes=%d" % unexpectedSuccesses)
  187. if infos:
  188. self.stream.writeln(" (%s)" % (", ".join(infos),))
  189. else:
  190. self.stream.write("\n")
  191. return result