forked from laurentb/xunitparser
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxunitparserx.py
286 lines (222 loc) · 7.94 KB
/
xunitparserx.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import math
import unittest
from datetime import timedelta
from xml.etree import ElementTree
from lxml import etree
def to_timedelta(val):
if val is None:
return None
secs = float(val)
if math.isnan(secs):
return None
return timedelta(seconds=secs)
class TestResult(unittest.TestResult):
def _exc_info_to_string(self, err, test):
err = (e for e in err if e)
return ': '.join(err)
class TestCase(unittest.TestCase):
TR_CLASS = TestResult
stdout = None
stderr = None
def __init__(self, classname, methodname):
super(TestCase, self).__init__()
self.classname = classname
self.methodname = methodname
self.props = dict()
def __str__(self):
return "%s (%s)" % (self.methodname, self.classname)
def __repr__(self):
return "<%s testMethod=%s>" % \
(self.classname, self.methodname)
def __hash__(self):
return hash((type(self), self.classname, self.methodname))
def id(self):
return "%s.%s" % (self.classname, self.methodname)
def seed(self, result, typename=None, message=None, trace=None):
""" Provide the expected result """
self.result, self.typename, self.message, self.trace = result, typename, message, trace
def run(self, tr=None):
""" Fake run() that produces the seeded result """
tr = tr or self.TR_CLASS()
tr.startTest(self)
if self.result == 'success':
tr.addSuccess(self)
elif self.result == 'skipped':
tr.addSkip(self, '%s: %s' % (self.typename, self._textMessage()))
elif self.result == 'error':
tr.addError(self, (self.typename, self._textMessage()))
elif self.result == 'failure':
tr.addFailure(self, (self.typename, self._textMessage()))
tr.stopTest(self)
return tr
def _textMessage(self):
msg = (e for e in (self.message, self.trace) if e)
return '\n\n'.join(msg) or None
@property
def alltext(self):
err = (e for e in (self.typename, self.message) if e)
err = ': '.join(err)
txt = (e for e in (err, self.trace) if e)
return '\n\n'.join(txt) or None
def setUp(self):
""" Dummy method so __init__ does not fail """
pass
def tearDown(self):
""" Dummy method so __init__ does not fail """
pass
def runTest(self):
""" Dummy method so __init__ does not fail """
self.run()
@property
def basename(self):
return self.classname.rpartition('.')[2]
@property
def success(self):
return self.result == 'success'
@property
def skipped(self):
return self.result == 'skipped'
@property
def failed(self):
return self.result == 'failure'
@property
def errored(self):
return self.result == 'error'
@property
def good(self):
return self.skipped or self.success
@property
def bad(self):
return not self.good
@property
def stdall(self):
""" All system output """
return '\n'.join([out for out in (self.stdout, self.stderr) if out])
class TestSuite(unittest.TestSuite):
def __init__(self, *args, **kwargs):
super(TestSuite, self).__init__(*args, **kwargs)
self.properties = {}
self.stdout = None
self.stderr = None
class Parser(object):
#TC_CLASS = TestCase
TC_CLASS = TestCase
TS_CLASS = TestSuite
TR_CLASS = TestResult
def parse(self, source):
xml = ElementTree.parse(source)
root = xml.getroot()
return self.parse_root(root)
def fromstring(self, source_str):
root=ElementTree.fromstring(source_str)
return self.parse_root(root)
pass
def parse_root(self, root):
"""
:param ElementTree.Element root: root element
:return:
:rtype: (TestSuite, TestResult)
"""
ts = self.TS_CLASS()
if root.tag == 'testsuites':
for subroot in root:
self.parse_testsuite(subroot, ts)
else:
self.parse_testsuite(root, ts)
ts._cleanup=False
tr = ts.run(self.TR_CLASS())
tr.time = to_timedelta(root.attrib.get('time'))
# check totals if they are in the root XML element
if 'errors' in root.attrib:
assert len(tr.errors) == int(root.attrib['errors'])
if 'failures' in root.attrib:
assert len(tr.failures) == int(root.attrib['failures'])
if 'skip' in root.attrib:
assert len(tr.skipped) == int(root.attrib['skip'])
if 'tests' in root.attrib:
assert len(list(ts)) == int(root.attrib['tests'])
return (ts, tr)
def parse_testsuite(self, root, ts):
assert root.tag == 'testsuite'
ts.name = root.attrib.get('name')
ts.package = root.attrib.get('package')
for el in root:
if el.tag == 'testcase':
self.parse_testcase(el, ts)
if el.tag == 'properties':
self.parse_properties(el, ts)
if el.tag == 'system-out' and el.text:
ts.stdout = el.text.strip()
if el.tag == 'system-err' and el.text:
ts.stderr = el.text.strip()
def parse_testcase(self, el, ts):
'''
:param ElementTree.Element el:
:param TestSuite ts:
:return:
'''
tc_classname = el.attrib.get('classname') or ts.name
tc = self.TC_CLASS(tc_classname, el.attrib['name'])
tc.seed('success', trace=el.text or None)
tc.time = to_timedelta(el.attrib.get('time'))
message = None
text = None
for e in el:
# error takes over failure in JUnit 4
if e.tag in ('failure', 'error', 'skipped'):
tc = self.TC_CLASS(tc_classname, el.attrib['name'])
result = e.tag
typename = e.attrib.get('type')
# reuse old if empty
message = e.attrib.get('message') or message
text = e.text or text
tc.seed(result, typename, message, text)
tc.time = to_timedelta(el.attrib.get('time'))
if e.tag == 'system-out' and e.text:
tc.stdout = e.text.strip()
if e.tag == 'system-err' and e.text:
tc.stderr = e.text.strip()
'''
<properties>
<property name="assertions" value="REQ-1234, REQ-5678, REQ-9101"/>
</properties>
'''
for prop_ele in el.findall('properties/property'):
tc.props[prop_ele.attrib['name']]=prop_ele.attrib['value']
pass
# add either the original "success" tc or a tc created by elements
ts.addTest(tc)
def parse_properties(self, el, ts):
for e in el:
if e.tag == 'property':
assert e.attrib['name'] not in ts.properties
ts.properties[e.attrib['name']] = e.attrib['value']
def parse(source):
"""
parse a junit xml file
:param source:
:return:
:rtype: ( TestSuite, TestResult)
"""
return Parser().parse(source)
def fromstring(source_str):
return Parser().fromstring(source_str)
def convert_mstest_trx_to_junit(source_str):
import pathlib
trx_to_junit_xlst_path_obj=pathlib.Path(__file__).parent/'trx-to-junit.xslt' # type: pathlib.Path
xslt_root_element = etree.XML(trx_to_junit_xlst_path_obj.read_bytes())
xlst_engine_obj = etree.XSLT(xslt_root_element)
source_root_element = etree.XML(source_str)
result_root_ele = xlst_engine_obj(source_root_element)
xml = str(result_root_ele)
return xml
pass
def parse_trx(source):
import pathlib
trx_source_str=pathlib.Path(source).read_text(encoding='utf-8')
return fromstring_trx(trx_source_str)
pass
def fromstring_trx(trx_source_str):
source_str=convert_mstest_trx_to_junit(trx_source_str)
return fromstring(source_str)
pass