Debian Codegraph @

src/_pytest/junitxml.py

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