junitxml.py 25 KB

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