Debian Codegraph @

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