result.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. """Test result object"""
  2. import io
  3. import sys
  4. import traceback
  5. from . import util
  6. from functools import wraps
  7. __unittest = True
  8. def failfast(method):
  9. @wraps(method)
  10. def inner(self, *args, **kw):
  11. if getattr(self, 'failfast', False):
  12. self.stop()
  13. return method(self, *args, **kw)
  14. return inner
  15. STDOUT_LINE = '\nStdout:\n%s'
  16. STDERR_LINE = '\nStderr:\n%s'
  17. class TestResult(object):
  18. """Holder for test result information.
  19. Test results are automatically managed by the TestCase and TestSuite
  20. classes, and do not need to be explicitly manipulated by writers of tests.
  21. Each instance holds the total number of tests run, and collections of
  22. failures and errors that occurred among those test runs. The collections
  23. contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
  24. formatted traceback of the error that occurred.
  25. """
  26. _previousTestClass = None
  27. _testRunEntered = False
  28. _moduleSetUpFailed = False
  29. def __init__(self, stream=None, descriptions=None, verbosity=None):
  30. self.failfast = False
  31. self.failures = []
  32. self.errors = []
  33. self.testsRun = 0
  34. self.skipped = []
  35. self.expectedFailures = []
  36. self.unexpectedSuccesses = []
  37. self.shouldStop = False
  38. self.buffer = False
  39. self.tb_locals = False
  40. self._stdout_buffer = None
  41. self._stderr_buffer = None
  42. self._original_stdout = sys.stdout
  43. self._original_stderr = sys.stderr
  44. self._mirrorOutput = False
  45. def printErrors(self):
  46. "Called by TestRunner after test run"
  47. def startTest(self, test):
  48. "Called when the given test is about to be run"
  49. self.testsRun += 1
  50. self._mirrorOutput = False
  51. self._setupStdout()
  52. def _setupStdout(self):
  53. if self.buffer:
  54. if self._stderr_buffer is None:
  55. self._stderr_buffer = io.StringIO()
  56. self._stdout_buffer = io.StringIO()
  57. sys.stdout = self._stdout_buffer
  58. sys.stderr = self._stderr_buffer
  59. def startTestRun(self):
  60. """Called once before any tests are executed.
  61. See startTest for a method called before each test.
  62. """
  63. def stopTest(self, test):
  64. """Called when the given test has been run"""
  65. self._restoreStdout()
  66. self._mirrorOutput = False
  67. def _restoreStdout(self):
  68. if self.buffer:
  69. if self._mirrorOutput:
  70. output = sys.stdout.getvalue()
  71. error = sys.stderr.getvalue()
  72. if output:
  73. if not output.endswith('\n'):
  74. output += '\n'
  75. self._original_stdout.write(STDOUT_LINE % output)
  76. if error:
  77. if not error.endswith('\n'):
  78. error += '\n'
  79. self._original_stderr.write(STDERR_LINE % error)
  80. sys.stdout = self._original_stdout
  81. sys.stderr = self._original_stderr
  82. self._stdout_buffer.seek(0)
  83. self._stdout_buffer.truncate()
  84. self._stderr_buffer.seek(0)
  85. self._stderr_buffer.truncate()
  86. def stopTestRun(self):
  87. """Called once after all tests are executed.
  88. See stopTest for a method called after each test.
  89. """
  90. @failfast
  91. def addError(self, test, err):
  92. """Called when an error has occurred. 'err' is a tuple of values as
  93. returned by sys.exc_info().
  94. """
  95. self.errors.append((test, self._exc_info_to_string(err, test)))
  96. self._mirrorOutput = True
  97. @failfast
  98. def addFailure(self, test, err):
  99. """Called when an error has occurred. 'err' is a tuple of values as
  100. returned by sys.exc_info()."""
  101. self.failures.append((test, self._exc_info_to_string(err, test)))
  102. self._mirrorOutput = True
  103. def addSubTest(self, test, subtest, err):
  104. """Called at the end of a subtest.
  105. 'err' is None if the subtest ended successfully, otherwise it's a
  106. tuple of values as returned by sys.exc_info().
  107. """
  108. # By default, we don't do anything with successful subtests, but
  109. # more sophisticated test results might want to record them.
  110. if err is not None:
  111. if getattr(self, 'failfast', False):
  112. self.stop()
  113. if issubclass(err[0], test.failureException):
  114. errors = self.failures
  115. else:
  116. errors = self.errors
  117. errors.append((subtest, self._exc_info_to_string(err, test)))
  118. self._mirrorOutput = True
  119. def addSuccess(self, test):
  120. "Called when a test has completed successfully"
  121. pass
  122. def addSkip(self, test, reason):
  123. """Called when a test is skipped."""
  124. self.skipped.append((test, reason))
  125. def addExpectedFailure(self, test, err):
  126. """Called when an expected failure/error occurred."""
  127. self.expectedFailures.append(
  128. (test, self._exc_info_to_string(err, test)))
  129. @failfast
  130. def addUnexpectedSuccess(self, test):
  131. """Called when a test was expected to fail, but succeed."""
  132. self.unexpectedSuccesses.append(test)
  133. def wasSuccessful(self):
  134. """Tells whether or not this result was a success."""
  135. # The hasattr check is for test_result's OldResult test. That
  136. # way this method works on objects that lack the attribute.
  137. # (where would such result instances come from? old stored pickles?)
  138. return ((len(self.failures) == len(self.errors) == 0) and
  139. (not hasattr(self, 'unexpectedSuccesses') or
  140. len(self.unexpectedSuccesses) == 0))
  141. def stop(self):
  142. """Indicates that the tests should be aborted."""
  143. self.shouldStop = True
  144. def _exc_info_to_string(self, err, test):
  145. """Converts a sys.exc_info()-style tuple of values into a string."""
  146. exctype, value, tb = err
  147. tb = self._clean_tracebacks(exctype, value, tb, test)
  148. tb_e = traceback.TracebackException(
  149. exctype, value, tb, capture_locals=self.tb_locals)
  150. msgLines = list(tb_e.format())
  151. if self.buffer:
  152. output = sys.stdout.getvalue()
  153. error = sys.stderr.getvalue()
  154. if output:
  155. if not output.endswith('\n'):
  156. output += '\n'
  157. msgLines.append(STDOUT_LINE % output)
  158. if error:
  159. if not error.endswith('\n'):
  160. error += '\n'
  161. msgLines.append(STDERR_LINE % error)
  162. return ''.join(msgLines)
  163. def _clean_tracebacks(self, exctype, value, tb, test):
  164. ret = None
  165. first = True
  166. excs = [(exctype, value, tb)]
  167. while excs:
  168. (exctype, value, tb) = excs.pop()
  169. # Skip test runner traceback levels
  170. while tb and self._is_relevant_tb_level(tb):
  171. tb = tb.tb_next
  172. # Skip assert*() traceback levels
  173. if exctype is test.failureException:
  174. self._remove_unittest_tb_frames(tb)
  175. if first:
  176. ret = tb
  177. first = False
  178. else:
  179. value.__traceback__ = tb
  180. if value is not None:
  181. for c in (value.__cause__, value.__context__):
  182. if c is not None:
  183. excs.append((type(c), c, c.__traceback__))
  184. return ret
  185. def _is_relevant_tb_level(self, tb):
  186. return '__unittest' in tb.tb_frame.f_globals
  187. def _remove_unittest_tb_frames(self, tb):
  188. '''Truncates usercode tb at the first unittest frame.
  189. If the first frame of the traceback is in user code,
  190. the prefix up to the first unittest frame is returned.
  191. If the first frame is already in the unittest module,
  192. the traceback is not modified.
  193. '''
  194. prev = None
  195. while tb and not self._is_relevant_tb_level(tb):
  196. prev = tb
  197. tb = tb.tb_next
  198. if prev is not None:
  199. prev.tb_next = None
  200. def __repr__(self):
  201. return ("<%s run=%i errors=%i failures=%i>" %
  202. (util.strclass(self.__class__), self.testsRun, len(self.errors),
  203. len(self.failures)))