blob: 1f66f1bb18f39c58b8b6da9d758a710653223672 [file] [log] [blame]
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001"""Test result object"""
2
Michael Foord5637f042010-04-02 21:42:47 +00003import os
4import sys
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00005import traceback
6
Michael Foordf6ff26c2010-04-07 23:04:22 +00007from StringIO import StringIO
Michael Foord5637f042010-04-02 21:42:47 +00008
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00009from . import util
Michael Foord1b9e9532010-03-22 01:01:34 +000010from functools import wraps
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000011
Michael Foordb1aa30f2010-03-22 00:06:30 +000012__unittest = True
13
Michael Foord1b9e9532010-03-22 01:01:34 +000014def failfast(method):
15 @wraps(method)
16 def inner(self, *args, **kw):
17 if getattr(self, 'failfast', False):
18 self.stop()
19 return method(self, *args, **kw)
20 return inner
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000021
Michael Foord9b4ee122010-04-03 02:21:39 +000022STDOUT_LINE = '\nStdout:\n%s'
23STDERR_LINE = '\nStderr:\n%s'
Michael Foord5637f042010-04-02 21:42:47 +000024
25
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000026class TestResult(object):
27 """Holder for test result information.
28
29 Test results are automatically managed by the TestCase and TestSuite
30 classes, and do not need to be explicitly manipulated by writers of tests.
31
32 Each instance holds the total number of tests run, and collections of
33 failures and errors that occurred among those test runs. The collections
34 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
35 formatted traceback of the error that occurred.
36 """
Michael Foord5ffa3252010-03-07 22:04:55 +000037 _previousTestClass = None
Michael Foorde5dc24e2010-11-01 22:11:53 +000038 _testRunEntered = False
Michael Foord5ffa3252010-03-07 22:04:55 +000039 _moduleSetUpFailed = False
Michael Foordd99ef9a2010-02-23 17:00:53 +000040 def __init__(self, stream=None, descriptions=None, verbosity=None):
Michael Foord1b9e9532010-03-22 01:01:34 +000041 self.failfast = False
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000042 self.failures = []
43 self.errors = []
44 self.testsRun = 0
45 self.skipped = []
46 self.expectedFailures = []
47 self.unexpectedSuccesses = []
48 self.shouldStop = False
Michael Foord5637f042010-04-02 21:42:47 +000049 self.buffer = False
Michael Foordf6ff26c2010-04-07 23:04:22 +000050 self._stdout_buffer = None
51 self._stderr_buffer = None
Michael Foord58c1e782010-04-02 22:08:29 +000052 self._original_stdout = sys.stdout
53 self._original_stderr = sys.stderr
Michael Foord5637f042010-04-02 21:42:47 +000054 self._mirrorOutput = False
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000055
Michael Foordd99ef9a2010-02-23 17:00:53 +000056 def printErrors(self):
57 "Called by TestRunner after test run"
58
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000059 def startTest(self, test):
60 "Called when the given test is about to be run"
Michael Foorddb43b5a2010-02-10 14:25:12 +000061 self.testsRun += 1
Michael Foord5637f042010-04-02 21:42:47 +000062 self._mirrorOutput = False
63 if self.buffer:
Michael Foordf6ff26c2010-04-07 23:04:22 +000064 if self._stderr_buffer is None:
65 self._stderr_buffer = StringIO()
66 self._stdout_buffer = StringIO()
Michael Foord5637f042010-04-02 21:42:47 +000067 sys.stdout = self._stdout_buffer
68 sys.stderr = self._stderr_buffer
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000069
70 def startTestRun(self):
71 """Called once before any tests are executed.
72
73 See startTest for a method called before each test.
74 """
75
76 def stopTest(self, test):
Michael Foorddb43b5a2010-02-10 14:25:12 +000077 """Called when the given test has been run"""
Michael Foord5637f042010-04-02 21:42:47 +000078 if self.buffer:
79 if self._mirrorOutput:
80 output = sys.stdout.getvalue()
81 error = sys.stderr.getvalue()
82 if output:
Michael Foord9b4ee122010-04-03 02:21:39 +000083 if not output.endswith('\n'):
84 output += '\n'
Michael Foord58c1e782010-04-02 22:08:29 +000085 self._original_stdout.write(STDOUT_LINE % output)
Michael Foord5637f042010-04-02 21:42:47 +000086 if error:
Michael Foord9b4ee122010-04-03 02:21:39 +000087 if not error.endswith('\n'):
88 error += '\n'
Michael Foord58c1e782010-04-02 22:08:29 +000089 self._original_stderr.write(STDERR_LINE % error)
Michael Foord5637f042010-04-02 21:42:47 +000090
Michael Foord25d79762010-04-02 22:30:56 +000091 sys.stdout = self._original_stdout
92 sys.stderr = self._original_stderr
Michael Foord5637f042010-04-02 21:42:47 +000093 self._stdout_buffer.seek(0)
94 self._stdout_buffer.truncate()
95 self._stderr_buffer.seek(0)
96 self._stderr_buffer.truncate()
97 self._mirrorOutput = False
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000098
99 def stopTestRun(self):
100 """Called once after all tests are executed.
101
102 See stopTest for a method called after each test.
103 """
104
Michael Foord1b9e9532010-03-22 01:01:34 +0000105 @failfast
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000106 def addError(self, test, err):
107 """Called when an error has occurred. 'err' is a tuple of values as
108 returned by sys.exc_info().
109 """
110 self.errors.append((test, self._exc_info_to_string(err, test)))
Michael Foord5637f042010-04-02 21:42:47 +0000111 self._mirrorOutput = True
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000112
Michael Foord1b9e9532010-03-22 01:01:34 +0000113 @failfast
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000114 def addFailure(self, test, err):
115 """Called when an error has occurred. 'err' is a tuple of values as
116 returned by sys.exc_info()."""
117 self.failures.append((test, self._exc_info_to_string(err, test)))
Michael Foord5637f042010-04-02 21:42:47 +0000118 self._mirrorOutput = True
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000119
120 def addSuccess(self, test):
121 "Called when a test has completed successfully"
122 pass
123
124 def addSkip(self, test, reason):
125 """Called when a test is skipped."""
126 self.skipped.append((test, reason))
127
128 def addExpectedFailure(self, test, err):
129 """Called when an expected failure/error occured."""
130 self.expectedFailures.append(
131 (test, self._exc_info_to_string(err, test)))
132
Michael Foord1b9e9532010-03-22 01:01:34 +0000133 @failfast
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000134 def addUnexpectedSuccess(self, test):
135 """Called when a test was expected to fail, but succeed."""
136 self.unexpectedSuccesses.append(test)
137
138 def wasSuccessful(self):
139 "Tells whether or not this result was a success"
140 return len(self.failures) == len(self.errors) == 0
141
142 def stop(self):
143 "Indicates that the tests should be aborted"
144 self.shouldStop = True
145
146 def _exc_info_to_string(self, err, test):
147 """Converts a sys.exc_info()-style tuple of values into a string."""
148 exctype, value, tb = err
149 # Skip test runner traceback levels
150 while tb and self._is_relevant_tb_level(tb):
151 tb = tb.tb_next
Michael Foord5637f042010-04-02 21:42:47 +0000152
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000153 if exctype is test.failureException:
154 # Skip assert*() traceback levels
155 length = self._count_relevant_tb_levels(tb)
Michael Foord5637f042010-04-02 21:42:47 +0000156 msgLines = traceback.format_exception(exctype, value, tb, length)
157 else:
158 msgLines = traceback.format_exception(exctype, value, tb)
159
160 if self.buffer:
161 output = sys.stdout.getvalue()
162 error = sys.stderr.getvalue()
163 if output:
Michael Foord9b4ee122010-04-03 02:21:39 +0000164 if not output.endswith('\n'):
165 output += '\n'
Michael Foord5637f042010-04-02 21:42:47 +0000166 msgLines.append(STDOUT_LINE % output)
167 if error:
Michael Foord9b4ee122010-04-03 02:21:39 +0000168 if not error.endswith('\n'):
169 error += '\n'
Michael Foord5637f042010-04-02 21:42:47 +0000170 msgLines.append(STDERR_LINE % error)
171 return ''.join(msgLines)
172
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000173
174 def _is_relevant_tb_level(self, tb):
Michael Foordb1aa30f2010-03-22 00:06:30 +0000175 return '__unittest' in tb.tb_frame.f_globals
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000176
177 def _count_relevant_tb_levels(self, tb):
178 length = 0
179 while tb and not self._is_relevant_tb_level(tb):
180 length += 1
181 tb = tb.tb_next
182 return length
183
184 def __repr__(self):
Michael Foordae3db0a2010-02-22 23:28:32 +0000185 return ("<%s run=%i errors=%i failures=%i>" %
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000186 (util.strclass(self.__class__), self.testsRun, len(self.errors),
Michael Foordae3db0a2010-02-22 23:28:32 +0000187 len(self.failures)))