junitxml.py 13 KB

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