Debian Codegraph @

_pytest/junitxml.py

raw symbols SCIP
1 """
2 report test results in JUnit-XML format,
3 for use with Jenkins and build integration servers.
4
5
6 Based on initial code from Ross Lawley.
7 """
8 # Output conforms to https://github.com/jenkinsci/xunit-plugin/blob/master/
9 # src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd
10
11 import py
12 import os
13 import re
14 import sys
15 import time
16 import pytest
17
18 # Python 2.X and 3.X compatibility
19 if sys.version_info[0] < 3:
20 from codecs import open
21 else:
22 unichr = chr
23 unicode = str
24 long = int
25
26
27 class Junit(py.xml.Namespace):
28 pass
29
30 # We need to get the subset of the invalid unicode ranges according to
31 # XML 1.0 which are valid in this python build. Hence we calculate
32 # this dynamically instead of hardcoding it. The spec range of valid
33 # chars is: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
34 # | [#x10000-#x10FFFF]
35 _legal_chars = (0x09, 0x0A, 0x0d)
36 _legal_ranges = (
37 (0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF),
38 )
39 _legal_xml_re = [
40 unicode("%s-%s") % (unichr(low), unichr(high))
41 for (low, high) in _legal_ranges if low < sys.maxunicode
42 ]
43 _legal_xml_re = [unichr(x) for x in _legal_chars] + _legal_xml_re
44 illegal_xml_re = re.compile(unicode('[^%s]') % unicode('').join(_legal_xml_re))
45 del _legal_chars
46 del _legal_ranges
47 del _legal_xml_re
48
49 _py_ext_re = re.compile(r"\.py$")
50
51
52 def bin_xml_escape(arg):
53 def repl(matchobj):
54 i = ord(matchobj.group())
55 if i <= 0xFF:
56 return unicode('#x%02X') % i
57 else:
58 return unicode('#x%04X') % i
59
60 return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg)))
61
62
63 class _NodeReporter(object):
64 def __init__(self, nodeid, xml):
65
66 self.id = nodeid
67 self.xml = xml
68 self.add_stats = self.xml.add_stats
69 self.duration = 0
70 self.properties = []
71 self.nodes = []
72 self.testcase = None
73 self.attrs = {}
74
75 def append(self, node):
76 self.xml.add_stats(type(node).__name__)
77 self.nodes.append(node)
78
79 def add_property(self, name, value):
80 self.properties.append((str(name), bin_xml_escape(value)))
81
82 def make_properties_node(self):
83 """Return a Junit node containing custom properties, if any.
84 """
85 if self.properties:
86 return Junit.properties([
87 Junit.property(name=name, value=value)
88 for name, value in self.properties
89 ])
90 return ''
91
92 def record_testreport(self, testreport):
93 assert not self.testcase
94 names = mangle_test_address(testreport.nodeid)
95 classnames = names[:-1]
96 if self.xml.prefix:
97 classnames.insert(0, self.xml.prefix)
98 attrs = {
99 "classname": ".".join(classnames),
100 "name": bin_xml_escape(names[-1]),
101 "file": testreport.location[0],
102 }
103 if testreport.location[1] is not None:
104 attrs["line"] = testreport.location[1]
105 self.attrs = attrs
106
107 def to_xml(self):
108 testcase = Junit.testcase(time=self.duration, **self.attrs)
109 testcase.append(self.make_properties_node())
110 for node in self.nodes:
111 testcase.append(node)
112 return testcase
113
114 def _add_simple(self, kind, message, data=None):
115 data = bin_xml_escape(data)
116 node = kind(data, message=message)
117 self.append(node)
118
119 def _write_captured_output(self, report):
120 for capname in ('out', 'err'):
121 allcontent = ""
122 for name, content in report.get_sections("Captured std%s" %
123 capname):
124 allcontent += content
125 if allcontent:
126 tag = getattr(Junit, 'system-' + capname)
127 self.append(tag(bin_xml_escape(allcontent)))
128
129 def append_pass(self, report):
130 self.add_stats('passed')
131 self._write_captured_output(report)
132
133 def append_failure(self, report):
134 # msg = str(report.longrepr.reprtraceback.extraline)
135 if hasattr(report, "wasxfail"):
136 self._add_simple(
137 Junit.skipped,
138 "xfail-marked test passes unexpectedly")
139 else:
140 if hasattr(report.longrepr, "reprcrash"):
141 message = report.longrepr.reprcrash.message
142 elif isinstance(report.longrepr, (unicode, str)):
143 message = report.longrepr
144 else:
145 message = str(report.longrepr)
146 message = bin_xml_escape(message)
147 fail = Junit.failure(message=message)
148 fail.append(bin_xml_escape(report.longrepr))
149 self.append(fail)
150 self._write_captured_output(report)
151
152 def append_collect_error(self, report):
153 # msg = str(report.longrepr.reprtraceback.extraline)
154 self.append(Junit.error(bin_xml_escape(report.longrepr),
155 message="collection failure"))
156
157 def append_collect_skipped(self, report):
158 self._add_simple(
159 Junit.skipped, "collection skipped", report.longrepr)
160
161 def append_error(self, report):
162 self._add_simple(
163 Junit.error, "test setup failure", report.longrepr)
164 self._write_captured_output(report)
165
166 def append_skipped(self, report):
167 if hasattr(report, "wasxfail"):
168 self._add_simple(
169 Junit.skipped, "expected test failure", report.wasxfail
170 )
171 else:
172 filename, lineno, skipreason = report.longrepr
173 if skipreason.startswith("Skipped: "):
174 skipreason = bin_xml_escape(skipreason[9:])
175 self.append(
176 Junit.skipped("%s:%s: %s" % (filename, lineno, skipreason),
177 type="pytest.skip",
178 message=skipreason))
179 self._write_captured_output(report)
180
181 def finalize(self):
182 data = self.to_xml().unicode(indent=0)
183 self.__dict__.clear()
184 self.to_xml = lambda: py.xml.raw(data)
185
186
187 @pytest.fixture
188 def record_xml_property(request):
189 """Fixture that adds extra xml properties to the tag for the calling test.
190 The fixture is callable with (name, value), with value being automatically
191 xml-encoded.
192 """
193 request.node.warn(
194 code='C3',
195 message='record_xml_property is an experimental feature',
196 )
197 xml = getattr(request.config, "_xml", None)
198 if xml is not None:
199 node_reporter = xml.node_reporter(request.node.nodeid)
200 return node_reporter.add_property
201 else:
202 def add_property_noop(name, value):
203 pass
204
205 return add_property_noop
206
207
208 def pytest_addoption(parser):
209 group = parser.getgroup("terminal reporting")
210 group.addoption(
211 '--junitxml', '--junit-xml',
212 action="store",
213 dest="xmlpath",
214 metavar="path",
215 default=None,
216 help="create junit-xml style report file at given path.")
217 group.addoption(
218 '--junitprefix', '--junit-prefix',
219 action="store",
220 metavar="str",
221 default=None,
222 help="prepend prefix to classnames in junit-xml output")
223
224
225 def pytest_configure(config):
226 xmlpath = config.option.xmlpath
227 # prevent opening xmllog on slave nodes (xdist)
228 if xmlpath and not hasattr(config, 'slaveinput'):
229 config._xml = LogXML(xmlpath, config.option.junitprefix)
230 config.pluginmanager.register(config._xml)
231
232
233 def pytest_unconfigure(config):
234 xml = getattr(config, '_xml', None)
235 if xml:
236 del config._xml
237 config.pluginmanager.unregister(xml)
238
239
240 def mangle_test_address(address):
241 path, possible_open_bracket, params = address.partition('[')
242 names = path.split("::")
243 try:
244 names.remove('()')
245 except ValueError:
246 pass
247 # convert file path to dotted path
248 names[0] = names[0].replace("/", '.')
249 names[0] = _py_ext_re.sub("", names[0])
250 # put any params back
251 names[-1] += possible_open_bracket + params
252 return names
253
254
255 class LogXML(object):
256 def __init__(self, logfile, prefix):
257 logfile = os.path.expanduser(os.path.expandvars(logfile))
258 self.logfile = os.path.normpath(os.path.abspath(logfile))
259 self.prefix = prefix
260 self.stats = dict.fromkeys([
261 'error',
262 'passed',
263 'failure',
264 'skipped',
265 ], 0)
266 self.node_reporters = {} # nodeid -> _NodeReporter
267 self.node_reporters_ordered = []
268
269 def finalize(self, report):
270 nodeid = getattr(report, 'nodeid', report)
271 # local hack to handle xdist report order
272 slavenode = getattr(report, 'node', None)
273 reporter = self.node_reporters.pop((nodeid, slavenode))
274 if reporter is not None:
275 reporter.finalize()
276
277 def node_reporter(self, report):
278 nodeid = getattr(report, 'nodeid', report)
279 # local hack to handle xdist report order
280 slavenode = getattr(report, 'node', None)
281
282 key = nodeid, slavenode
283
284 if key in self.node_reporters:
285 # TODO: breasks for --dist=each
286 return self.node_reporters[key]
287 reporter = _NodeReporter(nodeid, self)
288 self.node_reporters[key] = reporter
289 self.node_reporters_ordered.append(reporter)
290 return reporter
291
292 def add_stats(self, key):
293 if key in self.stats:
294 self.stats[key] += 1
295
296 def _opentestcase(self, report):
297 reporter = self.node_reporter(report)
298 reporter.record_testreport(report)
299 return reporter
300
301 def pytest_runtest_logreport(self, report):
302 """handle a setup/call/teardown report, generating the appropriate
303 xml tags as necessary.
304
305 note: due to plugins like xdist, this hook may be called in interlaced
306 order with reports from other nodes. for example:
307
308 usual call order:
309 -> setup node1
310 -> call node1
311 -> teardown node1
312 -> setup node2
313 -> call node2
314 -> teardown node2
315
316 possible call order in xdist:
317 -> setup node1
318 -> call node1
319 -> setup node2
320 -> call node2
321 -> teardown node2
322 -> teardown node1
323 """
324 if report.passed:
325 if report.when == "call": # ignore setup/teardown
326 reporter = self._opentestcase(report)
327 reporter.append_pass(report)
328 elif report.failed:
329 reporter = self._opentestcase(report)
330 if report.when == "call":
331 reporter.append_failure(report)
332 else:
333 reporter.append_error(report)
334 elif report.skipped:
335 reporter = self._opentestcase(report)
336 reporter.append_skipped(report)
337 self.update_testcase_duration(report)
338 if report.when == "teardown":
339 self.finalize(report)
340
341 def update_testcase_duration(self, report):
342 """accumulates total duration for nodeid from given report and updates
343 the Junit.testcase with the new total if already created.
344 """
345 reporter = self.node_reporter(report)
346 reporter.duration += getattr(report, 'duration', 0.0)
347
348 def pytest_collectreport(self, report):
349 if not report.passed:
350 reporter = self._opentestcase(report)
351 if report.failed:
352 reporter.append_collect_error(report)
353 else:
354 reporter.append_collect_skipped(report)
355
356 def pytest_internalerror(self, excrepr):
357 reporter = self.node_reporter('internal')
358 reporter.attrs.update(classname="pytest", name='internal')
359 reporter._add_simple(Junit.error, 'internal error', excrepr)
360
361 def pytest_sessionstart(self):
362 self.suite_start_time = time.time()
363
364 def pytest_sessionfinish(self):
365 dirname = os.path.dirname(os.path.abspath(self.logfile))
366 if not os.path.isdir(dirname):
367 os.makedirs(dirname)
368 logfile = open(self.logfile, 'w', encoding='utf-8')
369 suite_stop_time = time.time()
370 suite_time_delta = suite_stop_time - self.suite_start_time
371
372 numtests = self.stats['passed'] + self.stats['failure'] + self.stats['skipped']
373
374 logfile.write('<?xml version="1.0" encoding="utf-8"?>')
375 logfile.write(Junit.testsuite(
376 [x.to_xml() for x in self.node_reporters_ordered],
377 name="pytest",
378 errors=self.stats['error'],
379 failures=self.stats['failure'],
380 skips=self.stats['skipped'],
381 tests=numtests,
382 time="%.3f" % suite_time_delta, ).unicode(indent=0))
383 logfile.close()
384
385 def pytest_terminal_summary(self, terminalreporter):
386 terminalreporter.write_sep("-",
387 "generated xml file: %s" % (self.logfile))