blob: 3dc7154b732b45c495c1f5746d0652ee6d7d7d34 [file] [log] [blame]
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001"""Test result object"""
2
Benjamin Petersonb48af542010-04-11 20:43:16 +00003import os
4import io
5import sys
Benjamin Petersonbed7d042009-07-19 21:01:52 +00006import traceback
7
8from . import util
Benjamin Peterson8769fd82010-03-22 01:13:48 +00009from functools import wraps
Benjamin Petersonbed7d042009-07-19 21:01:52 +000010
Benjamin Petersondccc1fc2010-03-22 00:15:53 +000011__unittest = True
12
Benjamin Peterson8769fd82010-03-22 01:13:48 +000013def failfast(method):
14 @wraps(method)
15 def inner(self, *args, **kw):
16 if getattr(self, 'failfast', False):
17 self.stop()
18 return method(self, *args, **kw)
19 return inner
Benjamin Petersonbed7d042009-07-19 21:01:52 +000020
Benjamin Petersonb48af542010-04-11 20:43:16 +000021STDOUT_LINE = '\nStdout:\n%s'
22STDERR_LINE = '\nStderr:\n%s'
23
24
Benjamin Petersonbed7d042009-07-19 21:01:52 +000025class TestResult(object):
26 """Holder for test result information.
27
28 Test results are automatically managed by the TestCase and TestSuite
29 classes, and do not need to be explicitly manipulated by writers of tests.
30
31 Each instance holds the total number of tests run, and collections of
32 failures and errors that occurred among those test runs. The collections
33 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
34 formatted traceback of the error that occurred.
35 """
Benjamin Peterson847a4112010-03-14 15:04:17 +000036 _previousTestClass = None
Michael Foordbbea35f2010-11-01 21:09:03 +000037 _testRunEntered = False
Benjamin Peterson847a4112010-03-14 15:04:17 +000038 _moduleSetUpFailed = False
39 def __init__(self, stream=None, descriptions=None, verbosity=None):
Benjamin Peterson8769fd82010-03-22 01:13:48 +000040 self.failfast = False
Benjamin Petersonbed7d042009-07-19 21:01:52 +000041 self.failures = []
42 self.errors = []
43 self.testsRun = 0
44 self.skipped = []
45 self.expectedFailures = []
46 self.unexpectedSuccesses = []
47 self.shouldStop = False
Benjamin Petersonb48af542010-04-11 20:43:16 +000048 self.buffer = False
49 self._stdout_buffer = None
50 self._stderr_buffer = None
51 self._original_stdout = sys.stdout
52 self._original_stderr = sys.stderr
53 self._mirrorOutput = False
Benjamin Petersonbed7d042009-07-19 21:01:52 +000054
Benjamin Peterson847a4112010-03-14 15:04:17 +000055 def printErrors(self):
56 "Called by TestRunner after test run"
57
Benjamin Petersonbed7d042009-07-19 21:01:52 +000058 def startTest(self, test):
59 "Called when the given test is about to be run"
Michael Foord34c94622010-02-10 15:51:42 +000060 self.testsRun += 1
Benjamin Petersonb48af542010-04-11 20:43:16 +000061 self._mirrorOutput = False
62 if self.buffer:
63 if self._stderr_buffer is None:
64 self._stderr_buffer = io.StringIO()
65 self._stdout_buffer = io.StringIO()
66 sys.stdout = self._stdout_buffer
67 sys.stderr = self._stderr_buffer
Benjamin Petersonbed7d042009-07-19 21:01:52 +000068
69 def startTestRun(self):
70 """Called once before any tests are executed.
71
72 See startTest for a method called before each test.
73 """
74
75 def stopTest(self, test):
Michael Foord34c94622010-02-10 15:51:42 +000076 """Called when the given test has been run"""
Benjamin Petersonb48af542010-04-11 20:43:16 +000077 if self.buffer:
78 if self._mirrorOutput:
79 output = sys.stdout.getvalue()
80 error = sys.stderr.getvalue()
81 if output:
82 if not output.endswith('\n'):
83 output += '\n'
84 self._original_stdout.write(STDOUT_LINE % output)
85 if error:
86 if not error.endswith('\n'):
87 error += '\n'
88 self._original_stderr.write(STDERR_LINE % error)
89
90 sys.stdout = self._original_stdout
91 sys.stderr = self._original_stderr
92 self._stdout_buffer.seek(0)
93 self._stdout_buffer.truncate()
94 self._stderr_buffer.seek(0)
95 self._stderr_buffer.truncate()
96 self._mirrorOutput = False
Benjamin Petersonbed7d042009-07-19 21:01:52 +000097
98 def stopTestRun(self):
99 """Called once after all tests are executed.
100
101 See stopTest for a method called after each test.
102 """
103
Benjamin Peterson8769fd82010-03-22 01:13:48 +0000104 @failfast
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000105 def addError(self, test, err):
106 """Called when an error has occurred. 'err' is a tuple of values as
107 returned by sys.exc_info().
108 """
109 self.errors.append((test, self._exc_info_to_string(err, test)))
Benjamin Petersonb48af542010-04-11 20:43:16 +0000110 self._mirrorOutput = True
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000111
Benjamin Peterson8769fd82010-03-22 01:13:48 +0000112 @failfast
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000113 def addFailure(self, test, err):
114 """Called when an error has occurred. 'err' is a tuple of values as
115 returned by sys.exc_info()."""
116 self.failures.append((test, self._exc_info_to_string(err, test)))
Benjamin Petersonb48af542010-04-11 20:43:16 +0000117 self._mirrorOutput = True
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000118
119 def addSuccess(self, test):
120 "Called when a test has completed successfully"
121 pass
122
123 def addSkip(self, test, reason):
124 """Called when a test is skipped."""
125 self.skipped.append((test, reason))
126
127 def addExpectedFailure(self, test, err):
128 """Called when an expected failure/error occured."""
129 self.expectedFailures.append(
130 (test, self._exc_info_to_string(err, test)))
131
Benjamin Peterson8769fd82010-03-22 01:13:48 +0000132 @failfast
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000133 def addUnexpectedSuccess(self, test):
134 """Called when a test was expected to fail, but succeed."""
135 self.unexpectedSuccesses.append(test)
136
137 def wasSuccessful(self):
138 "Tells whether or not this result was a success"
139 return len(self.failures) == len(self.errors) == 0
140
141 def stop(self):
142 "Indicates that the tests should be aborted"
143 self.shouldStop = True
144
145 def _exc_info_to_string(self, err, test):
146 """Converts a sys.exc_info()-style tuple of values into a string."""
147 exctype, value, tb = err
148 # Skip test runner traceback levels
149 while tb and self._is_relevant_tb_level(tb):
150 tb = tb.tb_next
Benjamin Petersonb48af542010-04-11 20:43:16 +0000151
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000152 if exctype is test.failureException:
153 # Skip assert*() traceback levels
154 length = self._count_relevant_tb_levels(tb)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000155 msgLines = traceback.format_exception(exctype, value, tb, length)
156 else:
Michael Foordd23ea062010-05-02 21:00:22 +0000157 msgLines = traceback.format_exception(exctype, value, tb)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000158
159 if self.buffer:
160 output = sys.stdout.getvalue()
161 error = sys.stderr.getvalue()
162 if output:
163 if not output.endswith('\n'):
164 output += '\n'
165 msgLines.append(STDOUT_LINE % output)
166 if error:
167 if not error.endswith('\n'):
168 error += '\n'
169 msgLines.append(STDERR_LINE % error)
170 return ''.join(msgLines)
171
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000172
173 def _is_relevant_tb_level(self, tb):
Benjamin Petersondccc1fc2010-03-22 00:15:53 +0000174 return '__unittest' in tb.tb_frame.f_globals
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000175
176 def _count_relevant_tb_levels(self, tb):
177 length = 0
178 while tb and not self._is_relevant_tb_level(tb):
179 length += 1
180 tb = tb.tb_next
181 return length
182
183 def __repr__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000184 return ("<%s run=%i errors=%i failures=%i>" %
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000185 (util.strclass(self.__class__), self.testsRun, len(self.errors),
Benjamin Peterson847a4112010-03-14 15:04:17 +0000186 len(self.failures)))