forked from tfio/pytest-gui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipes.py
226 lines (200 loc) · 7.64 KB
/
pipes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
from __future__ import absolute_import
import json
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import sys
import time
import traceback
import unittest
class PipedTestResult(unittest.result.TestResult):
"""A test result class that can print test results in a machine-parseable format.
"""
RESULT_SEPARATOR = '\x1f' # ASCII US (Unit Separator)
def __init__(self, stream, use_old_discovery=True):
super(PipedTestResult, self).__init__()
self.stream = stream
self.use_old_discovery = use_old_discovery
self._first = True
# Create a clean buffer for stdout content.
self._stdout = StringIO()
sys.stdout = self._stdout
self._current_test = None
def _trim_docstring(self, docstring):
lines = docstring.expandtabs().splitlines()
indent = sys.maxsize
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
trimmed = [lines[0].strip()]
if indent < sys.maxsize:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
def description(self, test):
try:
# Wrapped _ErrorHolder objects have their own description
return self._trim_docstring(test.description)
except AttributeError:
# Fall back to the docstring on the method itself.
if test._testMethodDoc:
return self._trim_docstring(test._testMethodDoc)
else:
return 'No description'
def startTest(self, test):
super(PipedTestResult, self).startTest(test)
# We know we're starting a new test - record it.
self._current_test = test
self._stdout = StringIO()
sys.stdout = self._stdout
if self.use_old_discovery:
parts = test.id().split('.')
tests_index = parts.index('tests')
path = '%s.%s.%s' % (parts[tests_index - 1], parts[-2], parts[-1])
else:
path = test.id()
body = {
'path': path,
'start_time': time.time()
}
if self._first:
self.stream.write(PipedTestRunner.START_TEST_RESULTS + '\n')
self._first = False
else:
self.stream.write(self.RESULT_SEPARATOR + '\n')
self.stream.write('%s\n' % json.dumps(body))
self.stream.flush()
def addSuccess(self, test):
super(PipedTestResult, self).addSuccess(test)
body = {
'status': 'OK',
'end_time': time.time(),
'description': self.description(test),
'output': self._stdout.getvalue(),
}
self.stream.write('%s\n' % json.dumps(body))
self.stream.flush()
self._current_test = None
def addError(self, test, err):
# If there's no current test, the error occurred during test
# setup. Output a test start line so the protocol isn't confused.
if self._current_test is None:
self.startTest(test)
super(PipedTestResult, self).addError(test, err)
body = {
'status': 'E',
'end_time': time.time(),
'description': self.description(test),
'error': '\n'.join(traceback.format_exception(*err)),
'output': self._stdout.getvalue(),
}
self.stream.write('%s\n' % json.dumps(body))
self.stream.flush()
self._current_test = None
def addFailure(self, test, err):
super(PipedTestResult, self).addFailure(test, err)
body = {
'status': 'F',
'end_time': time.time(),
'description': self.description(test),
'error': '\n'.join(traceback.format_exception(*err)),
'output': self._stdout.getvalue(),
}
self.stream.write('%s\n' % json.dumps(body))
self.stream.flush()
self._current_test = None
def addSubTest(self, test, subtest, err):
super(PipedTestResult, self).addSubTest(test, subtest, err)
if err is None:
body = {
'status': 'OK',
'end_time': time.time(),
'description': self.description(test),
'output': self._stdout.getvalue(),
}
self.stream.write('%s\n' % json.dumps(body))
self.stream.flush()
elif issubclass(err[0], test.failureException):
body = {
'status': 'F',
'end_time': time.time(),
'description': self.description(test),
'error': '\n'.join(traceback.format_exception(*err)),
'output': self._stdout.getvalue(),
}
self.stream.write('%s\n' % json.dumps(body))
self.stream.flush()
else:
body = {
'status': 'E',
'end_time': time.time(),
'description': self.description(test),
'error': '\n'.join(traceback.format_exception(*err)),
'output': self._stdout.getvalue(),
}
self.stream.write('%s\n' % json.dumps(body))
self.stream.flush()
def addSkip(self, test, reason):
super(PipedTestResult, self).addSkip(test, reason)
body = {
'status': 's',
'end_time': time.time(),
'description': self.description(test),
'error': reason,
'output': self._stdout.getvalue(),
}
self.stream.write('%s\n' % json.dumps(body))
self.stream.flush()
self._current_test = None
def addExpectedFailure(self, test, err):
super(PipedTestResult, self).addExpectedFailure(test, err)
body = {
'status': 'x',
'end_time': time.time(),
'description': self.description(test),
'error': '\n'.join(traceback.format_exception(*err)),
'output': self._stdout.getvalue(),
}
self.stream.write('%s\n' % json.dumps(body))
self.stream.flush()
self._current_test = None
def addUnexpectedSuccess(self, test):
super(PipedTestResult, self).addUnexpectedSuccess(test)
body = {
'status': 'u',
'end_time': time.time(),
'description': self.description(test),
'output': self._stdout.getvalue(),
}
self.stream.write('%s\n' % json.dumps(body))
self.stream.flush()
self._current_test = None
class PipedTestRunner(unittest.TextTestRunner):
"""A test runner class that displays results in machine-parseable format.
"""
START_TEST_RESULTS = '\x02' # ASCII STX (Start of Text)
END_TEST_RESULTS = '\x03' # ASCII ETX (End of Text)
def __init__(self, stream=sys.stdout, use_old_discovery=False):
self.stream = stream
self.use_old_discovery = use_old_discovery
def run(self, test):
"Run the given test case or test suite."
# Remember stdout reference so it can be restored later
old_stdout = sys.stdout
# Create the result pipe, and run the tests with it.
result = PipedTestResult(self.stream, self.use_old_discovery)
test(result)
# Report end of test run
self.stream.write(self.END_TEST_RESULTS + '\n')
self.stream.flush()
# Restore the stdout reference
sys.stdout = old_stdout
return result