junitxml.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. # -*- coding: utf-8 -*-
  2. """
  3. report test results in JUnit-XML format,
  4. for use with Jenkins and build integration servers.
  5. Based on initial code from Ross Lawley.
  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. """
  9. from __future__ import absolute_import
  10. from __future__ import division
  11. from __future__ import print_function
  12. import functools
  13. import os
  14. import platform
  15. import re
  16. import sys
  17. import time
  18. from datetime import datetime
  19. import py
  20. import six
  21. import pytest
  22. from _pytest import nodes
  23. from _pytest.config import filename_arg
  24. # Python 2.X and 3.X compatibility
  25. if sys.version_info[0] < 3:
  26. from codecs import open
  27. class Junit(py.xml.Namespace):
  28. pass
  29. # We need to get the subset of the invalid unicode ranges according to
  30. # XML 1.0 which are valid in this python build. Hence we calculate
  31. # this dynamically instead of hardcoding it. The spec range of valid
  32. # chars is: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
  33. # | [#x10000-#x10FFFF]
  34. _legal_chars = (0x09, 0x0A, 0x0D)
  35. _legal_ranges = ((0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF))
  36. _legal_xml_re = [
  37. u"%s-%s" % (six.unichr(low), six.unichr(high))
  38. for (low, high) in _legal_ranges
  39. if low < sys.maxunicode
  40. ]
  41. _legal_xml_re = [six.unichr(x) for x in _legal_chars] + _legal_xml_re
  42. illegal_xml_re = re.compile(u"[^%s]" % u"".join(_legal_xml_re))
  43. del _legal_chars
  44. del _legal_ranges
  45. del _legal_xml_re
  46. _py_ext_re = re.compile(r"\.py$")
  47. def bin_xml_escape(arg):
  48. def repl(matchobj):
  49. i = ord(matchobj.group())
  50. if i <= 0xFF:
  51. return u"#x%02X" % i
  52. else:
  53. return u"#x%04X" % i
  54. return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg)))
  55. def merge_family(left, right):
  56. result = {}
  57. for kl, vl in left.items():
  58. for kr, vr in right.items():
  59. if not isinstance(vl, list):
  60. raise TypeError(type(vl))
  61. result[kl] = vl + vr
  62. left.update(result)
  63. families = {}
  64. families["_base"] = {"testcase": ["classname", "name"]}
  65. families["_base_legacy"] = {"testcase": ["file", "line", "url"]}
  66. # xUnit 1.x inherits legacy attributes
  67. families["xunit1"] = families["_base"].copy()
  68. merge_family(families["xunit1"], families["_base_legacy"])
  69. # xUnit 2.x uses strict base attributes
  70. families["xunit2"] = families["_base"]
  71. class _NodeReporter(object):
  72. def __init__(self, nodeid, xml):
  73. self.id = nodeid
  74. self.xml = xml
  75. self.add_stats = self.xml.add_stats
  76. self.family = self.xml.family
  77. self.duration = 0
  78. self.properties = []
  79. self.nodes = []
  80. self.testcase = None
  81. self.attrs = {}
  82. def append(self, node):
  83. self.xml.add_stats(type(node).__name__)
  84. self.nodes.append(node)
  85. def add_property(self, name, value):
  86. self.properties.append((str(name), bin_xml_escape(value)))
  87. def add_attribute(self, name, value):
  88. self.attrs[str(name)] = bin_xml_escape(value)
  89. def make_properties_node(self):
  90. """Return a Junit node containing custom properties, if any.
  91. """
  92. if self.properties:
  93. return Junit.properties(
  94. [
  95. Junit.property(name=name, value=value)
  96. for name, value in self.properties
  97. ]
  98. )
  99. return ""
  100. def record_testreport(self, testreport):
  101. assert not self.testcase
  102. names = mangle_test_address(testreport.nodeid)
  103. existing_attrs = self.attrs
  104. classnames = names[:-1]
  105. if self.xml.prefix:
  106. classnames.insert(0, self.xml.prefix)
  107. attrs = {
  108. "classname": ".".join(classnames),
  109. "name": bin_xml_escape(names[-1]),
  110. "file": testreport.location[0],
  111. }
  112. if testreport.location[1] is not None:
  113. attrs["line"] = testreport.location[1]
  114. if hasattr(testreport, "url"):
  115. attrs["url"] = testreport.url
  116. self.attrs = attrs
  117. self.attrs.update(existing_attrs) # restore any user-defined attributes
  118. # Preserve legacy testcase behavior
  119. if self.family == "xunit1":
  120. return
  121. # Filter out attributes not permitted by this test family.
  122. # Including custom attributes because they are not valid here.
  123. temp_attrs = {}
  124. for key in self.attrs.keys():
  125. if key in families[self.family]["testcase"]:
  126. temp_attrs[key] = self.attrs[key]
  127. self.attrs = temp_attrs
  128. def to_xml(self):
  129. testcase = Junit.testcase(time="%.3f" % self.duration, **self.attrs)
  130. testcase.append(self.make_properties_node())
  131. for node in self.nodes:
  132. testcase.append(node)
  133. return testcase
  134. def _add_simple(self, kind, message, data=None):
  135. data = bin_xml_escape(data)
  136. node = kind(data, message=message)
  137. self.append(node)
  138. def write_captured_output(self, report):
  139. if not self.xml.log_passing_tests and report.passed:
  140. return
  141. content_out = report.capstdout
  142. content_log = report.caplog
  143. content_err = report.capstderr
  144. if content_log or content_out:
  145. if content_log and self.xml.logging == "system-out":
  146. if content_out:
  147. # syncing stdout and the log-output is not done yet. It's
  148. # probably not worth the effort. Therefore, first the captured
  149. # stdout is shown and then the captured logs.
  150. content = "\n".join(
  151. [
  152. " Captured Stdout ".center(80, "-"),
  153. content_out,
  154. "",
  155. " Captured Log ".center(80, "-"),
  156. content_log,
  157. ]
  158. )
  159. else:
  160. content = content_log
  161. else:
  162. content = content_out
  163. if content:
  164. tag = getattr(Junit, "system-out")
  165. self.append(tag(bin_xml_escape(content)))
  166. if content_log or content_err:
  167. if content_log and self.xml.logging == "system-err":
  168. if content_err:
  169. content = "\n".join(
  170. [
  171. " Captured Stderr ".center(80, "-"),
  172. content_err,
  173. "",
  174. " Captured Log ".center(80, "-"),
  175. content_log,
  176. ]
  177. )
  178. else:
  179. content = content_log
  180. else:
  181. content = content_err
  182. if content:
  183. tag = getattr(Junit, "system-err")
  184. self.append(tag(bin_xml_escape(content)))
  185. def append_pass(self, report):
  186. self.add_stats("passed")
  187. def append_failure(self, report):
  188. # msg = str(report.longrepr.reprtraceback.extraline)
  189. if hasattr(report, "wasxfail"):
  190. self._add_simple(Junit.skipped, "xfail-marked test passes unexpectedly")
  191. else:
  192. if hasattr(report.longrepr, "reprcrash"):
  193. message = report.longrepr.reprcrash.message
  194. elif isinstance(report.longrepr, six.string_types):
  195. message = report.longrepr
  196. else:
  197. message = str(report.longrepr)
  198. message = bin_xml_escape(message)
  199. fail = Junit.failure(message=message)
  200. fail.append(bin_xml_escape(report.longrepr))
  201. self.append(fail)
  202. def append_collect_error(self, report):
  203. # msg = str(report.longrepr.reprtraceback.extraline)
  204. self.append(
  205. Junit.error(bin_xml_escape(report.longrepr), message="collection failure")
  206. )
  207. def append_collect_skipped(self, report):
  208. self._add_simple(Junit.skipped, "collection skipped", report.longrepr)
  209. def append_error(self, report):
  210. if report.when == "teardown":
  211. msg = "test teardown failure"
  212. else:
  213. msg = "test setup failure"
  214. self._add_simple(Junit.error, msg, report.longrepr)
  215. def append_skipped(self, report):
  216. if hasattr(report, "wasxfail"):
  217. xfailreason = report.wasxfail
  218. if xfailreason.startswith("reason: "):
  219. xfailreason = xfailreason[8:]
  220. self.append(
  221. Junit.skipped(
  222. "", type="pytest.xfail", message=bin_xml_escape(xfailreason)
  223. )
  224. )
  225. else:
  226. filename, lineno, skipreason = report.longrepr
  227. if skipreason.startswith("Skipped: "):
  228. skipreason = skipreason[9:]
  229. details = "%s:%s: %s" % (filename, lineno, skipreason)
  230. self.append(
  231. Junit.skipped(
  232. bin_xml_escape(details),
  233. type="pytest.skip",
  234. message=bin_xml_escape(skipreason),
  235. )
  236. )
  237. self.write_captured_output(report)
  238. def finalize(self):
  239. data = self.to_xml().unicode(indent=0)
  240. self.__dict__.clear()
  241. self.to_xml = lambda: py.xml.raw(data)
  242. def _warn_incompatibility_with_xunit2(request, fixture_name):
  243. """Emits a PytestWarning about the given fixture being incompatible with newer xunit revisions"""
  244. from _pytest.warning_types import PytestWarning
  245. xml = getattr(request.config, "_xml", None)
  246. if xml is not None and xml.family not in ("xunit1", "legacy"):
  247. request.node.warn(
  248. PytestWarning(
  249. "{fixture_name} is incompatible with junit_family '{family}' (use 'legacy' or 'xunit1')".format(
  250. fixture_name=fixture_name, family=xml.family
  251. )
  252. )
  253. )
  254. @pytest.fixture
  255. def record_property(request):
  256. """Add an extra properties the calling test.
  257. User properties become part of the test report and are available to the
  258. configured reporters, like JUnit XML.
  259. The fixture is callable with ``(name, value)``, with value being automatically
  260. xml-encoded.
  261. Example::
  262. def test_function(record_property):
  263. record_property("example_key", 1)
  264. """
  265. _warn_incompatibility_with_xunit2(request, "record_property")
  266. def append_property(name, value):
  267. request.node.user_properties.append((name, value))
  268. return append_property
  269. @pytest.fixture
  270. def record_xml_attribute(request):
  271. """Add extra xml attributes to the tag for the calling test.
  272. The fixture is callable with ``(name, value)``, with value being
  273. automatically xml-encoded
  274. """
  275. from _pytest.warning_types import PytestExperimentalApiWarning
  276. request.node.warn(
  277. PytestExperimentalApiWarning("record_xml_attribute is an experimental feature")
  278. )
  279. _warn_incompatibility_with_xunit2(request, "record_xml_attribute")
  280. # Declare noop
  281. def add_attr_noop(name, value):
  282. pass
  283. attr_func = add_attr_noop
  284. xml = getattr(request.config, "_xml", None)
  285. if xml is not None:
  286. node_reporter = xml.node_reporter(request.node.nodeid)
  287. attr_func = node_reporter.add_attribute
  288. return attr_func
  289. def _check_record_param_type(param, v):
  290. """Used by record_testsuite_property to check that the given parameter name is of the proper
  291. type"""
  292. __tracebackhide__ = True
  293. if not isinstance(v, six.string_types):
  294. msg = "{param} parameter needs to be a string, but {g} given"
  295. raise TypeError(msg.format(param=param, g=type(v).__name__))
  296. @pytest.fixture(scope="session")
  297. def record_testsuite_property(request):
  298. """
  299. Records a new ``<property>`` tag as child of the root ``<testsuite>``. This is suitable to
  300. writing global information regarding the entire test suite, and is compatible with ``xunit2`` JUnit family.
  301. This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:
  302. .. code-block:: python
  303. def test_foo(record_testsuite_property):
  304. record_testsuite_property("ARCH", "PPC")
  305. record_testsuite_property("STORAGE_TYPE", "CEPH")
  306. ``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.
  307. """
  308. __tracebackhide__ = True
  309. def record_func(name, value):
  310. """noop function in case --junitxml was not passed in the command-line"""
  311. __tracebackhide__ = True
  312. _check_record_param_type("name", name)
  313. xml = getattr(request.config, "_xml", None)
  314. if xml is not None:
  315. record_func = xml.add_global_property # noqa
  316. return record_func
  317. def pytest_addoption(parser):
  318. group = parser.getgroup("terminal reporting")
  319. group.addoption(
  320. "--junitxml",
  321. "--junit-xml",
  322. action="store",
  323. dest="xmlpath",
  324. metavar="path",
  325. type=functools.partial(filename_arg, optname="--junitxml"),
  326. default=None,
  327. help="create junit-xml style report file at given path.",
  328. )
  329. group.addoption(
  330. "--junitprefix",
  331. "--junit-prefix",
  332. action="store",
  333. metavar="str",
  334. default=None,
  335. help="prepend prefix to classnames in junit-xml output",
  336. )
  337. parser.addini(
  338. "junit_suite_name", "Test suite name for JUnit report", default="pytest"
  339. )
  340. parser.addini(
  341. "junit_logging",
  342. "Write captured log messages to JUnit report: "
  343. "one of no|system-out|system-err",
  344. default="no",
  345. ) # choices=['no', 'stdout', 'stderr'])
  346. parser.addini(
  347. "junit_log_passing_tests",
  348. "Capture log information for passing tests to JUnit report: ",
  349. type="bool",
  350. default=True,
  351. )
  352. parser.addini(
  353. "junit_duration_report",
  354. "Duration time to report: one of total|call",
  355. default="total",
  356. ) # choices=['total', 'call'])
  357. parser.addini(
  358. "junit_family",
  359. "Emit XML for schema: one of legacy|xunit1|xunit2",
  360. default="xunit1",
  361. )
  362. def pytest_configure(config):
  363. xmlpath = config.option.xmlpath
  364. # prevent opening xmllog on slave nodes (xdist)
  365. if xmlpath and not hasattr(config, "slaveinput"):
  366. config._xml = LogXML(
  367. xmlpath,
  368. config.option.junitprefix,
  369. config.getini("junit_suite_name"),
  370. config.getini("junit_logging"),
  371. config.getini("junit_duration_report"),
  372. config.getini("junit_family"),
  373. config.getini("junit_log_passing_tests"),
  374. )
  375. config.pluginmanager.register(config._xml)
  376. def pytest_unconfigure(config):
  377. xml = getattr(config, "_xml", None)
  378. if xml:
  379. del config._xml
  380. config.pluginmanager.unregister(xml)
  381. def mangle_test_address(address):
  382. path, possible_open_bracket, params = address.partition("[")
  383. names = path.split("::")
  384. try:
  385. names.remove("()")
  386. except ValueError:
  387. pass
  388. # convert file path to dotted path
  389. names[0] = names[0].replace(nodes.SEP, ".")
  390. names[0] = _py_ext_re.sub("", names[0])
  391. # put any params back
  392. names[-1] += possible_open_bracket + params
  393. return names
  394. class LogXML(object):
  395. def __init__(
  396. self,
  397. logfile,
  398. prefix,
  399. suite_name="pytest",
  400. logging="no",
  401. report_duration="total",
  402. family="xunit1",
  403. log_passing_tests=True,
  404. ):
  405. logfile = os.path.expanduser(os.path.expandvars(logfile))
  406. self.logfile = os.path.normpath(os.path.abspath(logfile))
  407. self.prefix = prefix
  408. self.suite_name = suite_name
  409. self.logging = logging
  410. self.log_passing_tests = log_passing_tests
  411. self.report_duration = report_duration
  412. self.family = family
  413. self.stats = dict.fromkeys(["error", "passed", "failure", "skipped"], 0)
  414. self.node_reporters = {} # nodeid -> _NodeReporter
  415. self.node_reporters_ordered = []
  416. self.global_properties = []
  417. # List of reports that failed on call but teardown is pending.
  418. self.open_reports = []
  419. self.cnt_double_fail_tests = 0
  420. # Replaces convenience family with real family
  421. if self.family == "legacy":
  422. self.family = "xunit1"
  423. def finalize(self, report):
  424. nodeid = getattr(report, "nodeid", report)
  425. # local hack to handle xdist report order
  426. slavenode = getattr(report, "node", None)
  427. reporter = self.node_reporters.pop((nodeid, slavenode))
  428. if reporter is not None:
  429. reporter.finalize()
  430. def node_reporter(self, report):
  431. nodeid = getattr(report, "nodeid", report)
  432. # local hack to handle xdist report order
  433. slavenode = getattr(report, "node", None)
  434. key = nodeid, slavenode
  435. if key in self.node_reporters:
  436. # TODO: breasks for --dist=each
  437. return self.node_reporters[key]
  438. reporter = _NodeReporter(nodeid, self)
  439. self.node_reporters[key] = reporter
  440. self.node_reporters_ordered.append(reporter)
  441. return reporter
  442. def add_stats(self, key):
  443. if key in self.stats:
  444. self.stats[key] += 1
  445. def _opentestcase(self, report):
  446. reporter = self.node_reporter(report)
  447. reporter.record_testreport(report)
  448. return reporter
  449. def pytest_runtest_logreport(self, report):
  450. """handle a setup/call/teardown report, generating the appropriate
  451. xml tags as necessary.
  452. note: due to plugins like xdist, this hook may be called in interlaced
  453. order with reports from other nodes. for example:
  454. usual call order:
  455. -> setup node1
  456. -> call node1
  457. -> teardown node1
  458. -> setup node2
  459. -> call node2
  460. -> teardown node2
  461. possible call order in xdist:
  462. -> setup node1
  463. -> call node1
  464. -> setup node2
  465. -> call node2
  466. -> teardown node2
  467. -> teardown node1
  468. """
  469. close_report = None
  470. if report.passed:
  471. if report.when == "call": # ignore setup/teardown
  472. reporter = self._opentestcase(report)
  473. reporter.append_pass(report)
  474. elif report.failed:
  475. if report.when == "teardown":
  476. # The following vars are needed when xdist plugin is used
  477. report_wid = getattr(report, "worker_id", None)
  478. report_ii = getattr(report, "item_index", None)
  479. close_report = next(
  480. (
  481. rep
  482. for rep in self.open_reports
  483. if (
  484. rep.nodeid == report.nodeid
  485. and getattr(rep, "item_index", None) == report_ii
  486. and getattr(rep, "worker_id", None) == report_wid
  487. )
  488. ),
  489. None,
  490. )
  491. if close_report:
  492. # We need to open new testcase in case we have failure in
  493. # call and error in teardown in order to follow junit
  494. # schema
  495. self.finalize(close_report)
  496. self.cnt_double_fail_tests += 1
  497. reporter = self._opentestcase(report)
  498. if report.when == "call":
  499. reporter.append_failure(report)
  500. self.open_reports.append(report)
  501. if not self.log_passing_tests:
  502. reporter.write_captured_output(report)
  503. else:
  504. reporter.append_error(report)
  505. elif report.skipped:
  506. reporter = self._opentestcase(report)
  507. reporter.append_skipped(report)
  508. self.update_testcase_duration(report)
  509. if report.when == "teardown":
  510. reporter = self._opentestcase(report)
  511. reporter.write_captured_output(report)
  512. for propname, propvalue in report.user_properties:
  513. reporter.add_property(propname, propvalue)
  514. self.finalize(report)
  515. report_wid = getattr(report, "worker_id", None)
  516. report_ii = getattr(report, "item_index", None)
  517. close_report = next(
  518. (
  519. rep
  520. for rep in self.open_reports
  521. if (
  522. rep.nodeid == report.nodeid
  523. and getattr(rep, "item_index", None) == report_ii
  524. and getattr(rep, "worker_id", None) == report_wid
  525. )
  526. ),
  527. None,
  528. )
  529. if close_report:
  530. self.open_reports.remove(close_report)
  531. def update_testcase_duration(self, report):
  532. """accumulates total duration for nodeid from given report and updates
  533. the Junit.testcase with the new total if already created.
  534. """
  535. if self.report_duration == "total" or report.when == self.report_duration:
  536. reporter = self.node_reporter(report)
  537. reporter.duration += getattr(report, "duration", 0.0)
  538. def pytest_collectreport(self, report):
  539. if not report.passed:
  540. reporter = self._opentestcase(report)
  541. if report.failed:
  542. reporter.append_collect_error(report)
  543. else:
  544. reporter.append_collect_skipped(report)
  545. def pytest_internalerror(self, excrepr):
  546. reporter = self.node_reporter("internal")
  547. reporter.attrs.update(classname="pytest", name="internal")
  548. reporter._add_simple(Junit.error, "internal error", excrepr)
  549. def pytest_sessionstart(self):
  550. self.suite_start_time = time.time()
  551. def pytest_sessionfinish(self):
  552. dirname = os.path.dirname(os.path.abspath(self.logfile))
  553. if not os.path.isdir(dirname):
  554. os.makedirs(dirname)
  555. logfile = open(self.logfile, "w", encoding="utf-8")
  556. suite_stop_time = time.time()
  557. suite_time_delta = suite_stop_time - self.suite_start_time
  558. numtests = (
  559. self.stats["passed"]
  560. + self.stats["failure"]
  561. + self.stats["skipped"]
  562. + self.stats["error"]
  563. - self.cnt_double_fail_tests
  564. )
  565. logfile.write('<?xml version="1.0" encoding="utf-8"?>')
  566. suite_node = Junit.testsuite(
  567. self._get_global_properties_node(),
  568. [x.to_xml() for x in self.node_reporters_ordered],
  569. name=self.suite_name,
  570. errors=self.stats["error"],
  571. failures=self.stats["failure"],
  572. skipped=self.stats["skipped"],
  573. tests=numtests,
  574. time="%.3f" % suite_time_delta,
  575. timestamp=datetime.fromtimestamp(self.suite_start_time).isoformat(),
  576. hostname=platform.node(),
  577. )
  578. logfile.write(Junit.testsuites([suite_node]).unicode(indent=0))
  579. logfile.close()
  580. def pytest_terminal_summary(self, terminalreporter):
  581. terminalreporter.write_sep("-", "generated xml file: %s" % (self.logfile))
  582. def add_global_property(self, name, value):
  583. __tracebackhide__ = True
  584. _check_record_param_type("name", name)
  585. self.global_properties.append((name, bin_xml_escape(value)))
  586. def _get_global_properties_node(self):
  587. """Return a Junit node containing custom properties, if any.
  588. """
  589. if self.global_properties:
  590. return Junit.properties(
  591. [
  592. Junit.property(name=name, value=value)
  593. for name, value in self.global_properties
  594. ]
  595. )
  596. return ""